93 lines
3.0 KiB
Rust
93 lines
3.0 KiB
Rust
use std::fs::File;
|
|
use std::io::{BufReader};
|
|
use std::io::prelude::*;
|
|
|
|
const RADIX: u32 = 10;
|
|
|
|
static mut LINE_VEC: Vec<Vec<u32>> = Vec::new();
|
|
static mut TOTAL_FLASHES: u32 = 0;
|
|
|
|
const STEPS: u32 = 300;
|
|
|
|
fn main(){
|
|
let file = File::open("./input.txt").expect("Read failed");
|
|
let reader = BufReader::new(file);
|
|
|
|
|
|
|
|
for line in reader.lines(){
|
|
let line_as_string = line.unwrap();
|
|
let line_as_int_vec = line_as_string.chars().map(|x| x.to_digit(RADIX).unwrap()).collect::<Vec<u32>>();
|
|
unsafe{LINE_VEC.push(line_as_int_vec);}
|
|
|
|
}
|
|
unsafe {
|
|
let height = LINE_VEC.len();
|
|
let width = LINE_VEC[0].len();
|
|
|
|
|
|
for _i in 1..=STEPS {
|
|
// Energy of each Octopus increases by 1
|
|
for line_nr in 0..height {
|
|
for column_nr in 0..width {
|
|
LINE_VEC[line_nr][column_nr] += 1;
|
|
}
|
|
}
|
|
|
|
// Flash all Octopus over 9 and reset to 9
|
|
for line_nr in 0..height {
|
|
for column_nr in 0..width {
|
|
if LINE_VEC[line_nr][column_nr] > 9 {
|
|
flash(line_nr, column_nr, height, width);
|
|
}
|
|
}
|
|
}
|
|
// Reset all flashed to 0
|
|
for line_nr in 0..height {
|
|
for column_nr in 0..width {
|
|
if LINE_VEC[line_nr][column_nr] >98 {
|
|
LINE_VEC[line_nr][column_nr] = 0;
|
|
}
|
|
}
|
|
}
|
|
// Check if all flash
|
|
let mut all_flashed = true;
|
|
for line_nr in 0..height {
|
|
for column_nr in 0..width {
|
|
if LINE_VEC[line_nr][column_nr] != 0 {
|
|
all_flashed = false;
|
|
}
|
|
}
|
|
}
|
|
if all_flashed {println!("All Flashed at step {}", _i);}
|
|
}
|
|
|
|
}
|
|
|
|
unsafe { println!("Total flashes: {}", TOTAL_FLASHES); }
|
|
}
|
|
|
|
|
|
fn flash(line_nr: usize, column_nr: usize, height: usize, width: usize) {
|
|
unsafe {
|
|
//Set Current Octopus to 0
|
|
if LINE_VEC[line_nr][column_nr] == 10 || LINE_VEC[line_nr][column_nr] == 9 {
|
|
LINE_VEC[line_nr][column_nr] = 99;
|
|
TOTAL_FLASHES += 1;
|
|
|
|
if line_nr > 0 && column_nr > 0 {flash(line_nr - 1, column_nr - 1, height, width);}
|
|
if line_nr > 0 {flash(line_nr - 1, column_nr, height, width);}
|
|
if line_nr > 0 && column_nr < width - 1 {flash(line_nr - 1, column_nr + 1, height, width);}
|
|
|
|
if column_nr > 0 {flash(line_nr, column_nr - 1, height, width);}
|
|
if column_nr < width - 1 {flash(line_nr , column_nr + 1, height, width);}
|
|
|
|
if line_nr < height - 1 && column_nr > 0 {flash(line_nr + 1, column_nr - 1, height, width);}
|
|
if line_nr < height - 1 {flash(line_nr + 1, column_nr, height, width);}
|
|
if line_nr < height - 1 && column_nr < width - 1 {flash(line_nr + 1, column_nr + 1, height, width);}
|
|
} else {
|
|
LINE_VEC[line_nr][column_nr] += 1;
|
|
}
|
|
}
|
|
}
|