use the fun functional approach

This commit is contained in:
Joseph Montanaro 2021-12-06 08:59:20 -08:00
parent 340ef2d4d3
commit c55a721067

View File

@ -1,7 +1,7 @@
use color_eyre::eyre;
fn most_common_bit(numbers: &Vec<u16>, pos: u8) -> u16 {
fn most_common_bit(numbers: &Vec<u16>, 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<u16>, pos: u8) -> u16 {
fn part1(numbers: &Vec<u16>) -> 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<u16>) -> u64 {
}
fn filter_bit_criteria(numbers: Vec<u16>, bit_pos: u8, bit_value: u16) -> Vec<u16> {
fn filter_bit_criteria(numbers: Vec<u16>, bit_pos: u16, bit_value: u16) -> Vec<u16> {
numbers
.into_iter()
.filter(|n| (n >> bit_pos) & 1 == bit_value)