Last active
December 12, 2021 04:25
-
-
Save neofight78/cb354450da2ef17ce35e902e18fbf7da to your computer and use it in GitHub Desktop.
Advent of Code 2021 - Day 11: Dumbo Octopus
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 Map { | |
octopuses: Vec<Vec<u32>>, | |
width: usize, | |
height: usize, | |
} | |
impl Map { | |
fn parse(input: &str) -> Self { | |
let octopuses = input | |
.lines() | |
.map(|l| { | |
l.chars() | |
.map(|c| c.to_digit(10).unwrap()) | |
.collect::<Vec<_>>() | |
}) | |
.collect::<Vec<_>>(); | |
let width = octopuses[0].len(); | |
let height = octopuses.len(); | |
Self { | |
octopuses, | |
width, | |
height, | |
} | |
} | |
#[allow(dead_code)] | |
fn find_first_simultaneous_flash(&mut self) -> u32 { | |
let mut count = 0; | |
loop { | |
count += 1; | |
if self.step() == self.width * self.height { | |
return count; | |
} | |
} | |
} | |
#[allow(dead_code)] | |
fn count_flashes(&mut self, steps: u32) -> usize { | |
let mut total = 0; | |
for _ in 0..steps { | |
total += self.step() | |
} | |
total | |
} | |
fn step(&mut self) -> usize { | |
for row in 0..self.height { | |
for col in 0..self.width { | |
self.octopuses[row][col] += 1; | |
} | |
} | |
let mut flashed = 0; | |
for row in 0..self.height { | |
for col in 0..self.width { | |
if self.octopuses[row][col] > 9 { | |
flashed += self.flash(row, col); | |
} | |
} | |
} | |
flashed | |
} | |
fn flash(&mut self, row: usize, col: usize) -> usize { | |
if self.octopuses[row][col] == 0 { | |
return 0; | |
} | |
self.octopuses[row][col] += 1; | |
if self.octopuses[row][col] <= 9 { | |
return 0; | |
} | |
self.octopuses[row][col] = 0; | |
let mut flashed = 1; | |
if row > 0 && col > 0 { | |
flashed += self.flash(row - 1, col - 1); | |
} | |
if col > 0 { | |
flashed += self.flash(row, col - 1); | |
} | |
if row < self.height - 1 && col > 0 { | |
flashed += self.flash(row + 1, col - 1) | |
}; | |
if row > 0 { | |
flashed += self.flash(row - 1, col); | |
} | |
if row < self.height - 1 { | |
flashed += self.flash(row + 1, col); | |
} | |
if row > 0 && col < self.height - 1 { | |
flashed += self.flash(row - 1, col + 1) | |
}; | |
if col < self.width - 1 { | |
flashed += self.flash(row, col + 1) | |
}; | |
if row < self.height - 1 && col < self.width - 1 { | |
flashed += self.flash(row + 1, col + 1) | |
}; | |
flashed | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment