-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday19.rs
81 lines (67 loc) · 1.71 KB
/
day19.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//! [Day 19: Linen Layout](https://adventofcode.com/2024/day/19)
struct Puzzle<'a> {
patterns: Vec<&'a str>,
designs: Vec<&'a str>,
}
impl<'a> Puzzle<'a> {
fn new(data: &'a str) -> Self {
let (patterns, designs) = data.split_once("\n\n").unwrap();
Self {
patterns: patterns.split(", ").collect(),
designs: designs.lines().collect(),
}
}
fn count_design_ways(&self, design: &str) -> u64 {
let n = design.len();
let mut dp = vec![0; n + 1];
dp[0] = 1;
for i in 1..=n {
for pattern in &self.patterns {
let m = pattern.len();
if i >= m && &&design[i - m..i] == pattern {
dp[i] += dp[i - m];
}
}
}
dp[n]
}
/// Solve part one.
fn part1(&self) -> usize {
self.designs
.iter()
.filter(|design| self.count_design_ways(design) != 0)
.count()
}
/// Solve part two.
fn part2(&self) -> u64 {
self.designs
.iter()
.map(|design| self.count_design_ways(design))
.sum()
}
}
/// # Panics
#[must_use]
pub fn solve(data: &str) -> (usize, u64) {
let puzzle = Puzzle::new(data);
(puzzle.part1(), puzzle.part2())
}
pub fn main() {
let args = aoc::parse_args();
args.run(solve);
}
#[cfg(test)]
mod test {
use super::*;
const TEST_INPUT: &str = include_str!("test.txt");
#[test]
fn test01() {
let puzzle = Puzzle::new(TEST_INPUT);
assert_eq!(puzzle.part1(), 6);
}
#[test]
fn test02() {
let puzzle = Puzzle::new(TEST_INPUT);
assert_eq!(puzzle.part2(), 16);
}
}