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
use std::collections::hash_map::{DefaultHasher, Entry};
use std::collections::HashMap;
use std::env;
use std::hash::{Hash, Hasher};
use std::mem::swap;

struct Grid {
    width: usize,
    height: usize,
    cells: Vec<u8>,
    next_gen_cells: Vec<u8>,
}

impl Grid {
    fn parse(input_string: &str) -> Self {
        let mut height = 0;
        let mut width = 0;
        let mut cells = Vec::new();
        for line in input_string.lines() {
            line.chars().for_each(|c| cells.push(c as u8));
            width = line.len();
            height += 1;
        }

        let next_gen_cells = vec![0; height * width];

        Self {
            width,
            height,
            cells,
            next_gen_cells,
        }
    }

    fn count_around(&self, x: usize, y: usize, needle: u8) -> u8 {
        let mut sum = 0;
        for &dy in &[-1_i32, 0, 1] {
            for &dx in &[-1_i32, 0, 1] {
                if dx == 0 && dy == 0 {
                    continue;
                }
                let nx = x as i32 + dx;
                let ny = y as i32 + dy;
                if nx >= 0
                    && (nx as usize) < self.width
                    && ny >= 0
                    && (ny as usize) < self.height
                    && self.cells[(self.width as i32 * ny + nx) as usize] == needle
                {
                    sum += 1;
                }
            }
        }
        sum
    }

    fn advance_minute(&mut self) -> Result<(), String> {
        for y in 0..self.height {
            for x in 0..self.width {
                let cell_value = self.cells[self.width * y + x];
                self.next_gen_cells[self.width * y + x] = match cell_value {
                    b'.' => {
                        if self.count_around(x, y, b'|') >= 3 {
                            b'|'
                        } else {
                            b'.'
                        }
                    }
                    b'|' => {
                        if self.count_around(x, y, b'#') >= 3 {
                            b'#'
                        } else {
                            b'|'
                        }
                    }
                    b'#' => {
                        if self.count_around(x, y, b'#') >= 1 && self.count_around(x, y, b'|') >= 1
                        {
                            b'#'
                        } else {
                            b'.'
                        }
                    }
                    _ => {
                        return Err(format!("Unhandled cell value: {}", cell_value));
                    }
                }
            }
        }
        swap(&mut self.cells, &mut self.next_gen_cells);
        Ok(())
    }

    fn resource_value(&self) -> usize {
        self.cells.iter().fold(0, |n, c| n + (*c == b'|') as usize)
            * self.cells.iter().fold(0, |n, c| n + (*c == b'#') as usize)
    }

    fn print(&self) {
        if env::var("ADVENT_DEBUG").is_err() {
            return;
        }
        for y in 0..self.height {
            for x in 0..self.width {
                print!("{}", self.cells[self.width * y + x] as char);
            }
            println!();
        }
        println!();
    }
}

pub fn part1(input_string: &str) -> Result<usize, String> {
    let mut grid = Grid::parse(input_string);
    grid.print();
    for _ in 0..10 {
        grid.advance_minute()?;
        grid.print();
    }
    Ok(grid.resource_value())
}

pub fn part2(input_string: &str) -> Result<usize, String> {
    let mut grid = Grid::parse(input_string);
    grid.print();

    let mut seen = HashMap::new();

    for i in 1..1_000_000_000 {
        grid.advance_minute()?;

        let mut hasher = DefaultHasher::new();
        grid.cells.hash(&mut hasher);
        let hash_value = hasher.finish();

        match seen.entry(hash_value) {
            Entry::Occupied(entry) => {
                let cycle_length = i - entry.get();
                let remaining_hashes = (1_000_000_000 - i) % cycle_length;
                for _ in 0..remaining_hashes {
                    grid.advance_minute()?;
                }
                return Ok(grid.resource_value());
            }
            Entry::Vacant(entry) => {
                entry.insert(i);
            }
        }
    }
    Err("No solution found".to_string())
}

#[test]
fn tests_part1() {
    assert_eq!(
        Ok(1147),
        part1(
            ".#.#...|#.
.....#|##|
.|..|...#.
..|#.....#
#.#|||#|#|
...#.||...
.|....|...
||...#|.#|
|.||||..|.
...#.|..|."
        )
    );

    assert_eq!(Ok(531_417), part1(include_str!("day18_input.txt")));
}

#[test]
fn tests_part2() {
    assert_eq!(Ok(205_296), part2(include_str!("day18_input.txt")));
}