From ad57cc604e983dfa7c3d1cc8b7567d5ecd6e1511 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Mon, 17 Dec 2018 14:26:23 -0800 Subject: [PATCH] [2018][rust][13.1] --- 2018/rust/src/bin/day_14.rs | 55 +++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 2018/rust/src/bin/day_14.rs diff --git a/2018/rust/src/bin/day_14.rs b/2018/rust/src/bin/day_14.rs new file mode 100644 index 0000000..c7afbec --- /dev/null +++ b/2018/rust/src/bin/day_14.rs @@ -0,0 +1,55 @@ +use std::error::Error; + +use advent_of_code::main; + +main!(); + +fn solve(_input: &str) -> Result> { + let elves = vec![0, 1]; + let recipes = vec![3, 7]; + let mut scoreboard = Scoreboard { elves, recipes }; + + let n = 919_901; + let recipes = scoreboard.find(|x| x.len() > n + 9).unwrap(); + let score: String = recipes[n..n + 10].iter().map(|&x| x.to_string()).collect(); + + Ok(score) +} + +#[derive(Debug)] +struct Scoreboard { + elves: Vec, + recipes: Vec, +} + +impl Iterator for Scoreboard { + type Item = Vec; + + fn next(&mut self) -> Option { + self.elves + .iter() + .map(|&x| self.recipes[x]) + .sum::() + .to_string() + .chars() + .map(|x| x.to_digit(10).unwrap() as usize) + .for_each(|x| self.recipes.push(x)); + self.elves = self + .elves + .iter() + .map(|&x| (1 + self.recipes[x] + x) % self.recipes.len()) + .collect(); + + Some(self.recipes.clone()) + } +} + +#[test] +fn test_scoreboard() { + let elves = vec![0, 1]; + let recipes = vec![3, 7]; + let mut scoreboard = Scoreboard { elves, recipes }; + + let recipes = scoreboard.next().unwrap(); + assert_eq!(recipes, vec![3, 7, 1, 0]); +}