Skip to content

Commit 4f6b17d

Browse files
committed
2024 day 22
1 parent f2cb83c commit 4f6b17d

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

crates/year2024/src/day22.rs

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
use utils::prelude::*;
2+
3+
/// Simulating a pseudorandom number generator.
4+
#[derive(Clone, Debug)]
5+
pub struct Day22 {
6+
input: Vec<u32>,
7+
}
8+
9+
impl Day22 {
10+
pub fn new(input: &str, _: InputType) -> Result<Self, InputError> {
11+
Ok(Self {
12+
input: parser::number_range(0..=0xFFFFFF).parse_lines(input)?,
13+
})
14+
}
15+
16+
#[must_use]
17+
pub fn part1(&self) -> u64 {
18+
let mut numbers = self.input.clone();
19+
for _ in 0..2000 {
20+
// Inner loop over numbers allows for vectorization
21+
for n in &mut numbers {
22+
*n = Self::next(*n);
23+
}
24+
}
25+
numbers.iter().map(|&n| n as u64).sum()
26+
}
27+
28+
#[must_use]
29+
pub fn part2(&self) -> u32 {
30+
let mut bananas = [0; 130321]; // 19 ** 4
31+
let mut seen = [0; 130321];
32+
for (i, &(mut n)) in self.input.iter().enumerate() {
33+
let mut index = 0;
34+
let mut last_digit = n % 10;
35+
for j in 0..2000 {
36+
let next = Self::next(n);
37+
let digit = next % 10;
38+
39+
index = (9 + digit - last_digit) as usize + ((index % 6859) * 19);
40+
if j >= 3 && seen[index] < i + 1 {
41+
bananas[index] += next % 10;
42+
seen[index] = i + 1;
43+
}
44+
45+
n = next;
46+
last_digit = digit;
47+
}
48+
}
49+
bananas.iter().max().copied().unwrap()
50+
}
51+
52+
#[inline(always)]
53+
fn next(mut n: u32) -> u32 {
54+
n = (n ^ (n << 6)) % 0x1000000;
55+
n = (n ^ (n >> 5)) % 0x1000000;
56+
n = (n ^ (n << 11)) % 0x1000000;
57+
n
58+
}
59+
}
60+
61+
examples!(Day22 -> (u64, u32) [
62+
{input: "1\n10\n100\n2024", part1: 37327623},
63+
{input: "1\n2\n3\n2024", part2: 23},
64+
]);

crates/year2024/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,5 @@ utils::year!(2024 => year2024, ${
2323
19 => day19::Day19,
2424
20 => day20::Day20,
2525
21 => day21::Day21,
26+
22 => day22::Day22,
2627
});

0 commit comments

Comments
 (0)