Created
December 22, 2024 20:14
-
-
Save jmikkola/d03bed1efbf7c3a98991e956c0fd500e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::env; | |
use std::fs; | |
// use std::collections::HashMap; | |
use hashbrown::HashMap; | |
fn main() { | |
let numbers = split_lines(read_input()); | |
println!("Part 1: {}", part1(&numbers)); | |
println!("Part 2: {}", part2(&numbers)); | |
} | |
fn part1(numbers: &[i64]) -> i64 { | |
let mut total = 0; | |
for n in numbers.iter() { | |
total += compute(*n, 2000); | |
} | |
total | |
} | |
fn part2(numbers: &[i64]) -> i64 { | |
let mut sums = HashMap::new(); | |
for n in numbers.iter() { | |
let seqs = sequences(*n, 2000); | |
for (key, value) in seqs.iter() { | |
let existing = sums.get(key).cloned().unwrap_or(0); | |
sums.insert(*key, existing + (*value as i64)); | |
} | |
} | |
sums.values().max().cloned().unwrap() | |
} | |
fn sequences(secret: i64, steps: i32) -> HashMap<(i8, i8, i8, i8), i8> { | |
let mut diffs = vec![]; | |
let mut values = vec![]; | |
let mut x = secret; | |
for _ in 0..steps { | |
let prev = (x % 10) as i8; | |
let next = step(x); | |
let value = (next % 10) as i8; | |
let diff = value - prev; | |
diffs.push(diff); | |
values.push(value); | |
x = next; | |
} | |
let mut result = HashMap::new(); | |
for i in 3..(steps as usize) { | |
let seq = (diffs[i - 3], diffs[i - 2], diffs[i - 1], diffs[i]); | |
if !result.contains_key(&seq) { | |
result.insert(seq, values[i]); | |
} | |
} | |
result | |
} | |
fn compute(secret: i64, steps: i32) -> i64 { | |
let mut x = secret; | |
for _ in 0..steps { | |
x = step(x); | |
} | |
x | |
} | |
fn step(mut x: i64) -> i64 { | |
x = (x * 64) ^ x; | |
x %= 16777216; | |
x = (x >> 5) ^ x; | |
x %= 16777216; | |
x = (x * 2048) ^ x; | |
x %= 16777216; | |
x | |
} | |
fn read_input() -> String { | |
get_content(get_arg()) | |
} | |
fn get_arg() -> String { | |
match env::args().nth(1) { | |
Some(f) => f, | |
None => "example".into(), | |
} | |
} | |
fn get_content(filename: String) -> String { | |
fs::read_to_string(filename).unwrap().trim().to_string() | |
} | |
fn split_lines(s: String) -> Vec<i64> { | |
s.split('\n') | |
.map(|line| line.parse().unwrap()) | |
.collect() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment