From 00000120504524323dbec217dfc2cf3ea5b2f956 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Jane=C5=BEi=C4=8D?= Date: Thu, 28 Nov 2024 03:20:19 +0100 Subject: [PATCH] solution: day 9 --- src/bin/09.rs | 79 +++++++++++++++++++++++++++++++++++++++++++++ src/examples/09.txt | 1 + 2 files changed, 80 insertions(+) create mode 100644 src/bin/09.rs create mode 100644 src/examples/09.txt diff --git a/src/bin/09.rs b/src/bin/09.rs new file mode 100644 index 0000000000..711c185 --- /dev/null +++ b/src/bin/09.rs @@ -0,0 +1,79 @@ +use itertools::Itertools; + +fn decompress(input: &str, recursive: bool) -> usize { + let mut stack = input + .chars() + .filter(|x| !x.is_whitespace()) + .rev() + .collect_vec(); + + let mut drained = vec![]; + let mut count = 0; + + while let Some(c) = stack.pop() { + if c == '(' { + let mut n = 0; + let sublen = loop { + let l = stack.pop().unwrap(); + if l == 'x' { + break n; + } + n = n * 10 + l.to_digit(10).unwrap() as usize; + }; + + let mut n = 0; + let repeat = loop { + let l = stack.pop().unwrap(); + if l == ')' { + break n; + } + n = n * 10 + l.to_digit(10).unwrap() as usize; + }; + + drained.clear(); + + for _ in 0..sublen { + drained.push(stack.pop().unwrap()); + } + + if recursive { + for _ in 0..repeat { + for d in drained.iter().copied().rev() { + stack.push(d); + } + } + } else { + count += drained.len() * repeat + } + } else { + count += 1 + } + } + + count +} + +pub fn part_one(input: &str) -> Option { + Some(decompress(input, false)) +} +pub fn part_two(input: &str) -> Option { + Some(decompress(input, true)) +} +fn main() { + let input = &aoc::read_file("inputs", 9); + aoc::solve!(part_one, part_two, input); +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn test_part_one() { + let input = aoc::read_file("examples", 9); + assert_eq!(part_one(&input), Some(238)); + } + #[test] + fn test_part_two() { + let input = aoc::read_file("examples", 9); + assert_eq!(part_two(&input), Some(445)); + } +} diff --git a/src/examples/09.txt b/src/examples/09.txt new file mode 100644 index 0000000000..8ccbf77 --- /dev/null +++ b/src/examples/09.txt @@ -0,0 +1 @@ +(25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN