Skip to main content

aoc/year2017/
day06.rs

1//! # Memory Reallocation
2//!
3//! Looking at the input and the reallocation rules, when there is at most one bank with
4//! 15 blocks, it is easy to see that no other bank will exceed 15 after reallocation.
5//! However, some input files have early scenarios where there are a couple of banks with
6//! 15, which can result in the next round or two needing to process 16 or even 17 blocks.
7//! The overflow issue only occurs early. In the long run, the banks settle into a pattern
8//! where overflow does not interfere.
9//!
10//! With that in mind, it is possible to design a compact layout that stores each bank in
11//! one nibble of a u64 in the common case, but with manual iterations managing the overflow
12//! as needed.
13//!
14//! For all but the few manual overflow cases, it is very fast to find the highest nibble
15//! using bitwise logic. To detect the cycle a [`FastMap`] stores each previously seen
16//! memory layout along with the cycle in which it first appeared.
17use std::array::from_fn;
18
19use crate::util::hash::*;
20use crate::util::parse::*;
21
22/// Reallocate a bank and set to zero by rotating this mask the correct number of bits.
23const REMOVE: u64 = 0x0fffffffffffffff;
24/// The highest number of banks when overflow is not a concern is 15, so each bank will
25/// add at most 1 to each of the banks that come after it.
26const SPREAD: [u64; 16] = [
27    0x0000000000000000,
28    0x0100000000000000,
29    0x0110000000000000,
30    0x0111000000000000,
31    0x0111100000000000,
32    0x0111110000000000,
33    0x0111111000000000,
34    0x0111111100000000,
35    0x0111111110000000,
36    0x0111111111000000,
37    0x0111111111100000,
38    0x0111111111110000,
39    0x0111111111111000,
40    0x0111111111111100,
41    0x0111111111111110,
42    0x0111111111111111,
43];
44
45type Input = (u32, u32);
46
47pub fn parse(input: &str) -> Input {
48    // Accumulate the input into a single `u64`.
49    let mut memory = input.iter_unsigned::<u64>().fold(0, |acc, n| (acc << 4) + n);
50    // Store previously seen configurations for cycle detection.
51    let mut seen = FastMap::with_capacity(20_000);
52    let mut cycles = 0;
53
54    loop {
55        // Find the highest nibble in the integer.
56        // We check each of the 4 bits for all nibbles in descending order by bitwise ANDing with
57        // the mask.
58        // If the mask is zero, then this implies that no nibbles have that bit set so we leave
59        // the mask unchanged.
60        // If some nibbles have that bit set, then we will "narrow" the mask to only consider
61        // those nibbles.
62        let mask = (0..4).fold(0x8888888888888888, |mask, shift| {
63            let result = (memory << shift) & mask;
64            if result == 0 { mask } else { result }
65        });
66
67        // The mask will have a 1 bit set for each of the joint highest values.
68        // Choose the lowest index which is the most significant bit set.
69        let offset = mask.leading_zeros();
70        let max = (memory.rotate_left(offset + 4) & 0xf) as usize;
71
72        // Common case has no overflow.
73        if max < 15 || mask.count_ones() == 1 {
74            // Empty the largest memory bank and reallocate its contents to the following banks.
75            memory = (memory & REMOVE.rotate_right(offset)) + SPREAD[max].rotate_right(offset);
76            cycles += 1;
77
78            // Check if we've seen this configuration before.
79            if let Some(previous) = seen.insert(memory, cycles) {
80                break (cycles, cycles - previous);
81            }
82        } else {
83            // Overflow case. This can happen in the early steps of the system, but resolves
84            // fairly quickly - in practice, the worst known input file had a total of 10 overflow
85            // cycles, with at most two adjacent overflows per encounter, with all overflows
86            // before cycle 200, well before the first repeated configuration. Thus, it is
87            // okay to not cache these states in seen.
88            let mut array: [_; 16] = from_fn(|i| (memory >> (4 * (15 - i))) & 0xf);
89
90            while array.iter().any(|&n| n >= 15) {
91                let max = *array.iter().max().unwrap();
92                let first = array.iter().position(|&n| n == max).unwrap();
93
94                array[first] = 0;
95                (0..max as usize).for_each(|i| array[(first + i + 1) % 16] += 1);
96
97                cycles += 1;
98            }
99
100            memory = array.iter().fold(0, |acc, n| (acc << 4) | n);
101        }
102    }
103}
104
105pub fn part1(input: &Input) -> u32 {
106    input.0
107}
108
109pub fn part2(input: &Input) -> u32 {
110    input.1
111}