summaryrefslogtreecommitdiffstats
path: root/src/bin/2023/day12.rs
blob: adb152a16cd58d6ca8e87a1054983b9f915531d5 (plain) (blame)
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
#![allow(dead_code)]
#![allow(unused_variables)]

use advent_of_code::prelude::*;

#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum Condition {
    Good,
    Bad,
    Unknown,
}

impl TryFrom<char> for Condition {
    type Error = anyhow::Error;

    fn try_from(value: char) -> std::result::Result<Self, Self::Error> {
        Ok(match value {
            '.' => Condition::Good,
            '#' => Condition::Bad,
            '?' => Condition::Unknown,
            _ => bail!("unknown condition {value}"),
        })
    }
}

pub struct Record {
    condition: Vec<Condition>,
    lengths: Vec<usize>,
}

impl Record {
    fn arrangements(&self) -> usize {
        arrangements(&self.condition, &self.lengths)
    }

    fn unfold(self) -> Self {
        let mut condition = vec![];
        condition.extend_from_slice(&self.condition);
        for _ in 0..4 {
            condition.push(Condition::Unknown);
            condition.extend_from_slice(&self.condition);
        }
        Self {
            condition,
            lengths: self.lengths.repeat(5),
        }
    }
}

fn arrangements(conditions: &[Condition], chunks: &[usize]) -> usize {
    let mut memo = HashMap::new();
    arrangements_memo(conditions, chunks, &mut memo)
}

fn arrangements_memo<'a, 'b>(
    conditions: &'a [Condition],
    chunks: &'b [usize],
    memo: &mut HashMap<(&'a [Condition], &'b [usize]), usize>,
) -> usize {
    if let Some(count) = memo.get(&(conditions, chunks)) {
        return *count;
    }
    let count = _arrangements(conditions, chunks, memo);
    memo.insert((conditions, chunks), count);
    count
}

fn _arrangements<'a, 'b>(
    conditions: &'a [Condition],
    chunks: &'b [usize],
    memo: &mut HashMap<(&'a [Condition], &'b [usize]), usize>,
) -> usize {
    let good_prefix = conditions
        .iter()
        .copied()
        .take_while(|condition| *condition == Condition::Good)
        .count();
    if good_prefix > 0 {
        return arrangements_memo(&conditions[good_prefix..], chunks, memo);
    }

    if conditions.is_empty() {
        if chunks.is_empty() {
            return 1;
        } else {
            return 0;
        }
    } else if chunks.is_empty() {
        if conditions.contains(&Condition::Bad) {
            return 0;
        } else {
            return 1;
        }
    } else if chunks.iter().sum::<usize>() + chunks.len() - 1
        > conditions.len()
    {
        return 0;
    }

    let next = conditions
        .iter()
        .copied()
        .take_while(|condition| *condition != Condition::Good)
        .take(chunks[0])
        .count();
    if next < chunks[0] {
        if conditions
            .iter()
            .copied()
            .take(next)
            .all(|condition| condition == Condition::Unknown)
        {
            return arrangements_memo(&conditions[next..], chunks, memo);
        } else {
            return 0;
        }
    }

    let mut total = 0;
    if conditions[0] == Condition::Unknown {
        total += arrangements_memo(&conditions[1..], chunks, memo);
    }
    if next == conditions.len() || conditions[next] != Condition::Bad {
        total += arrangements_memo(
            &conditions[(next + 1).min(conditions.len())..],
            &chunks[1..],
            memo,
        );
    }

    total
}

impl std::str::FromStr for Record {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        let mut parts = s.split_whitespace();
        Ok(Record {
            condition: parts
                .next()
                .unwrap()
                .chars()
                .map(|c| c.try_into().unwrap())
                .collect(),
            lengths: parts
                .next()
                .unwrap()
                .split(',')
                .map(|s| s.parse().unwrap())
                .collect(),
        })
    }
}

pub fn parse(fh: File) -> Result<Vec<Record>> {
    Ok(parse::lines(fh).collect())
}

pub fn part1(records: Vec<Record>) -> Result<i64> {
    Ok(records
        .into_iter()
        .map(|record| record.arrangements())
        .sum::<usize>()
        .try_into()
        .unwrap())
}

pub fn part2(records: Vec<Record>) -> Result<i64> {
    Ok(records
        .into_iter()
        .map(|record| record.unfold().arrangements())
        .sum::<usize>()
        .try_into()
        .unwrap())
}

#[test]
fn test() {
    assert_eq!(
        part1(parse(parse::data(2023, 12).unwrap()).unwrap()).unwrap(),
        7407
    );
    assert_eq!(
        part2(parse(parse::data(2023, 12).unwrap()).unwrap()).unwrap(),
        30568243604962
    );
}