Skip to main content

aoc/year2024/
day22.rs

1//! # Monkey Market
2//!
3//! Solves both parts simultaneously, parallelizing the work over multiple threads since
4//! each secret number is independent. The process of generating the next secret number is a
5//! [linear feedback shift register](https://en.wikipedia.org/wiki/Linear-feedback_shift_register),
6//! with a cycle of 2²⁴.
7//!
8//! Interestingly, this means that with some clever math it's possible to generate the `n`th number
9//! from any starting secret number with only 24 calculations. Unfortunately, this doesn't help for
10//! part two since we need to check every possible price change. However, to speed things up we can
11//! make several optimizations:
12//!
13//! * First the sequence of 4 prices is converted from -9..9 to a base 19 index of 0..19.
14//! * Whether a monkey has seen a sequence before and the total bananas for each sequence are stored
15//!   in an array. This is much faster than a `HashMap`. Using base 19 gives much better cache
16//!   locality needing only 130,321 elements, for example compared to shifting each new cost by 5
17//!   bits and storing in an array of 2²⁰ = 1,048,576 elements. Multiplication on modern processors
18//!   is cheap (and several instructions can issue at once) but random memory access is expensive.
19//!
20//! A SIMD variant processes 8 hashes at a time, taking about 60% of the time of the scalar version.
21//! The bottleneck is that disjoint indices must be written in sequence reducing the amount of work
22//! that can be parallelized.
23use self::implementation::*;
24use crate::util::parse::*;
25use crate::util::thread::*;
26
27type Input = (u64, u16);
28type Result = (u64, Vec<u16>);
29
30pub fn parse(input: &str) -> Input {
31    let result = parallel(input);
32
33    // Merge results from different threads.
34    let mut part_one = 0;
35    let mut part_two = vec![0; 130_321];
36
37    for (first, second) in result {
38        part_one += first;
39        part_two.iter_mut().zip(second).for_each(|(a, b)| *a += b);
40    }
41
42    (part_one, part_two.into_iter().max().unwrap())
43}
44
45pub fn part1(input: &Input) -> u64 {
46    input.0
47}
48
49pub fn part2(input: &Input) -> u16 {
50    input.1
51}
52
53#[cfg(not(feature = "simd"))]
54mod implementation {
55    use super::*;
56
57    // Use as many cores as possible to parallelize the remaining search.
58    pub(super) fn parallel(input: &str) -> Vec<Result> {
59        let numbers: Vec<_> = input.iter_unsigned().collect();
60        spawn_parallel_iterator(&numbers, worker)
61    }
62
63    fn worker(iter: ParIter<'_, u32>) -> Result {
64        let mut part_one = 0;
65        let mut part_two = vec![0; 130_321];
66        let mut seen = vec![u16::MAX; 130_321];
67
68        for (&zeroth, id) in iter.zip(0..) {
69            let first = hash(zeroth);
70            let second = hash(first);
71            let third = hash(second);
72
73            let mut a;
74            let mut b = to_index(zeroth, first);
75            let mut c = to_index(first, second);
76            let mut d = to_index(second, third);
77
78            let mut number = third;
79            let mut previous = third % 10;
80
81            for _ in 3..2000 {
82                number = hash(number);
83                let price = number % 10;
84
85                // Compute index into the array.
86                (a, b, c, d) = (b, c, d, to_index(previous, price));
87                let index = (6859 * a + 361 * b + 19 * c + d) as usize;
88                previous = price;
89
90                // Only sell the first time we see a sequence.
91                // By storing the id in the array we don't need to zero every iteration which is
92                // faster.
93                if seen[index] != id {
94                    part_two[index] += price as u16;
95                    seen[index] = id;
96                }
97            }
98
99            part_one += number as u64;
100        }
101
102        (part_one, part_two)
103    }
104
105    /// Compute next secret number using a
106    /// [Xorshift LFSR](https://en.wikipedia.org/wiki/Linear-feedback_shift_register#Xorshift_LFSRs).
107    fn hash(mut n: u32) -> u32 {
108        n = (n ^ (n << 6)) & 0xffffff;
109        n = (n ^ (n >> 5)) & 0xffffff;
110        (n ^ (n << 11)) & 0xffffff
111    }
112
113    /// Convert -9..9 to 0..18.
114    fn to_index(previous: u32, current: u32) -> u32 {
115        9 + current % 10 - previous % 10
116    }
117}
118
119#[cfg(feature = "simd")]
120mod implementation {
121    use std::simd::prelude::*;
122
123    use super::*;
124
125    type Vector = Simd<u32, 8>;
126
127    pub(super) fn parallel(input: &str) -> Vec<Result> {
128        let mut numbers: Vec<_> = input.iter_unsigned().collect();
129
130        // Add zero elements so that size is a multiple of 8.
131        // Zero always hashes to zero and does not contribute to score.
132        numbers.resize(numbers.len().next_multiple_of(8), 0);
133        let chunks: Vec<_> = numbers.chunks_exact(8).collect();
134
135        spawn_parallel_iterator(&chunks, worker)
136    }
137
138    /// Similar to scalar version but using SIMD vectors instead.
139    /// 8 lanes is the sweet spot for performance as the bottleneck is the scalar loop writing
140    /// to disjoint indices after each step.
141    fn worker(iter: ParIter<'_, &[u32]>) -> Result {
142        let ten = Simd::splat(10);
143        let x = Simd::splat(6859);
144        let y = Simd::splat(361);
145        let z = Simd::splat(19);
146
147        let mut part_one = 0;
148        let mut part_two = vec![0; 130_321];
149
150        for slice in iter {
151            // Each lane uses a different bit to track if a sequence has been seen before.
152            let mut seen = vec![u8::MAX; 130_321];
153
154            let zeroth = Simd::from_slice(slice);
155            let first = hash(zeroth);
156            let second = hash(first);
157            let third = hash(second);
158
159            let mut a;
160            let mut b = to_index(zeroth, first);
161            let mut c = to_index(first, second);
162            let mut d = to_index(second, third);
163
164            let mut number = third;
165            let mut previous = third % ten;
166
167            for _ in 3..2000 {
168                number = hash(number);
169                let prices = number % ten;
170
171                // Compute index into the array.
172                (a, b, c, d) = (b, c, d, to_index(previous, prices));
173                let indices = x * a + y * b + z * c + d;
174                previous = prices;
175
176                // Only sell the first time we see a sequence.
177                let indices = indices.to_array();
178                let prices = prices.to_array();
179
180                for i in 0..8 {
181                    let index = indices[i] as usize;
182
183                    // Avoid branching to improve speed, instead multiply by either 0 or 1,
184                    // depending if sequence has been seen before or not.
185                    let bit = (seen[index] >> i) & 1;
186                    seen[index] &= !(1 << i);
187
188                    part_two[index] += prices[i] as u16 * bit as u16;
189                }
190            }
191
192            part_one += number.reduce_sum() as u64;
193        }
194
195        (part_one, part_two)
196    }
197
198    /// SIMD vector arguments are passed in memory so inline functions to avoid slow transfers
199    /// to and from memory.
200    #[inline]
201    fn hash(mut n: Vector) -> Vector {
202        let mask = Simd::splat(0xffffff);
203        n = (n ^ (n << 6)) & mask;
204        n = (n ^ (n >> 5)) & mask;
205        (n ^ (n << 11)) & mask
206    }
207
208    #[inline]
209    fn to_index(previous: Vector, current: Vector) -> Vector {
210        let nine = Simd::splat(9);
211        let ten = Simd::splat(10);
212        nine + (current % ten) - (previous % ten)
213    }
214}