rust(day17): Part 1

This commit is contained in:
Sijmen 2020-12-23 02:38:29 +01:00
parent c53633b1c1
commit 7b6e8f05e0
Signed by: vijfhoek
GPG key ID: DAF7821E067D9C48

99
rust/src/day17.rs Normal file
View file

@ -0,0 +1,99 @@
use std::time::{Duration, Instant};
const SIZE: usize = 50;
const OFFSET: usize = SIZE / 2;
type Field = Vec<Vec<Vec<bool>>>;
pub fn step(field: &mut Field) {
let mut changes = Vec::new();
for (z, slice) in field.iter().enumerate() {
for (y, row) in slice.iter().enumerate() {
for (x, cell) in row.iter().enumerate() {
let mut neighbors = 0;
for dz in -1..=1 {
for dy in -1..=1 {
for dx in -1..=1 {
let nx = dx + x as i64;
let ny = dy + y as i64;
let nz = dz + z as i64;
if (nx == x as i64 && ny == y as i64 && nz == z as i64)
|| (nx < 0 || nx >= SIZE as i64)
|| (ny < 0 || ny >= SIZE as i64)
|| (nz < 0 || nz >= SIZE as i64)
{
continue;
}
if field[nz as usize][ny as usize][nx as usize] {
neighbors += 1;
}
}
}
}
if *cell && neighbors != 2 && neighbors != 3 {
changes.push((x, y, z, false));
}
if !cell && neighbors == 3 {
changes.push((x, y, z, true));
}
}
}
}
for (x, y, z, state) in changes {
field[z][y][x] = state;
}
}
pub fn run(_: bool) -> Duration {
let input = std::fs::read_to_string("../inputs/17").unwrap();
let instant = Instant::now();
let mut field = vec![vec![vec![false; SIZE]; SIZE]; SIZE];
for (y, line) in input.lines().enumerate() {
for (x, cell) in line.chars().enumerate() {
field[OFFSET][y + OFFSET - 1][x + OFFSET - 1] = cell == '#';
}
}
// for y in 0..SIZE {
// for x in 0..SIZE {
// print!("{}", if field[OFFSET][y][x] { '#' } else { '.' });
// }
// println!();
// }
for i in 0..6 {
step(&mut field);
println!("step {}:", i + 1);
// for z in (OFFSET - 1)..=(OFFSET + 1) {
// println!("z = {}", z as i64 - OFFSET as i64);
// for y in 0..SIZE {
// for x in 0..SIZE {
// print!("{}", if field[z][y][x] { '#' } else { '.' });
// }
// println!();
// }
// println!();
// }
}
let mut alive = 0;
for slice in field {
for row in slice {
for cell in row {
if cell {
alive += 1;
}
}
}
}
dbg!(alive);
instant.elapsed()
}