Skip to content

Instantly share code, notes, and snippets.

@icub3d
Created January 30, 2026 00:19
Show Gist options
  • Select an option

  • Save icub3d/6d39c424ba8fc16b6b2649f7ec57fcb1 to your computer and use it in GitHub Desktop.

Select an option

Save icub3d/6d39c424ba8fc16b6b2649f7ec57fcb1 to your computer and use it in GitHub Desktop.
Solution for Advent of Code 2017 Day 6
use std::time::Instant;
use rustc_hash::{FxHashMap, FxHashSet};
const INPUT: &str = include_str!("inputs/day06.txt");
fn parse(input: &str) -> Vec<usize> {
input
.split_whitespace()
.map(|v| v.parse::<usize>().unwrap())
.collect()
}
fn p1(input: &str) -> usize {
let mut bank = parse(input);
let mut seen = FxHashSet::default();
let mut iterations = 0;
loop {
iterations += 1;
// Find the largest values (lower index preference).
let (i, &v) = bank
.iter()
.enumerate()
.max_by(|(i1, v1), (i2, v2)| v1.cmp(v2).then(i2.cmp(i1)))
.unwrap();
// Redistribute.
bank[i] = 0;
for n in i + 1..i + 1 + v {
let n = n % bank.len();
bank[n] += 1;
}
// Check for seen.
if !seen.insert(bank.clone()) {
return iterations;
}
}
}
fn p2(input: &str) -> usize {
let mut bank = parse(input);
let mut seen = FxHashMap::default();
let mut iterations: usize = 0;
loop {
iterations += 1;
// Find the largest values (lower index preference).
let (i, &v) = bank
.iter()
.enumerate()
.max_by(|(i1, v1), (i2, v2)| v1.cmp(v2).then(i2.cmp(i1)))
.unwrap();
// Redistribute.
bank[i] = 0;
for n in i + 1..i + 1 + v {
let n = n % bank.len();
bank[n] += 1;
}
// Check for seen.
if let Some(original) = seen.get(&bank.clone()) {
return iterations - original;
} else {
seen.insert(bank.clone(), iterations);
}
}
}
fn main() {
let now = Instant::now();
let solution = p1(INPUT);
println!("p1 {:?} {}", now.elapsed(), solution);
let now = Instant::now();
let solution = p2(INPUT);
println!("p2 {:?} {}", now.elapsed(), solution);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_p1() {
let input = "0 2 7 0";
assert_eq!(p1(input), 5);
}
#[test]
fn test_p2() {
let input = "0 2 7 0";
assert_eq!(p2(input), 4);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment