|
| 1 | +#![allow(non_snake_case)] |
| 2 | + |
| 3 | +use aoc::Puzzle; |
| 4 | +use std::collections::HashMap; |
| 5 | + |
| 6 | +struct AoC2024_19 {} |
| 7 | + |
| 8 | +impl AoC2024_19 { |
| 9 | + #[allow(clippy::only_used_in_recursion)] |
| 10 | + fn count( |
| 11 | + &self, |
| 12 | + cache: &mut HashMap<String, usize>, |
| 13 | + design: String, |
| 14 | + towels: &[String], |
| 15 | + ) -> usize { |
| 16 | + if let Some(ans) = cache.get(&design) { |
| 17 | + return *ans; |
| 18 | + } |
| 19 | + if design.is_empty() { |
| 20 | + return 1; |
| 21 | + } |
| 22 | + let ans = towels |
| 23 | + .iter() |
| 24 | + .filter(|towel| design.starts_with(*towel)) |
| 25 | + .map(|towel| { |
| 26 | + self.count(cache, String::from(&design[towel.len()..]), towels) |
| 27 | + }) |
| 28 | + .sum(); |
| 29 | + cache.insert(design, ans); |
| 30 | + ans |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +impl aoc::Puzzle for AoC2024_19 { |
| 35 | + type Input = (Vec<String>, Vec<String>); |
| 36 | + type Output1 = usize; |
| 37 | + type Output2 = usize; |
| 38 | + |
| 39 | + aoc::puzzle_year_day!(2024, 19); |
| 40 | + |
| 41 | + fn parse_input(&self, lines: Vec<String>) -> Self::Input { |
| 42 | + let towels = lines[0].split(", ").map(String::from).collect(); |
| 43 | + let designs = lines[2..].to_vec(); |
| 44 | + (towels, designs) |
| 45 | + } |
| 46 | + |
| 47 | + fn part_1(&self, input: &Self::Input) -> Self::Output1 { |
| 48 | + let (towels, designs) = input; |
| 49 | + let mut cache: HashMap<String, usize> = HashMap::new(); |
| 50 | + designs |
| 51 | + .iter() |
| 52 | + .filter(|design| { |
| 53 | + self.count(&mut cache, String::from(*design), towels) > 0 |
| 54 | + }) |
| 55 | + .count() |
| 56 | + } |
| 57 | + |
| 58 | + fn part_2(&self, input: &Self::Input) -> Self::Output2 { |
| 59 | + let (towels, designs) = input; |
| 60 | + let mut cache: HashMap<String, usize> = HashMap::new(); |
| 61 | + designs |
| 62 | + .iter() |
| 63 | + .map(|design| self.count(&mut cache, String::from(design), towels)) |
| 64 | + .sum() |
| 65 | + } |
| 66 | + |
| 67 | + fn samples(&self) { |
| 68 | + aoc::puzzle_samples! { |
| 69 | + self, part_1, TEST, 6, |
| 70 | + self, part_2, TEST, 16 |
| 71 | + }; |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +fn main() { |
| 76 | + AoC2024_19 {}.run(std::env::args()); |
| 77 | +} |
| 78 | + |
| 79 | +const TEST: &str = "\ |
| 80 | +r, wr, b, g, bwu, rb, gb, br |
| 81 | +
|
| 82 | +brwrr |
| 83 | +bggr |
| 84 | +gbbr |
| 85 | +rrbgbr |
| 86 | +ubwu |
| 87 | +bwurrg |
| 88 | +brgr |
| 89 | +bbrgwb |
| 90 | +"; |
| 91 | + |
| 92 | +#[cfg(test)] |
| 93 | +mod tests { |
| 94 | + use super::*; |
| 95 | + |
| 96 | + #[test] |
| 97 | + pub fn samples() { |
| 98 | + AoC2024_19 {}.samples(); |
| 99 | + } |
| 100 | +} |
0 commit comments