aoc/year2018/day12.rs
1//! # Subterranean Sustainability
2//!
3//! The problem is a one-dimensional version of
4//! [Conway's Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life).
5//!
6//! We use a vector to store which pots are occupied and which are empty in each generation.
7//! When calculating the next step, we truncate the bit vector on the left and right.
8//! This makes it easier to compare generations in part two.
9//!
10//! The trick for part two is that the plants will eventually stabilize into a stable pattern
11//! (similar to a [glider](https://en.wikipedia.org/wiki/Glider_(Conway%27s_Game_of_Life)))
12//! that moves by the same amount each generation. Once two subsequent generations are the same,
13//! except for the starting position, we extrapolate 50 billion generations into the future.
14use std::mem::swap;
15
16type Input = (i64, i64);
17
18struct Pots {
19 /// Vector representing the pots. 1 means there is a plant in the pot, 0 means there isn't.
20 state: Vec<u8>,
21 /// A copy of the vector `state` before [`Self::step`] was called.
22 prev_state: Vec<u8>,
23 /// The id of the pot at the beginning of the bit vector `state`.
24 pos: i64,
25}
26
27impl Pots {
28 /// Parses the initial state into a bit vector.
29 fn new(initial_state: &[u8]) -> Self {
30 let state = initial_state.iter().map(|&b| u8::from(b == b'#')).collect();
31 Self { state, prev_state: Vec::new(), pos: 0 }
32 }
33
34 /// Applies the given rules to the pots and updates [`Self::state`]. A copy of the state before
35 /// this method was called is left in [`Self::prev_state`].
36 fn step(&mut self, rules: &[u8; 32]) {
37 // Prepare new state.
38 swap(&mut self.state, &mut self.prev_state);
39 self.state.clear();
40
41 let start = self.prev_state.iter().position(|&b| b == 1).unwrap();
42 let end = self.prev_state.iter().rposition(|&b| b == 1).unwrap();
43 let mut mask = 0;
44
45 // Apply rules and build up new state.
46 // Pad zeros onto the end to make handling next state easier.
47 for b in self.prev_state[start..=end].iter().copied().chain([0; 4]) {
48 mask = ((mask << 1) | usize::from(b)) & 0b11111;
49 self.state.push(rules[mask]);
50 }
51
52 // Update start position.
53 self.pos += start as i64 - 2;
54 }
55
56 /// Returns the sum of the numbers of all pots containing plants.
57 fn sum(&self) -> i64 {
58 self.state.iter().zip(self.pos..).map(|(&s, i)| i * i64::from(s)).sum()
59 }
60}
61
62pub fn parse(input: &str) -> Input {
63 // Parse initial state.
64 let (prefix, suffix) = input.split_once("\n\n").unwrap();
65 let mut pots = Pots::new(&prefix.as_bytes()[15..]);
66
67 // Parse rules into a table with all possible 2⁵=32 patterns.
68 let mut rules = [0; 32];
69 for line in suffix.lines().map(str::as_bytes) {
70 let binary = (0..5).fold(0, |acc, i| (acc << 1) | usize::from(line[i] == b'#'));
71 rules[binary] = u8::from(line[9] == b'#');
72 }
73
74 // Part one - Simulate the first 20 steps.
75 for _ in 0..20 {
76 pots.step(&rules);
77 }
78 let part_one = pots.sum();
79
80 // Part two - Only simulate until the generation repeats.
81 for steps in 20.. {
82 let prev_pos = pots.pos;
83 pots.step(&rules);
84 if pots.state == pots.prev_state {
85 // Generation has repeated - extrapolate to 50 billion steps.
86 pots.pos += (pots.pos - prev_pos) * (50_000_000_000 - steps - 1);
87 break;
88 }
89 }
90
91 let part_two = pots.sum();
92 (part_one, part_two)
93}
94
95pub fn part1(input: &Input) -> i64 {
96 input.0
97}
98
99pub fn part2(input: &Input) -> i64 {
100 input.1
101}