use the fun functional approach
This commit is contained in:
parent
340ef2d4d3
commit
c55a721067
@ -1,7 +1,7 @@
|
|||||||
use color_eyre::eyre;
|
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,
|
// number of times the bit in question is 1,
|
||||||
// minus the number of times it's 0
|
// minus the number of times it's 0
|
||||||
let mask: u16 = 1 << pos;
|
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 {
|
fn part1(numbers: &Vec<u16>) -> u64 {
|
||||||
let mut gamma = 0u16;
|
let gamma = (0..12).reduce(|g, i|
|
||||||
for i in 0..12 {
|
g | most_common_bit(numbers, i) << i
|
||||||
let mask = most_common_bit(numbers, i) << i;
|
).unwrap(); // unwrap is safe here since this iterator will always have elements
|
||||||
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)
|
|
||||||
// );
|
|
||||||
|
|
||||||
// epsilon is just the bit inverse of gamma, but since these are really 12-bit numbers
|
// 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
|
// 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
|
numbers
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|n| (n >> bit_pos) & 1 == bit_value)
|
.filter(|n| (n >> bit_pos) & 1 == bit_value)
|
||||||
|
Loading…
x
Reference in New Issue
Block a user