Implement day 9 part 1.

This commit is contained in:
2018-12-09 10:47:21 +01:00
parent cf6f4f9e1e
commit 1d5869af70
4 changed files with 83 additions and 0 deletions

1
2018/inputs/09.txt Normal file
View File

@@ -0,0 +1 @@
419 players; last marble is worth 72164 points

80
2018/src/day09.rs Normal file
View File

@@ -0,0 +1,80 @@
use common::Solution;
use std::io::Read;
fn winning_marbles(elves: usize, marbles: usize) -> usize {
let mut scores = vec![0usize; elves];
let mut state = Vec::new();
state.push(0);
let mut current = 0;
for marble in 1..=marbles {
if marble % 23 == 0 {
let player = marble % elves;
for _ in 0..7 {}
let to_remove = (current + state.len() - 7) % state.len();
scores[player] += marble + state[to_remove];
state.remove(to_remove);
current = to_remove;
} else {
let after = (current + 1) % state.len();
if after == state.len() - 1 {
state.push(marble);
} else {
state.insert(after + 1, marble);
}
current = after + 1;
}
}
*scores.iter().max().unwrap()
}
#[derive(Default)]
pub struct Day09 {}
impl Day09 {
pub fn new() -> Self {
Default::default()
}
fn read_input(input: &mut Read) -> (usize, usize) {
let mut data = String::new();
input.read_to_string(&mut data).unwrap();
let mut parts = data.split(" ");
let elves = parts.next().unwrap().parse().unwrap();
let marbles = parts.skip(5).next().unwrap().parse().unwrap();
(elves, marbles)
}
}
impl Solution for Day09 {
fn part1(&mut self, input: &mut Read) -> String {
let (elves, marbles) = Day09::read_input(input);
format!("{}", winning_marbles(elves, marbles))
}
fn part2(&mut self, input: &mut Read) -> String {
let (elves, marbles) = Day09::read_input(input);
format!("{}", winning_marbles(elves, marbles * 100))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_winning_marbles() {
assert_eq!(32, winning_marbles(9, 25));
assert_eq!(8317, winning_marbles(10, 1618));
assert_eq!(146373, winning_marbles(13, 7999));
assert_eq!(2764, winning_marbles(17, 1104));
assert_eq!(54718, winning_marbles(21, 6111));
assert_eq!(37305, winning_marbles(30, 5807));
}
}

View File

@@ -11,3 +11,4 @@ pub mod day05;
pub mod day06; pub mod day06;
pub mod day07; pub mod day07;
pub mod day08; pub mod day08;
pub mod day09;

View File

@@ -20,6 +20,7 @@ fn get_impl(day: u32) -> Box<common::Solution> {
6 => Box::new(day06::Day06::new()), 6 => Box::new(day06::Day06::new()),
7 => Box::new(day07::Day07::new()), 7 => Box::new(day07::Day07::new()),
8 => Box::new(day08::Day08::new()), 8 => Box::new(day08::Day08::new()),
9 => Box::new(day09::Day09::new()),
val => panic!("Unimplemented day {}", val), val => panic!("Unimplemented day {}", val),
} }
} }