From 2cf9933300007d5e85ced4a90153af560b78b5be Mon Sep 17 00:00:00 2001 From: Johannes Schaefer Date: Mon, 10 Dec 2018 15:16:06 +0100 Subject: [PATCH] day09 part 2 --- src/main.rs | 4 +-- src/tasks/day09.rs | 70 ++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 66 insertions(+), 8 deletions(-) diff --git a/src/main.rs b/src/main.rs index 71b4610..ed875b3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,4 @@ fn main() { - aoc_2018::tasks::day09::task1(); - // aoc_2018::tasks::day08::task2(); + // aoc_2018::tasks::day09::task1(); + aoc_2018::tasks::day09::task2(); } diff --git a/src/tasks/day09.rs b/src/tasks/day09.rs index 37a5a1e..642f5a6 100644 --- a/src/tasks/day09.rs +++ b/src/tasks/day09.rs @@ -1,6 +1,6 @@ const PLAYERS: usize = 468; const MODULO: usize = 23; -const HIGHEST_MARBLE: usize = 71843; +const HIGHEST_MARBLE: usize = 7184300; pub fn task1() { let mut player_score = [0usize; PLAYERS]; @@ -18,19 +18,77 @@ pub fn task1() { deck.insert(current_index, marble); } current_player = (current_player + 1) % PLAYERS; + if marble % 10000 == 0 { + println!("{} ({}%)", marble, marble as f32 / HIGHEST_MARBLE as f32); + } } let result = player_score.iter().max().unwrap(); - println!("The highest score is {}", result); // 385469 too low + println!("The highest score is {}", result); } pub fn rem(a: usize, sub: usize, m: usize) -> usize { if sub > a { - let mut x = a as isize; - x -= sub as isize; - x = x % m as isize; - (x + m as isize) as usize + (a + m - sub) % m } else { (a - sub) % m } } + +pub fn task2() { + let _dummy_node = ListNode { + value: 0, + id_left: 0, + id_right: 0, + }; + + let mut player_score = [0usize; PLAYERS]; + let mut current_player = 1; + + let mut nodes = Vec::with_capacity(HIGHEST_MARBLE); + nodes.push(ListNode { + value: 0, + id_left: 0, + id_right: 0, + }); + let mut current_node = &nodes[0]; + + for marble in 1..=HIGHEST_MARBLE { + if marble % MODULO == 0 { + for _ in 0..7 { + current_node = &nodes[current_node.id_left]; + } + player_score[current_player] += marble; + player_score[current_player] += current_node.value; + let id_left = current_node.id_left; + let id_right = current_node.id_right; + nodes[id_left].id_right = id_right; + nodes[id_right].id_left = id_left; + current_node = &nodes[id_right]; + } else { + let id_left = current_node.id_right; + let id_right = nodes[current_node.id_right].id_right; + let new = ListNode { + value: marble, + id_left, + id_right, + }; + nodes.push(new); + let id_new = nodes.len() - 1; + nodes[id_left].id_right = id_new; + nodes[id_right].id_left = id_new; + current_node = &nodes[id_new]; + } + current_player = (current_player + 1) % PLAYERS; + } + + let result = player_score.iter().max().unwrap(); + println!("The highest score is {}", result); +} + +#[derive(Debug)] +struct ListNode { + value: usize, + id_left: usize, + id_right: usize, +}