diff options
author | Jesse Luehrs <doy@tozt.net> | 2023-12-04 02:52:50 -0500 |
---|---|---|
committer | Jesse Luehrs <doy@tozt.net> | 2023-12-04 02:52:50 -0500 |
commit | 8cd0d842f0ffb0750f2df7dcee8c29c800d7c8af (patch) | |
tree | fa2fb4406cc435600abff3b4917dfb35cfa60396 /src/bin | |
parent | 6c05e1f8daffabd71be5aac7c0bc9d7586b5c359 (diff) | |
download | advent-of-code-8cd0d842f0ffb0750f2df7dcee8c29c800d7c8af.tar.gz advent-of-code-8cd0d842f0ffb0750f2df7dcee8c29c800d7c8af.zip |
day 4
Diffstat (limited to 'src/bin')
-rw-r--r-- | src/bin/2023/day4.rs | 58 | ||||
-rw-r--r-- | src/bin/2023/main.rs | 2 |
2 files changed, 60 insertions, 0 deletions
diff --git a/src/bin/2023/day4.rs b/src/bin/2023/day4.rs new file mode 100644 index 0000000..a93a1d2 --- /dev/null +++ b/src/bin/2023/day4.rs @@ -0,0 +1,58 @@ +#![allow(dead_code)] +#![allow(unused_variables)] + +use advent_of_code::prelude::*; + +pub fn parse(fh: File) -> Result<Vec<(HashSet<i64>, HashSet<i64>)>> { + Ok(parse::raw_lines(fh) + .map(|line| { + let line = line.split(": ").nth(1).unwrap(); + let mut parts = line.split(" | "); + let winning = parts.next().unwrap(); + let ours = parts.next().unwrap(); + ( + winning + .split_whitespace() + .map(|s| s.parse().unwrap()) + .collect(), + ours.split_whitespace() + .map(|s| s.parse().unwrap()) + .collect(), + ) + }) + .collect()) +} + +pub fn part1(cards: Vec<(HashSet<i64>, HashSet<i64>)>) -> Result<i64> { + let mut total = 0; + for (winning, ours) in cards { + let matches = (&ours & &winning).len(); + if matches > 0 { + total += 2i64.pow((matches - 1).try_into().unwrap()); + } + } + Ok(total) +} + +pub fn part2(cards: Vec<(HashSet<i64>, HashSet<i64>)>) -> Result<i64> { + let mut counts = vec![1; cards.len()]; + for (i, (winning, ours)) in cards.into_iter().enumerate() { + let matches = (&ours & &winning).len(); + for prize in 0..matches { + counts[i + 1 + prize] += counts[i]; + } + } + Ok(counts.iter().sum()) +} + +#[test] +fn test() { + assert_eq!( + part1(parse(parse::data(2023, 4).unwrap()).unwrap()).unwrap(), + 25183 + ); + assert_eq!( + part2(parse(parse::data(2023, 4).unwrap()).unwrap()).unwrap(), + 5667240 + ); +} diff --git a/src/bin/2023/main.rs b/src/bin/2023/main.rs index 652bf26..4033702 100644 --- a/src/bin/2023/main.rs +++ b/src/bin/2023/main.rs @@ -14,6 +14,7 @@ use advent_of_code::prelude::*; mod day1; mod day2; mod day3; +mod day4; // NEXT MOD #[paw::main] @@ -23,6 +24,7 @@ fn main(opt: Opt) -> Result<()> { 1 => advent_of_code::day!(2023, opt.day, opt.puzzle, day1), 2 => advent_of_code::day!(2023, opt.day, opt.puzzle, day2), 3 => advent_of_code::day!(2023, opt.day, opt.puzzle, day3), + 4 => advent_of_code::day!(2023, opt.day, opt.puzzle, day4), // NEXT PART _ => panic!("unknown day {}", opt.day), } |