Expand description
Β§Chocolate Charts
This solution is heavily inspired by Askalskiβs excellent post Breaking the 1 billion recipes per second barrier.
The key insight is that after 23 recipes the elves converge into using the same subset of recipes. This subset can be stored compactly in about 20% of the space and read sequentially to allow efficient vector processing.
Tricks used to speed things up:
- Separate writer and reader threads to generate recipes and check them in parallel.
- Vector processing of recipes using techniques similar to SIMD.
ConstantsΒ§
- PREFIX π
- Pre-calculate the first 23 recipes.
FunctionsΒ§
- from_
be_ πbytes - Convert 8 bytes in big endian order into a
usize. - lsb π
- Convenience function that returns least significant byte.
- parse
- part1
- part2
- prefix_
sum π - Compute the prefix sum of each byte within a
usize. Leta..hdenote the bytes from most significant to least significant andΞ£x..ydenote the sum fromxtoyinclusive. - reader π
- Receives batches of recipes from the writer thread, then scans them byte by byte searching for the part two pattern. For simplicity the pattern is always assumed to be six digits.
- scatter π
- Write each digit to its respective index. Indices are a single byte so always less than 256. Taking a fixed-size window allows the compiler to remove the bounds check for every write.
- unpack π
- Takes two groups of 8 digits each packed into a
usizeas input, then returns the output digits and their respective locations. Ones from sums greater than ten are implicit and not included since recipes has already been pre-filled with ones. - writer π
- Generates recipes then sends them to the reader thread for checking in batches. Processing is broken into alternating βcoldβ and βhotβ loops. An outer enclosing loop checks periodically for the done signal from the reader thread.
Type AliasesΒ§
- Input π