Created
December 4, 2021 11:35
-
-
Save neofight78/fa79ccfd08028a10d379afccbd135a98 to your computer and use it in GitHub Desktop.
Advent of Code 2021 - Day 4: Giant Squid
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Board { | |
numbers: [[u64; 5]; 5], | |
marked: u64, | |
has_won: bool, | |
} | |
impl Board { | |
fn is_marked(&self, col: usize, row: usize) -> bool { | |
let mask = (1 << col) << (row * 8); | |
(self.marked & mask) != 0 | |
} | |
fn mark(&mut self, col: usize, row: usize) -> bool { | |
let mask = (1 << col) << (row * 8); | |
self.marked |= mask; | |
let row_mask = 0x1F << (8 * row); | |
let column_mask = 0x0101010101 << col; | |
self.has_won |= | |
(self.marked & row_mask) == row_mask || (self.marked & column_mask) == column_mask; | |
self.has_won | |
} | |
fn check_number(&mut self, number: u64) -> bool { | |
for row in 0..5 { | |
for col in 0..5 { | |
if self.numbers[col][row] == number && self.mark(col, row) { | |
return true; | |
} | |
} | |
} | |
false | |
} | |
fn score(&self) -> u64 { | |
let mut total = 0; | |
for row in 0..5 { | |
for col in 0..5 { | |
if !self.is_marked(col, row) { | |
total += self.numbers[col][row]; | |
} | |
} | |
} | |
total | |
} | |
} | |
fn play(caller: &[u64], boards: &mut [Board]) -> u64 { | |
for &number in caller { | |
for board in boards.iter_mut() { | |
if board.check_number(number) { | |
return board.score() * number; | |
} | |
} | |
} | |
panic!("No winner found!"); | |
} | |
fn play_last(caller: &[u64], boards: &mut [Board]) -> u64 { | |
let mut last_score = 0; | |
for &number in caller { | |
for board in boards.iter_mut().filter(|b| !b.has_won) { | |
if board.check_number(number) { | |
last_score = board.score() * number; | |
} | |
} | |
} | |
last_score | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment