summaryrefslogtreecommitdiff
path: root/2023/src/bin/day_12.rs
blob: e60b450de5e6a8b79db79c799e4c68d9d9118400 (plain)
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
use nom::{
    branch::alt,
    character::complete::{char, line_ending, space1, u32},
    combinator::{map, value},
    multi::{many1, many1_count, separated_list1},
    sequence::separated_pair,
    IResult,
};
use std::{collections::BTreeMap, fs};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let input = fs::read_to_string("inputs/day_12.txt")?;
    let small = SpringField::parser(&input).unwrap().1;
    dbg!(&small.possibilities_sum());

    let large = small.expand();
    dbg!(&large.possibilities_sum());

    Ok(())
}

#[derive(Debug)]
struct SpringField(Vec<SpringRow>);

#[derive(Debug, Clone)]
struct SpringRow {
    springs: Vec<Spring>,
    check: Vec<u32>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Spring {
    Good,
    Bad(usize),
    Unknown,
}

impl SpringField {
    fn parser(input: &str) -> IResult<&str, Self> {
        map(separated_list1(line_ending, SpringRow::parser), SpringField)(input)
    }

    fn possibilities_sum(&self) -> usize {
        self.0.iter().map(|r| r.possibilities_count()).sum()
    }

    fn expand(&self) -> SpringField {
        SpringField(self.0.iter().map(|r| r.expand()).collect())
    }
}

impl SpringRow {
    fn parser(input: &str) -> IResult<&str, Self> {
        map(
            separated_pair(
                many1(Spring::parser),
                space1,
                separated_list1(char(','), u32),
            ),
            |(springs, check)| SpringRow { springs, check },
        )(input)
    }

    fn expand(&self) -> SpringRow {
        let mut expanded = SpringRow {
            springs: Vec::new(),
            check: Vec::new(),
        };

        for _ in 0..5 {
            expanded.springs.append(&mut self.springs.clone());
            expanded.springs.push(Spring::Unknown);
            expanded.check.append(&mut self.check.clone());
        }

        // should only have the extra Unknown between, not at the very end.
        expanded.springs.pop();

        expanded
    }

    fn possibilities_count(&self) -> usize {
        let optimized = self.optimize_tail();
        optimized.possibilities_count_inner(0, 0, &mut BTreeMap::new())
    }

    fn optimize_tail(&self) -> SpringRow {
        let mut optimized = self.clone();
        while optimized.springs.len() > 0 && optimized.check.len() > 0 {
            match optimized.springs[optimized.springs.len() - 1] {
                Spring::Good => {
                    optimized.springs.pop();
                }
                Spring::Bad(s) if s > optimized.check[optimized.check.len() - 1] as usize => {
                    panic!("Unsolvable row");
                }
                Spring::Bad(s) if s <= optimized.check[optimized.check.len() - 1] as usize => {
                    optimized.trim_bad_suffix();
                }
                Spring::Bad(_) => unreachable!(),
                Spring::Unknown => {
                    break;
                }
            }
        }

        optimized
    }

    fn trim_bad_suffix(&mut self) {
        let last_check = self.check.pop().expect("No trailing check to pop") as usize;
        let mut check_i = 0;
        while check_i < last_check {
            match self
                .springs
                .pop()
                .expect("Ran out of springs while optimizing suffix!")
            {
                Spring::Unknown => {
                    check_i += 1;
                }
                Spring::Bad(inc) => {
                    check_i += inc;
                }
                Spring::Good => {
                    panic!("Found a good spring in the middle of what must be a bad spring range");
                }
            }
        }
        let is_boundary = self.springs.len() == 0;
        let has_extra_good_or_unknown_to_trim =
            !is_boundary && !matches!(self.springs.last(), Some(Spring::Bad(_)));

        let valid_suffix =
            check_i == last_check && (is_boundary || has_extra_good_or_unknown_to_trim);
        if !valid_suffix {
            panic!("The suffix had another invalid bad section immediately!");
        }

        if has_extra_good_or_unknown_to_trim {
            self.springs.pop();
        }
    }

    fn possibilities_count_inner(
        &self,
        springs_offset: usize,
        check_offset: usize,
        cache: &mut BTreeMap<(usize, usize), usize>,
    ) -> usize {
        if let Some(cached) = cache.get(&(springs_offset, check_offset)) {
            return *cached;
        };

        let (springs_offset, check_offset) = match self.optimize_head(springs_offset, check_offset)
        {
            Some(optimized) => optimized,
            None => {
                return 0;
            }
        };

        let springs = &self.springs[springs_offset..];
        let check = &self.check[check_offset..];

        if check.len() == 1 && springs.iter().all(|s| !matches!(s, Spring::Bad(_))) {
            let mut contigous_unknowns = Vec::new();
            let mut next_contiguous_unknown = 0;
            let mut is_in_unknown = false;
            for spring in springs.iter() {
                match spring {
                    Spring::Unknown => {
                        next_contiguous_unknown += 1;
                        is_in_unknown = true;
                    }
                    Spring::Good => {
                        if is_in_unknown {
                            contigous_unknowns.push(next_contiguous_unknown);
                            next_contiguous_unknown = 0;
                            is_in_unknown = false;
                        }
                    }
                    Spring::Bad(_) => unreachable!(),
                }
            }
            if is_in_unknown {
                contigous_unknowns.push(next_contiguous_unknown);
            }

            return contigous_unknowns
                .iter()
                .map(|region| {
                    if *region >= check[0] as usize {
                        region - check[0] as usize + 1
                    } else {
                        0
                    }
                })
                .sum();
        }

        if check.len() == 0 {
            if springs.iter().any(|s| matches!(s, Spring::Bad(_))) {
                return 0;
            } else {
                return 1;
            }
        }

        let valid_prefix_possibilities_count =
            if let Some((without_prefix_springs_offset, without_prefix_check_offset)) =
                self.trim_bad_prefix(springs_offset, check_offset)
            {
                self.possibilities_count_inner(
                    without_prefix_springs_offset,
                    without_prefix_check_offset,
                    cache,
                )
            } else {
                0
            };

        let non_prefix_possibilities_count =
            self.possibilities_count_inner(springs_offset + 1, check_offset, cache);

        let total_possibilities = valid_prefix_possibilities_count + non_prefix_possibilities_count;

        cache.insert((springs_offset, check_offset), total_possibilities);

        total_possibilities
    }

    fn optimize_head(
        &self,
        mut springs_offset: usize,
        mut check_offset: usize,
    ) -> Option<(usize, usize)> {
        while springs_offset < self.springs.len() && check_offset < self.check.len() {
            match self.springs[springs_offset] {
                Spring::Good => {
                    springs_offset += 1;
                }
                Spring::Bad(s) if s > self.check[check_offset] as usize => {
                    return None;
                }
                Spring::Bad(s) if s <= self.check[check_offset] as usize => {
                    match self.trim_bad_prefix(springs_offset, check_offset) {
                        Some((new_springs, new_check)) => {
                            springs_offset = new_springs;
                            check_offset = new_check;
                        }
                        None => return None,
                    };
                }
                Spring::Bad(_) => unreachable!(),
                Spring::Unknown => {
                    break;
                }
            }
        }

        if springs_offset == self.springs.len() && check_offset != self.check.len() {
            None
        } else {
            Some((springs_offset, check_offset))
        }
    }

    fn trim_bad_prefix(
        &self,
        springs_offset: usize,
        check_offset: usize,
    ) -> Option<(usize, usize)> {
        let first_check = self.check[check_offset] as usize;
        let mut check_i = 0;
        let mut springs_i = springs_offset;
        while check_i < first_check {
            if springs_i >= self.springs.len() {
                return None;
            }

            match self.springs[springs_i] {
                Spring::Unknown => {
                    check_i += 1;
                }
                Spring::Bad(inc) => {
                    check_i += inc;
                }
                Spring::Good => {
                    return None;
                }
            }
            springs_i += 1;
        }

        let is_boundary = springs_i == self.springs.len();
        let has_extra_good_or_unknown_to_trim =
            !is_boundary && !matches!(self.springs[springs_i], Spring::Bad(_));
        let valid_prefix =
            check_i == first_check && (is_boundary || has_extra_good_or_unknown_to_trim);

        if valid_prefix {
            let new_springs_i = if has_extra_good_or_unknown_to_trim {
                springs_i + 1
            } else {
                springs_i
            };
            Some((new_springs_i, check_offset + 1))
        } else {
            None
        }
    }
}

impl Spring {
    fn parser(input: &str) -> IResult<&str, Self> {
        alt((
            value(Spring::Good, many1_count(char('.'))),
            map(many1_count(char('#')), Spring::Bad),
            value(Spring::Unknown, char('?')),
        ))(input)
    }
}