Skip to main content

aoc/year2022/
day20.rs

1//! # Grove Positioning System
2//!
3//! We store the numbers in an array of `vec`s. The initial size of each vector is 20
4//! so that numbers are spread as evenly as possible.
5//!
6//! Using multiple leaf `vec`s greatly reduces the time to insert, remove and find
7//! numbers, compared to storing all numbers in a single flat `vec`. Some further optimizations:
8//! * The first and second level indices of a number change only when it moves, so these can be
9//!   stored in a lookup array for fast access.
10//! * The size of each first level `vec` is the sum of the second level `vec`s contained inside.
11//!   This is stored in the `skip` array to prevent recomputing on each move.
12//!
13//! This implementation is both faster and simpler than the previous version (preserved in the
14//! commit history) that used an [order statistic tree](https://en.wikipedia.org/wiki/Order_statistic_tree),
15//! although perhaps adding [balancing rotations](https://en.wikipedia.org/wiki/Tree_rotation)
16//! to the tree would make it faster.
17//!
18//! Leaf `vec`s are padded to a size modulo 64 to speed up searching for numbers. A SIMD variant
19//! can search for 64 numbers simultaneously.
20use std::array::from_fn;
21use std::iter::repeat_n;
22
23use crate::util::parse::*;
24
25struct PaddedVec {
26    size: usize,
27    vec: Vec<u16>,
28}
29
30pub fn parse(input: &str) -> Vec<i64> {
31    input.iter_signed().collect()
32}
33
34pub fn part1(input: &[i64]) -> i64 {
35    decrypt(input, 1, 1)
36}
37
38pub fn part2(input: &[i64]) -> i64 {
39    decrypt(input, 811589153, 10)
40}
41
42fn decrypt(input: &[i64], key: i64, rounds: usize) -> i64 {
43    // Important nuance, size is one less because we don't consider the moving number.
44    let size = input.len() - 1;
45    // Another nuance, input contains duplicate numbers, so use index to refer to each number
46    // uniquely.
47    let indices: Vec<_> = (0..input.len() as u16).collect();
48    // Pre-process the numbers, converting any negative indices to positive indices that will wrap.
49    // For example, -1 becomes 4998.
50    let numbers: Vec<_> =
51        input.iter().map(|&n| (n * key).rem_euclid(size as i64) as usize).collect();
52    // Store location of each number within `mixed` for faster lookup.
53    let mut lookup = Vec::with_capacity(input.len());
54    // Size of each block of 16 elements for faster lookup.
55    let mut skip = [0; 16];
56    // Break 5000 numbers into roughly equal chunks.
57    let mut mixed: [_; 256] = from_fn(|_| PaddedVec { size: 0, vec: Vec::with_capacity(128) });
58
59    for (second, slice) in indices.chunks(input.len().div_ceil(256)).enumerate() {
60        let size = slice.len();
61
62        mixed[second].size = size;
63        mixed[second].vec.resize(size.next_multiple_of(64), 0);
64        mixed[second].vec[..size].copy_from_slice(slice);
65
66        lookup.extend(repeat_n(second, size));
67        skip[second / 16] += size;
68    }
69
70    for _ in 0..rounds {
71        'mix: for index in 0..input.len() {
72            // Quickly find the leaf vector storing the number.
73            let number = numbers[index];
74            let second = lookup[index];
75            let first = second / 16;
76
77            // Third level changes as other numbers are added and removed,
78            // so needs to be checked each time.
79            let third = position(&mixed[second], index as u16);
80
81            // Find the offset of the number by adding the size of all previous `vec`s.
82            let position = third
83                + skip[..first].iter().sum::<usize>()
84                + mixed[16 * first..second].iter().map(|v| v.size).sum::<usize>();
85            // Update our position, wrapping around if necessary.
86            let mut next = (position + number) % size;
87
88            // Remove number from current leaf vector, also updating the first level size.
89            mixed[second].size -= 1;
90            mixed[second].vec.remove(third);
91            mixed[second].vec.push(0);
92            skip[first] -= 1;
93
94            // Find our new destination, by checking `vec`s in order until the total elements
95            // are greater than our new index.
96            for (first, outer) in mixed.chunks_exact_mut(16).enumerate() {
97                if next > skip[first] {
98                    next -= skip[first];
99                } else {
100                    for (second, inner) in outer.iter_mut().enumerate() {
101                        if next > inner.size {
102                            next -= inner.size;
103                        } else {
104                            // Insert number into its new home.
105                            inner.size += 1;
106                            inner.vec.insert(next, index as u16);
107                            inner.vec.resize(inner.size.next_multiple_of(64), 0);
108                            // Update location.
109                            skip[first] += 1;
110                            lookup[index] = 16 * first + second;
111                            continue 'mix;
112                        }
113                    }
114                }
115            }
116        }
117    }
118
119    let indices: Vec<_> =
120        mixed.into_iter().flat_map(|pv| pv.vec.into_iter().take(pv.size)).collect();
121    let zeroth = indices.iter().position(|&i| input[i as usize] == 0).unwrap();
122
123    [1000, 2000, 3000]
124        .iter()
125        .map(|offset| (zeroth + offset) % indices.len())
126        .map(|index| input[indices[index] as usize] * key)
127        .sum()
128}
129
130/// The compiler optimizes the position search when the size of the chunk is known.
131#[cfg(not(feature = "simd"))]
132#[inline]
133fn position(haystack: &PaddedVec, needle: u16) -> usize {
134    for (base, slice) in haystack.vec.chunks_exact(64).enumerate() {
135        if let Some(offset) = slice.iter().position(|&i| i == needle) {
136            return 64 * base + offset;
137        }
138    }
139
140    unreachable!()
141}
142
143/// Search 64 lanes simultaneously.
144#[cfg(feature = "simd")]
145#[inline]
146fn position(haystack: &PaddedVec, needle: u16) -> usize {
147    use std::simd::prelude::*;
148
149    for (base, slice) in haystack.vec.chunks_exact(64).enumerate() {
150        if let Some(offset) =
151            Simd::<u16, 64>::from_slice(slice).simd_eq(Simd::splat(needle)).first_set()
152        {
153            return 64 * base + offset;
154        }
155    }
156
157    unreachable!()
158}