Skip to main content

aoc/year2020/
day15.rs

1//! # Rambunctious Recitation
2//!
3//! For efficiency the `vec` storing the last previously spoken turn of numbers is `u32`.
4//! Each difference is at least one so zero is used as a special value to indicate numbers not
5//! seen before.
6//!
7//! To speed things up even more, we notice that most large numbers over a certain threshold are
8//! spoken only once. Storing if numbers have been seen before in a compact bitset prevents
9//! expensive reads to main memory and halves the time needed for the solution.
10//!
11//! Zero occurs the most so storing it as a dedicated variable saves another 2% of execution time.
12use std::mem::replace;
13
14use crate::util::parse::*;
15
16const THRESHOLD: usize = 0x10000;
17
18pub fn parse(input: &str) -> Vec<usize> {
19    input.iter_unsigned().collect()
20}
21
22pub fn part1(input: &[usize]) -> usize {
23    play(input, 2020)
24}
25
26pub fn part2(input: &[usize]) -> usize {
27    play(input, 30_000_000)
28}
29
30fn play(input: &[usize], rounds: usize) -> usize {
31    let (&(mut last), starting) = input.split_last().unwrap();
32
33    let mut zeroth = 0;
34    let mut spoken = vec![0; rounds];
35    let mut seen = vec![0_u64; rounds / 64];
36
37    for (&n, i) in starting.iter().zip(1..) {
38        if n == 0 {
39            zeroth = i;
40        } else {
41            spoken[n] = i as u32;
42        }
43    }
44
45    for i in input.len()..rounds {
46        if last == 0 {
47            // Handle zero specially as it occurs the most.
48            let previous = replace(&mut zeroth, i);
49            last = if previous == 0 { 0 } else { i - previous };
50        } else if last < THRESHOLD {
51            // Smaller numbers occur frequently so skip previously seen bitset check.
52            let previous = replace(&mut spoken[last], i as u32) as usize;
53            last = if previous == 0 { 0 } else { i - previous };
54        } else {
55            // An array of 30 million `u32`s needs 120 MB of memory which exceeds most caches.
56            // Writing and reading to random locations in this large array goes to main memory
57            // which is slow. Store if a number has been seen before in a compact bitset,
58            // needing only a more cache friendly 4 MB.
59            let base = last / 64;
60            let mask = 1 << (last % 64);
61
62            if seen[base] & mask == 0 {
63                seen[base] |= mask;
64                spoken[last] = i as u32;
65                last = 0;
66            } else {
67                let previous = replace(&mut spoken[last], i as u32) as usize;
68                last = i - previous;
69            }
70        }
71    }
72
73    last
74}