|
| 1 | +//! [Day 22: Monkey Market](https://adventofcode.com/2024/day/22) |
| 2 | +
|
| 3 | +use std::collections::{HashMap, HashSet}; |
| 4 | + |
| 5 | +fn next_secret(secret: i64) -> i64 { |
| 6 | + let secret = (secret ^ (secret * 64)) % 16777216; |
| 7 | + let secret = (secret ^ (secret / 32)) % 16777216; |
| 8 | + let secret = (secret ^ (secret * 2048)) % 16777216; |
| 9 | + secret |
| 10 | +} |
| 11 | + |
| 12 | +struct Puzzle { |
| 13 | + initial_secrets: Vec<i64>, |
| 14 | +} |
| 15 | + |
| 16 | +impl Puzzle { |
| 17 | + fn new() -> Puzzle { |
| 18 | + Puzzle { |
| 19 | + initial_secrets: Vec::new(), |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + /// Get the puzzle input. |
| 24 | + fn configure(&mut self, path: &str) { |
| 25 | + let data = std::fs::read_to_string(path).unwrap(); |
| 26 | + |
| 27 | + self.initial_secrets |
| 28 | + .extend(data.lines().map_while(|s| s.parse::<i64>().ok())); |
| 29 | + } |
| 30 | + |
| 31 | + /// Solve part one. |
| 32 | + fn part1(&self) -> i64 { |
| 33 | + self.initial_secrets |
| 34 | + .iter() |
| 35 | + .map(|&initial_secret| (0..2000).fold(initial_secret, |secret, _| next_secret(secret))) |
| 36 | + .sum() |
| 37 | + } |
| 38 | + |
| 39 | + /// Solve part two. |
| 40 | + fn part2(&self) -> i64 { |
| 41 | + let mut bananas = HashMap::new(); |
| 42 | + |
| 43 | + for &initial_secret in &self.initial_secrets { |
| 44 | + let mut prices = Vec::new(); |
| 45 | + |
| 46 | + let mut secret = initial_secret; |
| 47 | + prices.push(secret % 10); |
| 48 | + for _ in 0..2000 { |
| 49 | + secret = next_secret(secret); |
| 50 | + prices.push(secret % 10); |
| 51 | + } |
| 52 | + |
| 53 | + let mut seen = HashSet::new(); |
| 54 | + for p in prices.windows(5) { |
| 55 | + let sequence = [p[1] - p[0], p[2] - p[1], p[3] - p[2], p[4] - p[3]]; |
| 56 | + |
| 57 | + if !seen.contains(&sequence) { |
| 58 | + seen.insert(sequence); |
| 59 | + *bananas.entry(sequence).or_default() += p[4]; |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + *bananas.values().max().unwrap() |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +fn main() { |
| 69 | + let args = aoc::parse_args(); |
| 70 | + let mut puzzle = Puzzle::new(); |
| 71 | + puzzle.configure(args.path.as_str()); |
| 72 | + println!("{}", puzzle.part1()); |
| 73 | + println!("{}", puzzle.part2()); |
| 74 | +} |
| 75 | + |
| 76 | +/// Test from puzzle input |
| 77 | +#[cfg(test)] |
| 78 | +mod test { |
| 79 | + use super::*; |
| 80 | + |
| 81 | + #[test] |
| 82 | + fn test01() { |
| 83 | + let mut puzzle = Puzzle::new(); |
| 84 | + puzzle.configure("test.txt"); |
| 85 | + assert_eq!(puzzle.part1(), 37327623); |
| 86 | + } |
| 87 | + |
| 88 | + #[test] |
| 89 | + fn test02() { |
| 90 | + let mut puzzle = Puzzle::new(); |
| 91 | + puzzle.configure("test.txt"); |
| 92 | + assert_eq!(puzzle.part2(), 23 + 1); |
| 93 | + } |
| 94 | +} |
0 commit comments