From b6111fe33729b8aaef5ddd89f0804d8e29ac5776 Mon Sep 17 00:00:00 2001 From: Andrew Coleman Date: Wed, 27 Dec 2023 17:05:57 -0500 Subject: [PATCH] day15 solution --- 2023/src/day15.rs | 64 +++++++++++++++++++++++++++++++++++++++++++++++ 2023/src/lib.rs | 1 + 2 files changed, 65 insertions(+) create mode 100644 2023/src/day15.rs diff --git a/2023/src/day15.rs b/2023/src/day15.rs new file mode 100644 index 0000000..a4be8e2 --- /dev/null +++ b/2023/src/day15.rs @@ -0,0 +1,64 @@ +use aoc_runner_derive::aoc; + +fn hash(input: &str) -> usize { + let mut cur: usize = 0; + for c in input.chars() { + cur = ((cur + c as usize) * 17) % 256; + } + cur +} + +#[aoc(day15, part1)] +fn part1(input: &str) -> usize { + input.trim_end().split(",").map(|t| hash(t)).sum() +} + +#[aoc(day15, part2)] +fn part2(input: &str) -> usize { + let mut boxes: Vec> = vec![]; + for _ in 0..256 { + boxes.push(vec![]); + } + for lens in input.trim_end().split(",") { + if lens.contains("-") { + let parts = lens.split("-").collect::>(); + let h = hash(parts[0]); + if let Some(index) = boxes[h].iter().position(|t| t.0 == parts[0]) { + boxes[h].remove(index); + } + } else { + let parts = lens.split("=").collect::>(); + let h = hash(parts[0]); + let n = (parts[0], parts[1].parse::().unwrap()); + if let Some(index) = boxes[h].iter().position(|t| t.0 == parts[0]) { + boxes[h][index].1 = n.1; + } else { + boxes[h].push(n); + } + } + } + + let mut sum = 0; + for (box_index, b) in boxes.iter().enumerate() { + if b.is_empty() { + continue; + } + for (index, lens) in b.iter().enumerate() { + sum += (box_index + 1) * (index + 1) * lens.1; + } + } + sum +} + +#[cfg(test)] +mod tests { + use super::*; + + const SAMPLE_DATA: &'static str = "rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7"; + + #[test] + fn sample_data() { + assert_eq!(part1(&SAMPLE_DATA), 1320); + assert_eq!(part2(&SAMPLE_DATA), 145); + } +} diff --git a/2023/src/lib.rs b/2023/src/lib.rs index 605e6fa..8376a12 100644 --- a/2023/src/lib.rs +++ b/2023/src/lib.rs @@ -14,5 +14,6 @@ mod day11; mod day12; mod day13; mod day14; +mod day15; aoc_lib! { year = 2023 }