diff --git a/aoc2021/aoc2021_bench/benches/aoc2021_bench.rs b/aoc2021/aoc2021_bench/benches/aoc2021_bench.rs index f4475d2..05cb02e 100644 --- a/aoc2021/aoc2021_bench/benches/aoc2021_bench.rs +++ b/aoc2021/aoc2021_bench/benches/aoc2021_bench.rs @@ -1,13 +1,9 @@ use criterion::{criterion_group, criterion_main, Criterion}; use aoc2021::day01; -use aoc2021::day02; -use aoc2021::day03; fn aoc2021_all(c: &mut Criterion) { c.bench_function("day01", |b| b.iter(|| day01::run().unwrap())); - c.bench_function("day02", |b| b.iter(|| day02::run().unwrap())); - c.bench_function("day03", |b| b.iter(|| day03::run().unwrap())); } criterion_group! { diff --git a/aoc2021/src/day03.rs b/aoc2021/src/day03.rs index 69989e5..dc97d18 100644 --- a/aoc2021/src/day03.rs +++ b/aoc2021/src/day03.rs @@ -73,10 +73,12 @@ fn part2(input: &str) -> Result { Ok(oxygen_generator_rating * co2_scrubber_rating) } -fn filter_by_strat(binary_numbers: &[&str], size: usize, strat: Strat) -> Result -where - Strat: Fn(bool) -> char, -{ +enum FilterStrategy { + MostCommon, + LeastCommon, +} + +fn filter_by_strat(binary_numbers: &[&str], size: usize, strat: FilterStrategy) -> Result { let mut numbers = binary_numbers.to_vec(); for pos in 0..size { @@ -85,8 +87,19 @@ where break; } - let one_is_more_common = count_ones(&numbers, pos) >= ((numbers.len() + 1) / 2); - let digit_of_interest = strat(one_is_more_common); + let digit_of_interest = if count_ones(&numbers, pos) >= ((numbers.len() + 1) / 2) { + // majority of ones, or equality + match strat { + FilterStrategy::MostCommon => '1', + FilterStrategy::LeastCommon => '0', + } + } else { + // majority of zeroes + match strat { + FilterStrategy::MostCommon => '0', + FilterStrategy::LeastCommon => '1', + } + }; // TODO: use drain_filter when stable let mut i = 0; @@ -108,26 +121,14 @@ where /// position, and keep only numbers with that bit in that position. If 0 and 1 are equally common, /// keep values with a 1 in the position being considered. fn compute_oxygen_generator_rating(binary_numbers: &[&str], size: usize) -> Result { - filter_by_strat(binary_numbers, size, |one_is_more_common| { - if one_is_more_common { - '1' - } else { - '0' - } - }) + filter_by_strat(binary_numbers, size, FilterStrategy::MostCommon) } /// To find CO2 scrubber rating, determine the least common value (0 or 1) in the current bit /// position, and keep only numbers with that bit in that position. If 0 and 1 are equally /// common, keep values with a 0 in the position being considered. fn compute_co2_scrubber_rating(binary_numbers: &[&str], size: usize) -> Result { - filter_by_strat(binary_numbers, size, |one_is_more_common| { - if one_is_more_common { - '0' - } else { - '1' - } - }) + filter_by_strat(binary_numbers, size, FilterStrategy::LeastCommon) } #[cfg(test)]