-
Notifications
You must be signed in to change notification settings - Fork 3
/
day_12.rs
119 lines (101 loc) Β· 3.06 KB
/
day_12.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
use std::collections::HashMap;
use common::{solution, Answer};
solution!("Hot Springs", 12);
fn part_a(input: &str) -> Answer {
parse(input)
.iter()
.map(|s| s.arrangements())
.sum::<usize>()
.into()
}
fn part_b(input: &str) -> Answer {
parse(input)
.iter()
.map(|s| s.expand().arrangements())
.sum::<usize>()
.into()
}
#[derive(Debug, Clone)]
struct Spring {
field: Vec<char>,
springs: Vec<usize>,
}
fn parse(input: &str) -> Vec<Spring> {
let mut out = Vec::new();
for line in input.lines() {
let (field, springs) = line.split_once(' ').unwrap();
let springs = springs
.split(',')
.map(|s| s.parse().unwrap())
.collect::<Vec<_>>();
let mut field = field.chars().collect::<Vec<_>>();
field.push('.');
out.push(Spring { field, springs });
}
out
}
impl Spring {
fn arrangements(&self) -> usize {
fn count(
memo: &mut HashMap<(usize, usize, usize), usize>,
spring: &Spring,
pos: usize,
block: usize,
sequences: usize,
) -> usize {
if let Some(&res) = memo.get(&(pos, block, sequences)) {
return res;
}
let mut res = 0;
if pos == spring.field.len() {
res = (sequences == spring.springs.len()) as usize;
} else if spring.field[pos] == '#' {
res = count(memo, spring, pos + 1, block + 1, sequences)
} else if spring.field[pos] == '.' || sequences == spring.springs.len() {
if sequences < spring.springs.len() && block == spring.springs[sequences] {
res = count(memo, spring, pos + 1, 0, sequences + 1)
} else if block == 0 {
res = count(memo, spring, pos + 1, 0, sequences)
}
} else {
res += count(memo, spring, pos + 1, block + 1, sequences);
if block == spring.springs[sequences] {
res += count(memo, spring, pos + 1, 0, sequences + 1)
} else if block == 0 {
res += count(memo, spring, pos + 1, 0, sequences)
}
}
memo.insert((pos, block, sequences), res);
res
}
count(&mut HashMap::new(), self, 0, 0, 0)
}
fn expand(&self) -> Self {
let mut new_field = self.field.clone();
*new_field.last_mut().unwrap() = '?';
Self {
field: new_field.repeat(5),
springs: self.springs.repeat(5),
}
}
}
#[cfg(test)]
mod test {
use indoc::indoc;
const CASE: &str = indoc! {"
???.### 1,1,3
.??..??...?##. 1,1,3
?#?#?#?#?#?#?#? 1,3,1,6
????.#...#... 4,1,1
????.######..#####. 1,6,5
?###???????? 3,2,1
"};
#[test]
fn part_a() {
assert_eq!(super::part_a(CASE), 21.into());
}
#[test]
fn part_b() {
assert_eq!(super::part_b(CASE), 525152.into());
}
}