day 3 part 1
This commit is contained in:
parent
335b7a25cf
commit
b519e0bad2
36
2021/src/day3.rs
Normal file
36
2021/src/day3.rs
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
use color_eyre::eyre;
|
||||||
|
|
||||||
|
|
||||||
|
pub fn part1(numbers: &Vec<u16>) -> u64 {
|
||||||
|
let mut bit_diffs: [isize; 12] = [0; 12];
|
||||||
|
for num in numbers {
|
||||||
|
for i in 0..11 {
|
||||||
|
if num & (1 << i) > 0 {
|
||||||
|
bit_diffs[i] += 1
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
bit_diffs[i] -= 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut gamma = 0u16;
|
||||||
|
for (i, sum) in bit_diffs.iter().enumerate() {
|
||||||
|
let bit = if *sum >= 0 {1} else {0};
|
||||||
|
gamma |= bit << i;
|
||||||
|
}
|
||||||
|
|
||||||
|
let epsilon = !gamma & (65535 >> 4); // since these are really only 12-bit numbers we have to clear the 4 spurious 1's that come from inverting epsilon
|
||||||
|
epsilon as u64 * gamma as u64
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
pub fn run(data: &str) -> eyre::Result<()> {
|
||||||
|
let mut nums = Vec::new();
|
||||||
|
for line in data.lines() {
|
||||||
|
nums.push(u16::from_str_radix(line, 2)?);
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("One: {}", part1(&nums));
|
||||||
|
Ok(())
|
||||||
|
}
|
@ -4,13 +4,13 @@ use color_eyre::eyre;
|
|||||||
|
|
||||||
mod lib;
|
mod lib;
|
||||||
use lib::load;
|
use lib::load;
|
||||||
mod day2;
|
mod day3;
|
||||||
|
|
||||||
|
|
||||||
fn main() -> eyre::Result<()> {
|
fn main() -> eyre::Result<()> {
|
||||||
let data = load("data/02.txt")?;
|
let data = load("data/03.txt")?;
|
||||||
let start = Instant::now();
|
let start = Instant::now();
|
||||||
day2::run(&data)?;
|
day3::run(&data)?;
|
||||||
let (dur, unit) = format_ns(start.elapsed().as_nanos());
|
let (dur, unit) = format_ns(start.elapsed().as_nanos());
|
||||||
println!("Completed in {}{}", dur, unit);
|
println!("Completed in {}{}", dur, unit);
|
||||||
Ok(())
|
Ok(())
|
||||||
|
Loading…
x
Reference in New Issue
Block a user