From b1a8ab8bcdb43ad282af80189763476f3ac427f2 Mon Sep 17 00:00:00 2001 From: Joseph Montanaro Date: Fri, 3 Dec 2021 14:48:34 -0800 Subject: [PATCH] refactor in preparation for part 2 --- 2021/src/day3.rs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/2021/src/day3.rs b/2021/src/day3.rs index 4902b93..51189e2 100644 --- a/2021/src/day3.rs +++ b/2021/src/day3.rs @@ -1,7 +1,7 @@ use color_eyre::eyre; -pub fn part1(numbers: &Vec) -> u64 { +fn most_common_bits(numbers: &Vec) -> u16 { let mut bit_diffs: [isize; 12] = [0; 12]; for num in numbers { for i in 0..11 { @@ -14,13 +14,24 @@ pub fn part1(numbers: &Vec) -> u64 { } } - let mut gamma = 0u16; + let mut result = 0u16; for (i, sum) in bit_diffs.iter().enumerate() { let bit = if *sum >= 0 {1} else {0}; - gamma |= bit << i; + result |= 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 + result +} + + +fn invert_12bit(n: u16) -> u16 { + !n & (65535 >> 4) // since these are really only 12-bit numbers we have to clear the 4 spurious 1's that come from inverting the original +} + + +fn part1(numbers: &Vec) -> u64 { + let gamma = most_common_bits(numbers); + let epsilon = invert_12bit(gamma); epsilon as u64 * gamma as u64 }