Skip to content

Instantly share code, notes, and snippets.

@neofight78
Created December 25, 2021 05:53
Show Gist options
  • Save neofight78/59ce450253a2d3d648a5134886bc3f69 to your computer and use it in GitHub Desktop.
Save neofight78/59ce450253a2d3d648a5134886bc3f69 to your computer and use it in GitHub Desktop.
Advent of Code 2021 - Day 25: Sea Cucumber
fn main() {
let mut sea_floor = SeaFloor::from(INPUT);
let mut step = 0;
loop {
step += 1;
if !sea_floor.step() {
println!("The sea cucumbers stop moving after step: {}", step);
break;
}
}
}
struct SeaFloor {
width: usize,
height: usize,
east_facing_herd: Vec<Vec<bool>>,
south_facing_herd: Vec<Vec<bool>>,
}
impl SeaFloor {
fn step(&mut self) -> bool {
let mut moved = false;
let mut next = vec![vec![false; self.width]; self.height];
for x in 0..self.width {
let next_x = if x + 1 == self.width { 0 } else { x + 1 };
for (y, next_row) in next.iter_mut().enumerate().take(self.height) {
if !self.east_facing_herd[y][x] {
continue;
}
if self.east_facing_herd[y][next_x] || self.south_facing_herd[y][next_x] {
next_row[x] = true;
} else {
next_row[next_x] = true;
moved = true;
}
}
}
self.east_facing_herd = next;
let mut next = vec![vec![false; self.width]; self.height];
for y in 0..self.height {
let next_y = if y + 1 == self.height { 0 } else { y + 1 };
for x in 0..self.width {
if !self.south_facing_herd[y][x] {
continue;
}
if self.south_facing_herd[next_y][x] || self.east_facing_herd[next_y][x] {
next[y][x] = true;
} else {
next[next_y][x] = true;
moved = true;
}
}
}
self.south_facing_herd = next;
moved
}
}
impl From<&str> for SeaFloor {
fn from(value: &str) -> Self {
let width = value.lines().next().unwrap().len();
let height = value.lines().count();
let mut east_facing_herd = vec![vec![false; width]; height];
let mut south_facing_herd = vec![vec![false; width]; height];
value.lines().enumerate().for_each(|(y, row)| {
row.chars().enumerate().for_each(|(x, c)| match c {
'>' => east_facing_herd[y][x] = true,
'v' => south_facing_herd[y][x] = true,
_ => (),
})
});
Self {
width,
height,
east_facing_herd,
south_facing_herd,
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment