summaryrefslogtreecommitdiff
path: root/2023/src/bin/day_12.rs
blob: a2e83bebe2193b59fc9fb4ed40c8f8df5ce6683f (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
use nom::{
    branch::alt,
    character::complete::{char, line_ending, space1, u32},
    combinator::{map, value},
    multi::{many1, separated_list1},
    sequence::separated_pair,
    IResult,
};
use std::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)]
struct SpringRow {
    springs: Vec<Option<Spring>>,
    check: Vec<u32>,
}

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

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(None);
            expanded.check.append(&mut self.check.clone());
        }

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

        expanded
    }

    fn validate_check(&self, springs: &[Spring]) -> bool {
        let mut current_check_index = 0;
        let mut current_count = 0;
        let mut in_bad_lands = false;

        for spring in springs {
            match spring {
                Spring::Good => {
                    if in_bad_lands {
                        let valid = self
                            .check
                            .get(current_check_index)
                            .map_or(false, |expected| *expected == current_count);
                        if !valid {
                            return false;
                        }
                        current_count = 0;

                        current_check_index += 1;
                    }
                    in_bad_lands = false;
                }
                Spring::Bad => {
                    current_count += 1;
                    in_bad_lands = true;
                }
            }
        }

        if in_bad_lands {
            let valid = self
                .check
                .get(current_check_index)
                .map_or(false, |expected| *expected == current_count);
            if !valid {
                return false;
            }
            current_check_index += 1;
        }

        self.check.len() == current_check_index
    }

    fn possibilities_count(&self) -> usize {
        let unknown_indexes: Vec<usize> = self
            .springs
            .iter()
            .enumerate()
            .filter_map(|(i, s)| s.is_none().then_some(i))
            .collect();

        assert_ne!(unknown_indexes.len(), 0);
        let max_possibilities = 2_usize.pow(unknown_indexes.len().try_into().unwrap());

        let mut spring_guess: Vec<Spring> = self
            .springs
            .iter()
            .map(|s| s.unwrap_or(Spring::Bad))
            .collect();
        let unknown_indexes: Vec<usize> = self
            .springs
            .iter()
            .enumerate()
            .filter_map(|(i, s)| s.is_none().then_some(i))
            .collect();
        let possibilities = (0..max_possibilities)
            .filter(|i| {
                for (bit_index, spring_index) in unknown_indexes.iter().enumerate() {
                    spring_guess[*spring_index] = if i & (1 << bit_index) != 0 {
                        Spring::Bad
                    } else {
                        Spring::Good
                    };
                }
                self.validate_check(&spring_guess)
            })
            .count();

        possibilities
    }
}

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