Day 18 part 1.

This commit is contained in:
2024-06-28 10:38:50 +02:00
parent 8551abf624
commit 340fe7025b
2 changed files with 69 additions and 0 deletions

68
src/day18.rs Normal file
View File

@@ -0,0 +1,68 @@
use aoc_runner_derive::{aoc, aoc_generator};
type Field = Vec<Vec<bool>>;
#[aoc_generator(day18)]
fn parse(input: &str) -> Field {
let w = input.lines().next().unwrap().len();
let h = input.lines().count();
let mut result = vec![vec![false; h + 2]; w + 2];
input.lines().enumerate().for_each(|(y, line)| {
line.chars()
.enumerate()
.for_each(|(x, c)| result[x + 1][y + 1] = c == '#');
});
result
}
#[aoc(day18, part1)]
fn part1(input: &Field) -> usize {
let mut current = input.clone();
let mut next = input.clone();
for _ in 0..100 {
for x in 1..current.len() - 1 {
for y in 1..current.len() - 1 {
let now = current[x][y];
let neighbors_on: usize = count_neighbors(&current, x, y);
let new = if now {
neighbors_on == 2 || neighbors_on == 3
} else {
neighbors_on == 3
};
next[x][y] = new;
}
}
(current, next) = (next, current);
}
current.into_iter().flatten().filter(|x| *x).count()
}
fn count_neighbors(field: &Field, x: usize, y: usize) -> usize {
let mut result = 0;
if field[x - 1][y - 1] {
result += 1;
}
if field[x][y - 1] {
result += 1;
}
if field[x + 1][y - 1] {
result += 1;
}
if field[x - 1][y] {
result += 1;
}
if field[x + 1][y] {
result += 1;
}
if field[x - 1][y + 1] {
result += 1;
}
if field[x][y + 1] {
result += 1;
}
if field[x + 1][y + 1] {
result += 1;
}
result
}