1use std::array::from_fn;
19
20use crate::util::parse::*;
21
22pub fn parse(input: &str) -> Vec<isize> {
23 input.iter_signed().collect()
24}
25
26pub fn part1(input: &[isize]) -> u64 {
28 let mut jump = input.to_vec();
29 let mut total = 0;
30 let mut index = 0;
31
32 while index < jump.len() {
33 let next = index.wrapping_add_signed(jump[index]);
34 jump[index] += 1;
35 total += 1;
36 index = next;
37 }
38
39 total
40}
41
42pub fn part2(input: &[isize]) -> u64 {
43 let mut jump = input.to_vec();
44 let mut total = 0;
45 let mut index = 0;
46
47 let mut fine = 0;
48 let mut compact = Vec::new();
49
50 let cache: Vec<[_; 0x10000]> =
53 Vec::from_fn(3, |offset| from_fn(|value| compute_block(value, offset)));
54
55 while index < jump.len() {
56 if index / 16 < compact.len() {
57 if index % 16 >= 3 {
58 let j = index / 16;
59 let (next, steps, delta) = compute_block(compact[j], index % 16);
60
61 compact[j] = usize::from(next);
62 total += u64::from(steps);
63 index += usize::from(delta);
64 }
65
66 for value in &mut compact[index / 16..] {
68 let (next, steps, delta) = cache[index % 16][*value];
69
70 *value = usize::from(next);
71 total += u64::from(steps);
72 index += usize::from(delta);
73 }
74 } else {
75 let next = index.wrapping_add_signed(jump[index]);
77 jump[index] += if jump[index] == 3 { -1 } else { 1 };
78 total += 1;
79
80 if jump[index] == 2 && index == fine {
83 fine += 1;
84 if fine.is_multiple_of(16) {
85 let value =
86 (fine - 16..fine).rev().fold(0, |acc, i| (acc << 1) | (jump[i] & 1));
87 compact.push(value as usize);
88 }
89 }
90
91 index = next;
92 }
93 }
94
95 total
96}
97
98#[inline]
99fn compute_block(mut value: usize, mut offset: usize) -> (u16, u8, u8) {
100 let start = offset;
101 let mut steps = 0;
102
103 while offset < 16 {
104 value ^= 1 << offset;
105 steps += 1;
106 offset += 3 - ((value >> offset) & 1);
107 }
108
109 (value as u16, steps, (offset - start) as u8)
110}