use std::error::Error; use std::fs::File; use std::io::{self, BufRead}; use std::vec::Vec; fn flash(x: i32, y: i32, grid: &mut Vec>) { for dy in [-1, 0, 1] { for dx in [-1, 0, 1] { if dx == 0 && dy == 0 { continue; } let ax = x + dx; let ay = y + dy; if ay < 0 || ay as usize >= grid.len() { continue; } if ax < 0 || ax as usize >= grid[ay as usize].len() { continue; } if grid[ay as usize][ax as usize] > 0 { grid[ay as usize][ax as usize] += 1; } } } grid[y as usize][x as usize] = 0; } fn print_grid(grid: &Vec>) { for y in 0..grid.len() { for x in 0..grid[y].len() { print!("{}", grid[y][x]); } println!(""); } println!(); } fn main() -> Result<(), Box> { let file = File::open("inputs/day11.txt")?; let mut grid: Vec> = io::BufReader::new(file) .lines() .map(|l| { l.unwrap() .chars() .map(|c| c.to_digit(10).unwrap()) .collect() }) .collect(); let mut answer1 = 0; let mut step = 0; while grid.iter().any(|r| r.iter().any(|e| e > &0)) { let mut next_grid: Vec> = grid .iter() .map(|r| r.iter().map(|e| e + 1).collect()) .collect(); while next_grid.iter().any(|r| r.iter().any(|e| e > &9)) { for y in 0..next_grid.len() { for x in 0..next_grid[y].len() { if next_grid[y][x] > 9 { flash(x as i32, y as i32, &mut next_grid); if step < 100 { answer1 += 1; } } } } } grid = next_grid; step += 1; println!("Step {}", step); print_grid(&grid); } println!("Answer1: {}", answer1); println!("Answer2: {}", step); Ok(()) }