aoc/year2018/day14.rs
1//! # Chocolate Charts
2//!
3//! This solution is heavily inspired by [Askalski's](https://www.reddit.com/user/askalski/)
4//! excellent post [Breaking the 1 billion recipes per second barrier](https://www.reddit.com/r/adventofcode/comments/a6wpwa/2018_day_14_breaking_the_1_billion_recipes_per/).
5//!
6//! The key insight is that after 23 recipes the elves converge into using the *same subset* of
7//! recipes. This subset can be stored compactly in about 20% of the space and read sequentially
8//! to allow efficient vector processing.
9//!
10//! Tricks used to speed things up:
11//! * Separate writer and reader threads to generate recipes and check them in parallel.
12//! * Vector processing of recipes using techniques similar to SIMD.
13use std::sync::atomic::{AtomicBool, Ordering};
14use std::sync::mpsc::{Receiver, Sender, channel};
15use std::thread;
16
17use crate::util::parse::*;
18
19/// Pre-calculate the first 23 recipes.
20const PREFIX: [u8; 23] = [3, 7, 1, 0, 1, 0, 1, 2, 4, 5, 1, 5, 8, 9, 1, 6, 7, 7, 9, 2, 5, 1, 0];
21
22type Input = (String, usize);
23
24pub fn parse(input: &str) -> Input {
25 // Send batches of recipes from the writer to the reader for checking.
26 let (tx, rx) = channel();
27 // Thread safe flag to let writer know when to stop.
28 let done = AtomicBool::new(false);
29 // Store recipes in fixed-size vec prefilled with ones. Part two result is around 20 million
30 // so size should be sufficient for most inputs.
31 let mut recipes = vec![1; 25_000_000];
32
33 thread::scope(|scope| {
34 // Start writer thread to produce new recipes.
35 scope.spawn(|| writer(tx, &done, recipes.as_mut_slice()));
36 // Reader thread checks recipes for the answers, returning when both parts are found.
37 scope.spawn(|| reader(rx, &done, input)).join().unwrap()
38 })
39}
40
41pub fn part1(input: &Input) -> &str {
42 &input.0
43}
44
45pub fn part2(input: &Input) -> usize {
46 input.1
47}
48
49/// Receives batches of recipes from the writer thread, then scans them byte by byte searching
50/// for the part two pattern. For simplicity the pattern is always assumed to be six digits.
51fn reader(rx: Receiver<&[u8]>, done: &AtomicBool, input: &str) -> (String, usize) {
52 let part_one_target = input.unsigned::<usize>() + 10;
53 let part_two_target = u32::from_str_radix(input.trim(), 16).unwrap();
54
55 let mut part_one_result = None;
56 let mut part_two_result = None;
57
58 let mut history = Vec::new();
59 let mut total = 0;
60 let mut pattern = 0;
61
62 for slice in rx {
63 history.push(slice);
64 total += slice.len();
65
66 // The recipes are broken up into batches. Even though these batches originally come
67 // from the same contiguous slice, this thread has no way to know that or reassemble
68 // the original. The result could potentially be split over two or more slices.
69 if part_one_result.is_none() && total >= part_one_target {
70 // Push each digit into a string as there could be leading zeroes.
71 let digits = history.iter().copied().flatten().skip(part_one_target - 10).take(10);
72 part_one_result = Some(digits.map(|&digit| char::from(digit + b'0')).collect());
73 }
74
75 // Simple brute force pattern matching. Slices are received in order so the pattern will
76 // handle cases when the target is split between two slices.
77 if part_two_result.is_none() {
78 for (i, n) in slice.iter().copied().enumerate() {
79 pattern = ((pattern << 4) | u32::from(n)) & 0xffffff;
80
81 if pattern == part_two_target {
82 part_two_result = Some(total - slice.len() + i - 5);
83 break;
84 }
85 }
86 }
87
88 // Signal the writer thread to finish once both results are found.
89 if part_one_result.is_some() && part_two_result.is_some() {
90 done.store(true, Ordering::Relaxed);
91 break;
92 }
93 }
94
95 (part_one_result.unwrap(), part_two_result.unwrap())
96}
97
98/// Generates recipes then sends them to the reader thread for checking in batches.
99/// Processing is broken into alternating "cold" and "hot" loops. An outer enclosing loop checks
100/// periodically for the done signal from the reader thread.
101///
102/// The "cold" loop processes recipes serially one by one but can handle input corner cases.
103/// It's used when either:
104/// * One or both elves are within the first 23 recipes.
105/// * One or both elves are within the last 16 recipes.
106///
107/// The "hot" loop processes recipes efficiently in chunks of 16. The vast majority of recipes
108/// are calculated in this loop. As much as possible is parallelized using techniques similar to
109/// SIMD but using regular instructions instead of SIMD intrinsics or Rust's portable SIMD API.
110///
111/// Interestingly, on an Apple M2 Max this "poor man's SIMD" has the same performance as using
112/// the portable SIMD API. This is probably due to the fact that the serial loops that write new
113/// recipes take the majority of the time.
114fn writer<'a>(tx: Sender<&'a [u8]>, done: &AtomicBool, mut recipes: &'a mut [u8]) {
115 // The first 23 recipes have already been generated
116 // so the elves start at position 0 and 8 respectively.
117 let mut elf1 = 0;
118 let mut index1 = 0;
119
120 let mut elf2 = 8;
121 let mut index2 = 0;
122
123 let mut base = 0;
124 let mut size = 23;
125 let mut needed = 23;
126
127 // Store the smaller subset of recipes used by the elves.
128 let mut write = 0;
129 let mut snack = vec![0; 5_000_000];
130
131 while !done.load(Ordering::Relaxed) {
132 // Cold loop to handle start and end transitions.
133 while elf1 < 23 || elf2 < 23 || write - index1.max(index2) <= 16 {
134 // After the first 23 recipes both elves converge on the same set of ingredients.
135 let recipe1 = if elf1 < 23 {
136 PREFIX[elf1]
137 } else {
138 index1 += 1;
139 snack[index1 - 1]
140 };
141
142 let recipe2 = if elf2 < 23 {
143 PREFIX[elf2]
144 } else {
145 index2 += 1;
146 snack[index2 - 1]
147 };
148
149 // Add next recipe.
150 let next = recipe1 + recipe2;
151 if next < 10 {
152 recipes[size - base] = next;
153 size += 1;
154 } else {
155 recipes[size - base + 1] = next - 10;
156 size += 2;
157 }
158
159 if needed < size {
160 let digit = recipes[needed - base];
161 needed += 1 + usize::from(digit);
162
163 snack[write] = digit;
164 write += 1;
165 }
166
167 // Wrap around to start if necessary.
168 elf1 += 1 + usize::from(recipe1);
169 if elf1 >= size {
170 elf1 -= size;
171 index1 = 0;
172 }
173
174 elf2 += 1 + usize::from(recipe2);
175 if elf2 >= size {
176 elf2 -= size;
177 index2 = 0;
178 }
179 }
180
181 // Hot loop to handle the majority of recipes in the middle. Process at most 10,000 recipes
182 // at a time in order to produce batches between 160,000 and 320,000 bytes in size.
183 // This size is roughly tuned in order to maximize reader thread throughput.
184 let batch_size = 10_000.min((write - index1.max(index2) - 1) / 16);
185
186 for _ in 0..batch_size {
187 // Snacks can be processed sequentially.
188 let first = from_be_bytes(&snack, index1);
189 let second = from_be_bytes(&snack, index2);
190 let third = from_be_bytes(&snack, index1 + 8);
191 let fourth = from_be_bytes(&snack, index2 + 8);
192
193 // Each elf will skip forward between 16 and 32 snacks. Both halves can be added before
194 // the prefix sum, as the total of 16 digits is at most 144 so always fits in a byte.
195 elf1 += 16 + lsb(prefix_sum(first + third));
196 elf2 += 16 + lsb(prefix_sum(second + fourth));
197 index1 += 16;
198 index2 += 16;
199
200 // Process the digits in parallel using techniques similar to SIMD.
201 let (digits1, indices1, extra1) = unpack(first, second);
202 let (digits2, indices2, extra2) = unpack(third, fourth);
203
204 // Scatter each digit into the correct location, leaving "holes" where ones should go.
205 // This is handled correctly by prefilling `recipes` with ones when initializing.
206 scatter(&mut recipes[size - base..], digits1, indices1);
207 size += extra1;
208 scatter(&mut recipes[size - base..], digits2, indices2);
209 size += extra2;
210
211 // Write the recipes that will actually be used in subsequent loops to a smaller
212 // contiguous vec.
213 while needed < size {
214 let digit = recipes[needed - base];
215 needed += 1 + usize::from(digit);
216
217 snack[write] = digit;
218 write += 1;
219 }
220 }
221
222 // Split the mutable `recipes` slice into two parts. This allows the reader thread to
223 // access the head in parallel while the writer thread continues to write to the tail,
224 // ensuring unique ownership of each part of memory to prevent any concurrency issues.
225 let head = recipes.split_off_mut(..size - base).unwrap();
226 let _unused = tx.send(head);
227 base = size;
228 }
229
230 // Drop the sender to make the receiver hang up.
231 drop(tx);
232}
233
234/// Convert 8 bytes in [big endian order](https://en.wikipedia.org/wiki/Endianness) into a `usize`.
235#[inline]
236fn from_be_bytes(slice: &[u8], index: usize) -> usize {
237 usize::from_be_bytes(slice[index..index + 8].try_into().unwrap())
238}
239
240/// Write each digit to its respective index. Indices are a single byte so always less than 256.
241/// Taking a fixed-size window allows the compiler to remove the bounds check for every write.
242#[inline]
243fn scatter(recipes: &mut [u8], digits: usize, indices: usize) {
244 let window = recipes.first_chunk_mut::<256>().unwrap();
245
246 for shift in (0..64).step_by(8) {
247 let digit = lsb(digits >> shift);
248 let index = lsb(indices >> shift);
249 window[index] = digit as u8;
250 }
251}
252
253/// Convenience function that returns least significant byte.
254#[inline]
255fn lsb(u: usize) -> usize {
256 u & 0xff
257}
258
259/// Compute the prefix sum of each byte within a `usize`. Let `a..h` denote the bytes from most
260/// significant to least significant and `Σx..y` denote the sum from `x` to `y` inclusive.
261///
262/// ```none
263/// s | a | b | c | d | e | f | g | h |
264/// s += (s >> 8) | a | Σa..b | Σb..c | Σc..d | Σd..e | Σe..f | Σf..g | Σg..h |
265/// s += (s >> 16) | a | Σa..b | Σa..c | Σa..d | Σb..e | Σc..f | Σd..g | Σe..h |
266/// s += (s >> 32) | a | Σa..b | Σa..c | Σa..d | Σa..e | Σa..f | Σa..g | Σa..h |
267/// ```
268#[inline]
269fn prefix_sum(mut s: usize) -> usize {
270 s += s >> 8;
271 s += s >> 16;
272 s += s >> 32;
273 s
274}
275
276/// Takes two groups of 8 digits each packed into a `usize` as input, then returns the output
277/// digits and their respective locations. Ones from sums greater than ten are implicit and not
278/// included since recipes has already been pre-filled with ones.
279#[inline]
280fn unpack(first: usize, second: usize) -> (usize, usize, usize) {
281 const ONES: usize = 0x0101010101010101;
282 const SIXES: usize = 0x0606060606060606;
283 const INDICES: usize = 0x0001020304050607;
284
285 // Example values, showing each byte in a column:
286 //
287 // first | 04 | 01 | 09 | 08 | 00 | 03 | 05 | 07 |
288 // second | 03 | 00 | 02 | 04 | 09 | 06 | 05 | 01 |
289 // sum | 07 | 01 | 0b | 0c | 09 | 09 | 0a | 08 |
290 let sum = first + second;
291
292 // Add 6 to each byte so that sums greater than or equal to ten become greater than or equal
293 // to 16, setting the first bit in the high nibble of each byte.
294 //
295 // sum | 07 | 01 | 0b | 0c | 09 | 09 | 0a | 08 |
296 // SIXES | 06 | 06 | 06 | 06 | 06 | 06 | 06 | 06 |
297 // total | 0d | 07 | 11 | 12 | 0f | 0f | 10 | 0e |
298 // tens | 00 | 00 | 01 | 01 | 00 | 00 | 01 | 00 |
299 let tens = ((sum + SIXES) >> 4) & ONES;
300
301 // Multiply by 10 to "spread" a 10 into each byte that has a total greater than 10.
302 //
303 // tens | 00 | 00 | 01 | 01 | 00 | 00 | 01 | 00 |
304 // tens * 10 | 00 | 00 | 0a | 0a | 00 | 00 | 0a | 00 |
305 // digits | 07 | 01 | 01 | 02 | 09 | 09 | 00 | 08 |
306 let digits = sum - 10 * tens;
307
308 // Columns greater than 10 will take 2 bytes when written to recipes. Each index is
309 // offset by the number of 10s before it. Adding the normal increasing indices gives the
310 // final location of each byte.
311 //
312 // tens | 00 | 00 | 01 | 01 | 00 | 00 | 01 | 00 |
313 // prefix sum | 00 | 00 | 01 | 02 | 02 | 02 | 03 | 03 |
314 // INDICES | 00 | 01 | 02 | 03 | 04 | 05 | 06 | 07 |
315 // indices | 00 | 02 | 03 | 05 | 06 | 07 | 09 | 0a |
316 let indices = prefix_sum(tens) + INDICES;
317
318 // The total number of bytes that need to be written is one plus the last index.
319 let extra = 1 + lsb(indices);
320
321 (digits, indices, extra)
322}