1
0
Fork 0

Make code nicer

This commit is contained in:
Lars Martens 2021-12-11 12:16:03 +01:00
parent cf754c5205
commit 291834774d

View file

@ -13,20 +13,18 @@ fn solve() -> (usize, usize) {
i += 1; i += 1;
// Add one to each octopus // Add one to each octopus
for row in 0..field.len() { field.apply(|o| {
for col in 0..field[0].len() { o.energy += 1;
field[row][col].energy += 1; });
}
}
// Do the flashing // Do the flashing
let mut changed = true; let mut changed = true;
while changed { while changed {
changed = false; changed = false;
for row in 0..field.len() { for row in 0..10 {
for col in 0..field[0].len() { for col in 0..10 {
let current = &mut field[row][col]; let current = &mut field.0[row][col];
if current.energy > 9 && !current.did_flash { if current.energy > 9 && !current.did_flash {
current.did_flash = true; current.did_flash = true;
changed = true; changed = true;
@ -34,7 +32,7 @@ fn solve() -> (usize, usize) {
flashes += 1; flashes += 1;
} }
for (r, c) in neighbors(row, col) { for (r, c) in neighbors(row, col) {
field[r][c].energy += 1; field.0[r][c].energy += 1;
} }
} }
} }
@ -42,20 +40,17 @@ fn solve() -> (usize, usize) {
} }
// Have all octopi flashed? // Have all octopi flashed?
if field.iter().flat_map(|r| r.iter()).all(|o| o.did_flash) { if field.0.iter().flat_map(|r| r.iter()).all(|o| o.did_flash) {
return (flashes, i); return (flashes, i);
} }
// Reset octopi > 9 // Reset octopi > 9
for row in 0..field.len() { field.apply(|o| {
for col in 0..field[0].len() { if o.energy > 9 {
let current = &mut field[row][col]; o.energy = 0;
if current.energy > 9 { o.did_flash = false;
current.energy = 0;
current.did_flash = false;
}
} }
} });
} }
} }
@ -90,7 +85,21 @@ fn neighbors(row: usize, col: usize) -> Vec<(usize, usize)> {
neighbors neighbors
} }
type Field = Vec<Vec<Octopus>>; struct Field(Vec<Vec<Octopus>>);
impl Field {
/// Do something with every octopus
fn apply<F>(&mut self, mut op: F)
where
F: FnMut(&mut Octopus),
{
for row in 0..10 {
for col in 0..10 {
op(&mut self.0[row][col])
}
}
}
}
struct Octopus { struct Octopus {
energy: u32, energy: u32,
@ -98,16 +107,18 @@ struct Octopus {
} }
fn input() -> Field { fn input() -> Field {
include_str!("../../input/11.txt") Field(
.lines() include_str!("../../input/11.txt")
.map(|l| { .lines()
l.chars() .map(|l| {
.map(|c| c.to_digit(10).unwrap()) l.chars()
.map(|n| Octopus { .map(|c| c.to_digit(10).unwrap())
energy: n, .map(|n| Octopus {
did_flash: false, energy: n,
}) did_flash: false,
.collect() })
}) .collect()
.collect() })
.collect(),
)
} }