summaryrefslogtreecommitdiff
path: root/src/bin/day_24.rs
blob: ebc6a1be78d7c464b2783e5aa3fd5e1117ac62a8 (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
use rpds::RedBlackTreeSet;
use std::io;
use std::io::prelude::*;
use std::iter;
use std::iter::FromIterator;
use std::process;
use structopt::StructOpt;

#[derive(Debug, StructOpt)]
#[structopt(name = "Day 24: Planet of Discord")]
/// Simulates the life and death of Eris bugs
///
/// See https://adventofcode.com/2019/day/24 for details.
struct Opt {
    /// How many iterations of the game of life should be run
    /// If not provided, runs until a state appears twice.
    #[structopt(short = "n")]
    depth: Option<usize>,
    /// Interprets the map as being one part of an infinite fractal map
    #[structopt(short = "f")]
    fractal: bool,
}

fn main() {
    let stdin = io::stdin();
    let opt = Opt::from_args();

    let initial_state: State = stdin
        .lock()
        .lines()
        .map(|x| exit_on_failed_assertion(x, "Error reading input"))
        .collect::<State>()
        .with_fractal_mode(opt.fractal);

    let final_state = match opt.depth {
        Some(depth) => initial_state.n_steps_forward(depth),
        None => initial_state.first_repeated_state(),
    };

    println!("Bugs: {}", final_state.alive.size());
    println!("Biodiversity: {}", final_state.biodiversity_rating());
}

fn exit_on_failed_assertion<A, E: std::error::Error>(data: Result<A, E>, message: &str) -> A {
    match data {
        Ok(data) => data,
        Err(e) => {
            eprintln!("{}: {}", message, e);
            process::exit(1);
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct State {
    alive: RedBlackTreeSet<Coordinate>,
    fractal_mode: bool,
}

impl FromIterator<String> for State {
    fn from_iter<T: IntoIterator<Item = String>>(iter: T) -> Self {
        State {
            alive: iter
                .into_iter()
                .enumerate()
                .flat_map(move |(y, line)| {
                    line.chars()
                        .enumerate()
                        .filter(move |(_x, c)| *c == '#')
                        .map(move |(x, _c)| Coordinate {
                            x: x as isize,
                            y: y as isize,
                            depth: 0,
                        })
                        .collect::<Vec<Coordinate>>()
                })
                .collect(),
            fractal_mode: false,
        }
    }
}

impl State {
    fn with_fractal_mode(&self, fractal_mode: bool) -> State {
        State {
            fractal_mode,
            ..self.clone()
        }
    }

    fn n_steps_forward(&self, n: usize) -> Self {
        iter::successors(Some(self.clone()), |state| Some(state.next()))
            .nth(n)
            .unwrap()
    }

    fn first_repeated_state(&self) -> State {
        iter::successors(
            Some((RedBlackTreeSet::new(), self.clone())),
            |(seen, state)| Some((seen.insert(state.clone()), state.next())),
        )
        .find(|(seen, state)| seen.contains(state))
        .unwrap()
        .1
    }

    fn next(&self) -> State {
        State {
            alive: self
                .still_alive_next_round()
                .chain(self.comes_alive_next_round())
                .collect(),
            ..self.clone()
        }
    }

    fn biodiversity_rating(&self) -> usize {
        self.alive
            .iter()
            .map(|coord| 2_usize.pow((coord.y * 5 + coord.x) as u32))
            .sum()
    }

    fn still_alive_next_round<'a>(&'a self) -> impl Iterator<Item = Coordinate> + 'a {
        self.alive
            .iter()
            .filter(move |coord| self.count_alive_neighbours(**coord) == 1)
            .cloned()
    }

    fn comes_alive_next_round<'a>(&'a self) -> impl Iterator<Item = Coordinate> + 'a {
        self.alive
            .iter()
            .flat_map(move |coord| self.neighbours(*coord))
            .filter(move |coord| !self.alive.contains(coord))
            .filter(move |coord| {
                self.count_alive_neighbours(*coord) == 1 || self.count_alive_neighbours(*coord) == 2
            })
    }

    fn count_alive_neighbours(&self, coordinate: Coordinate) -> usize {
        self.neighbours(coordinate)
            .into_iter()
            .filter(|coord| self.alive.contains(coord))
            .count()
    }

    fn neighbours(&self, coordinate: Coordinate) -> Vec<Coordinate> {
        if self.fractal_mode {
            [(-1, 0), (1, 0), (0, -1), (0, 1)]
                .into_iter()
                .map(|(dx, dy)| Coordinate {
                    x: coordinate.x + dx,
                    y: coordinate.y + dy,
                    depth: coordinate.depth,
                })
                .flat_map(move |coord| match (coord.x, coord.y) {
                    (x, _y) if x < 0 => vec![Coordinate {
                        x: 1,
                        y: 2,
                        depth: coord.depth - 1,
                    }]
                    .into_iter(),
                    (_x, y) if y < 0 => vec![Coordinate {
                        x: 2,
                        y: 1,
                        depth: coord.depth - 1,
                    }]
                    .into_iter(),
                    (x, _y) if x >= 5 => vec![Coordinate {
                        x: 3,
                        y: 2,
                        depth: coord.depth - 1,
                    }]
                    .into_iter(),
                    (_x, y) if y >= 5 => vec![Coordinate {
                        x: 2,
                        y: 3,
                        depth: coord.depth - 1,
                    }]
                    .into_iter(),
                    (2, 2) => match (coordinate.x, coordinate.y) {
                        (1, 2) => (0..5)
                            .map(|y| Coordinate {
                                x: 0,
                                y,
                                depth: coord.depth + 1,
                            })
                            .collect::<Vec<_>>()
                            .into_iter(),
                        (2, 1) => (0..5)
                            .map(|x| Coordinate {
                                x,
                                y: 0,
                                depth: coord.depth + 1,
                            })
                            .collect::<Vec<_>>()
                            .into_iter(),
                        (3, 2) => (0..5)
                            .map(|y| Coordinate {
                                x: 4,
                                y,
                                depth: coord.depth + 1,
                            })
                            .collect::<Vec<_>>()
                            .into_iter(),
                        (2, 3) => (0..5)
                            .map(|x| Coordinate {
                                x,
                                y: 4,
                                depth: coord.depth + 1,
                            })
                            .collect::<Vec<_>>()
                            .into_iter(),
                        (_, _) => vec![].into_iter(),
                    },
                    _ => vec![coord.clone()].into_iter(),
                })
                .collect()
        } else {
            [(-1, 0), (1, 0), (0, -1), (0, 1)]
                .into_iter()
                .map(|(dx, dy)| Coordinate {
                    x: coordinate.x + dx,
                    y: coordinate.y + dy,
                    depth: coordinate.depth,
                })
                .filter(|coord| coord.x >= 0 && coord.x < 5 && coord.y >= 0 && coord.y < 5)
                .collect()
        }
    }
}

#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq)]
struct Coordinate {
    x: isize,
    y: isize,
    depth: isize,
}