summaryrefslogtreecommitdiff
path: root/src/bin/day_24.rs
blob: ef10ae89bbb41875067c50a4333ce9937aacff01 (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
use rpds::vector::Vector;
use rpds::RedBlackTreeSet;
use std::fmt;
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 {}

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();

    println!(
        "{}",
        initial_state.first_repeated_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 {
    grid: Vector<Vector<bool>>,
}

impl FromIterator<String> for State {
    fn from_iter<T: IntoIterator<Item = String>>(iter: T) -> Self {
        State {
            grid: iter
                .into_iter()
                .map(|line| line.chars().map(|c| c == '#').collect::<Vector<_>>())
                .collect(),
        }
    }
}

impl fmt::Display for State {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.grid
            .iter()
            .map(|row| {
                writeln!(
                    f,
                    "{}",
                    row.iter()
                        .map(|alive| if *alive { '#' } else { '.' })
                        .collect::<String>()
                )
            })
            .collect()
    }
}

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

    fn next(&self) -> State {
        State {
            grid: self
                .grid
                .iter()
                .enumerate()
                .map(|(y, row)| {
                    row.iter()
                        .enumerate()
                        .map(|(x, alive)| {
                            if *alive {
                                self.count_alive_neighbours(x, y) == 1
                            } else {
                                self.count_alive_neighbours(x, y) == 1
                                    || self.count_alive_neighbours(x, y) == 2
                            }
                        })
                        .collect()
                })
                .collect(),
        }
    }

    fn biodiversity_rating(&self) -> usize {
        self.grid
            .iter()
            .flat_map(|row| row.iter())
            .enumerate()
            .map(|(i, state)| if *state { 2_usize.pow(i as u32) } else { 0 })
            .sum()
    }

    fn count_alive_neighbours(&self, x: usize, y: usize) -> usize {
        [(-1, 0), (1, 0), (0, -1), (0, 1)]
            .into_iter()
            .filter_map(|(dx, dy)| {
                if (x > 0 || *dx >= 0) && (y > 0 || *dy >= 0) {
                    Some(((x as i32 + dx) as usize, (y as i32 + dy) as usize))
                } else {
                    None
                }
            })
            .filter(|(x, y)| self.grid.get(*y).and_then(|row| row.get(*x)).cloned() == Some(true))
            .count()
    }
}