day09 part 2

This commit is contained in:
Johannes Schaefer
2018-12-10 15:16:06 +01:00
parent e5a3a1458a
commit 2cf9933300
2 changed files with 66 additions and 8 deletions

View File

@@ -1,4 +1,4 @@
fn main() { fn main() {
aoc_2018::tasks::day09::task1(); // aoc_2018::tasks::day09::task1();
// aoc_2018::tasks::day08::task2(); aoc_2018::tasks::day09::task2();
} }

View File

@@ -1,6 +1,6 @@
const PLAYERS: usize = 468; const PLAYERS: usize = 468;
const MODULO: usize = 23; const MODULO: usize = 23;
const HIGHEST_MARBLE: usize = 71843; const HIGHEST_MARBLE: usize = 7184300;
pub fn task1() { pub fn task1() {
let mut player_score = [0usize; PLAYERS]; let mut player_score = [0usize; PLAYERS];
@@ -18,19 +18,77 @@ pub fn task1() {
deck.insert(current_index, marble); deck.insert(current_index, marble);
} }
current_player = (current_player + 1) % PLAYERS; 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(); 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 { pub fn rem(a: usize, sub: usize, m: usize) -> usize {
if sub > a { if sub > a {
let mut x = a as isize; (a + m - sub) % m
x -= sub as isize;
x = x % m as isize;
(x + m as isize) as usize
} else { } else {
(a - sub) % m (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,
}