Skip to content

Commit 7079138

Browse files
committed
Day 19
1 parent a9012ec commit 7079138

File tree

2 files changed

+111
-0
lines changed

2 files changed

+111
-0
lines changed

data/examples/19.txt

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
r, wr, b, g, bwu, rb, gb, br
2+
3+
brwrr
4+
bggr
5+
gbbr
6+
rrbgbr
7+
ubwu
8+
bwurrg
9+
brgr
10+
bbrgwb

src/bin/19.rs

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
use std::collections::HashMap;
2+
3+
advent_of_code::solution!(19);
4+
5+
pub fn part_one(input: &str) -> Option<u32> {
6+
let mut lines = input.lines();
7+
let towels: Vec<&str> = lines.next().unwrap().split(", ").collect();
8+
lines.next(); // Skip empty line
9+
10+
let mut memo: HashMap<&str, bool> = HashMap::new();
11+
12+
Some(
13+
lines
14+
.filter_map(|line| {
15+
if get_if_possible(line, &towels, &mut memo) {
16+
Some(1)
17+
} else {
18+
None
19+
}
20+
})
21+
.sum(),
22+
)
23+
}
24+
25+
fn get_num_possible_combinations<'a>(
26+
towel: &'a str,
27+
possible_towels: &[&str],
28+
memo: &mut HashMap<&'a str, u64>,
29+
) -> u64 {
30+
if towel.is_empty() {
31+
return 1;
32+
}
33+
if memo.contains_key(towel) {
34+
return memo[towel];
35+
}
36+
let p = possible_towels
37+
.iter()
38+
.map(|pt| {
39+
if let Some(new_towel) = towel.strip_prefix(pt) {
40+
get_num_possible_combinations(new_towel, possible_towels, memo)
41+
} else {
42+
0
43+
}
44+
})
45+
.sum();
46+
memo.insert(towel, p);
47+
p
48+
}
49+
50+
fn get_if_possible<'a>(
51+
towel: &'a str,
52+
possible_towels: &[&str],
53+
memo: &mut HashMap<&'a str, bool>,
54+
) -> bool {
55+
if towel.is_empty() {
56+
return true;
57+
}
58+
if memo.contains_key(towel) {
59+
return memo[towel];
60+
}
61+
let p = possible_towels.iter().any(|pt| {
62+
if let Some(new_towel) = towel.strip_prefix(pt) {
63+
get_if_possible(new_towel, possible_towels, memo)
64+
} else {
65+
false
66+
}
67+
});
68+
memo.insert(towel, p);
69+
p
70+
}
71+
72+
pub fn part_two(input: &str) -> Option<u64> {
73+
let mut lines = input.lines();
74+
let towels: Vec<&str> = lines.next().unwrap().split(", ").collect();
75+
lines.next(); // Skip empty line
76+
77+
let mut memo: HashMap<&str, u64> = HashMap::new();
78+
79+
Some(
80+
lines
81+
.map(|line| get_num_possible_combinations(line, &towels, &mut memo))
82+
.sum(),
83+
)
84+
}
85+
86+
#[cfg(test)]
87+
mod tests {
88+
use super::*;
89+
90+
#[test]
91+
fn test_part_one() {
92+
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
93+
assert_eq!(result, Some(6));
94+
}
95+
96+
#[test]
97+
fn test_part_two() {
98+
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
99+
assert_eq!(result, Some(16));
100+
}
101+
}

0 commit comments

Comments
 (0)