From 8551abf624eb064c7cf93634f86ab9d40276f961 Mon Sep 17 00:00:00 2001 From: Johannes Date: Thu, 27 Jun 2024 23:00:54 +0200 Subject: [PATCH] Day 17 part 2. --- src/day17.rs | 50 ++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 40 insertions(+), 10 deletions(-) diff --git a/src/day17.rs b/src/day17.rs index 0367614..cabb877 100644 --- a/src/day17.rs +++ b/src/day17.rs @@ -7,37 +7,67 @@ fn parse(input: &str) -> Vec { #[aoc(day17, part1)] fn part1(input: &[u32]) -> usize { - bar(input, 150) + bar1(input, 150) } -fn bar(containers: &[u32], target: u32) -> usize { - baz(containers, target, 0) +fn bar1(containers: &[u32], target: u32) -> usize { + baz1(containers, target, 0) } -fn baz(containers: &[u32], target: u32, filled: u32) -> usize { +fn baz1(containers: &[u32], target: u32, filled: u32) -> usize { if filled > target { return 0; } else if filled == target { return 1; - } else if containers.len() == 0 { + } else if containers.is_empty() { return 0; } - baz(&containers[1..], target, filled + containers[0]) - + baz(&containers[1..], target, filled) + baz1(&containers[1..], target, filled + containers[0]) + baz1(&containers[1..], target, filled) +} + +fn bar2(containers: &[u32], target: u32) -> usize { + let mut counts = vec![0; containers.len() + 1]; + baz2(containers, target, 0, 0, &mut counts); + counts.into_iter().find(|count| *count > 0).unwrap() +} + +fn baz2(containers: &[u32], target: u32, filled: u32, count: usize, counts: &mut [usize]) { + if filled > target { + return; + } else if filled == target { + counts[count] += 1; + return; + } else if containers.is_empty() { + return; + } + + baz2( + &containers[1..], + target, + filled + containers[0], + count + 1, + counts, + ); + baz2(&containers[1..], target, filled, count, counts); } #[aoc(day17, part2)] fn part2(_input: &[u32]) -> usize { - 0 + bar2(_input, 150) } #[cfg(test)] mod test { - use crate::day17::bar; + use crate::day17::{bar1, bar2}; #[test] fn part1() { - assert_eq!(bar(&[20, 15, 10, 5, 5], 25), 4) + assert_eq!(bar1(&[20, 15, 10, 5, 5], 25), 4) + } + + #[test] + fn part2() { + assert_eq!(bar2(&[20, 15, 10, 5, 5], 25), 3) } }