1use utils::prelude::*;
23/// Simulating a circular buffer.
4#[derive(Clone, Debug)]
5pub struct Day17 {
6 step_size: u32,
7}
89impl Day17 {
10pub fn new(input: &str, _: InputType) -> Result<Self, InputError> {
11Ok(Self {
12 step_size: parser::u32().parse_complete(input)?,
13 })
14 }
1516#[must_use]
17pub fn part1(&self) -> u32 {
18let mut buffer = Vec::with_capacity(2018);
19 buffer.push(0);
2021let mut i = 0;
22for iteration in 1..=2017u16 {
23 i = (i + self.step_size as usize) % buffer.len();
24 buffer.insert(i + 1, iteration);
25 i += 1;
26 }
2728 buffer[(i + 1) % buffer.len()] as u32
29 }
3031#[must_use]
32pub fn part2(&self) -> u32 {
33let mut result = 0u32;
3435// 0 is always at the start of the buffer, so the answer is the last value in position 1,
36 // which is the last value inserted when the spinlock is at 0.
37let (mut i, mut iteration) = (0, 1);
38while iteration <= 50_000_000 {
39if i == 0 {
40 result = iteration;
41 }
4243// Skip iterations until the spinlock wraps around to the start of the buffer again
44let skip_iterations = (iteration - i).div_ceil(self.step_size + 1);
45 iteration += skip_iterations;
46 i = (i + skip_iterations * (self.step_size + 1)) % iteration;
47 }
4849 result
50 }
51}
5253examples!(Day17 -> (u32, u32) [
54 {input: "3", part1: 638},
55]);