diff --git a/2021/src/day3.rs b/2021/src/day3.rs index 1800580..3b1a9c7 100644 --- a/2021/src/day3.rs +++ b/2021/src/day3.rs @@ -1,7 +1,7 @@ use color_eyre::eyre; -fn most_common_bit(numbers: &Vec, pos: u8) -> u16 { +fn most_common_bit(numbers: &Vec, pos: u16) -> u16 { // number of times the bit in question is 1, // minus the number of times it's 0 let mask: u16 = 1 << pos; @@ -16,18 +16,9 @@ fn most_common_bit(numbers: &Vec, pos: u8) -> u16 { fn part1(numbers: &Vec) -> u64 { - let mut gamma = 0u16; - for i in 0..12 { - let mask = most_common_bit(numbers, i) << i; - gamma |= mask; - } - - // alternate solution: it feels super cool, but it's not any fewer lines than the above, and way less clear :( - // let gamma = (0..12) - // .fold( - // 0u16, - // |g, i| g | (most_common_bit(numbers, i) << i) - // ); + let gamma = (0..12).reduce(|g, i| + g | most_common_bit(numbers, i) << i + ).unwrap(); // unwrap is safe here since this iterator will always have elements // epsilon is just the bit inverse of gamma, but since these are really 12-bit numbers // we have to clear the 4 spurious 1's that come from inverting the original @@ -36,7 +27,7 @@ fn part1(numbers: &Vec) -> u64 { } -fn filter_bit_criteria(numbers: Vec, bit_pos: u8, bit_value: u16) -> Vec { +fn filter_bit_criteria(numbers: Vec, bit_pos: u16, bit_value: u16) -> Vec { numbers .into_iter() .filter(|n| (n >> bit_pos) & 1 == bit_value)