From 7b6e8f05e0be52d88309a547bbf832ebc6a0ac34 Mon Sep 17 00:00:00 2001 From: Sijmen Schoon Date: Wed, 23 Dec 2020 02:38:29 +0100 Subject: [PATCH] rust(day17): Part 1 --- rust/src/day17.rs | 99 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 rust/src/day17.rs diff --git a/rust/src/day17.rs b/rust/src/day17.rs new file mode 100644 index 0000000..eab4d68 --- /dev/null +++ b/rust/src/day17.rs @@ -0,0 +1,99 @@ +use std::time::{Duration, Instant}; + +const SIZE: usize = 50; +const OFFSET: usize = SIZE / 2; + +type Field = Vec>>; + +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() +}