From d65dda9e5b818bc1bae6aaf6453145e08f00e5b7 Mon Sep 17 00:00:00 2001 From: Joel Klinghed Date: Sat, 6 Dec 2025 20:34:18 +0100 Subject: Initital commit Day01 - Day06 --- day04/src/main.rs | 96 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 day04/src/main.rs (limited to 'day04/src/main.rs') diff --git a/day04/src/main.rs b/day04/src/main.rs new file mode 100644 index 0000000..0205021 --- /dev/null +++ b/day04/src/main.rs @@ -0,0 +1,96 @@ +use std::io; + +fn valid(map: &[Vec], x: i32, y: i32) -> bool { + if x < 0 { + return false; + } + if y < 0 { + return false; + } + let uy: usize = y.try_into().unwrap(); + if uy >= map.len() { + return false; + } + let ux: usize = x.try_into().unwrap(); + if ux >= map[uy].len() { + return false; + } + true +} + +fn is_paper(map: &[Vec], x: i32, y: i32) -> bool { + if valid(map, x, y) { + let uy: usize = y.try_into().unwrap(); + let ux: usize = x.try_into().unwrap(); + return map[uy][ux] == '@'; + } + false +} + +fn adjacent(map: &[Vec], x: i32, y: i32) -> usize { + let mut count = 0; + for dx in -1..=1 { + if is_paper(map, x + dx, y - 1) { + count += 1; + } + if is_paper(map, x + dx, y + 1) { + count += 1; + } + } + if is_paper(map, x - 1, y) { + count += 1; + } + if is_paper(map, x + 1, y) { + count += 1; + } + count +} + +fn main() { + let mut map: Vec> = Vec::new(); + + loop { + let mut buffer = String::new(); + let bytes = io::stdin().read_line(&mut buffer).unwrap(); + if bytes == 0 { + break; + } + map.push(buffer.trim_end().chars().collect()); + } + + let mut total = 0; + for y in 0..map.len() { + for x in 0..map[y].len() { + if is_paper(&map, x.try_into().unwrap(), y.try_into().unwrap()) + && adjacent(&map, x.try_into().unwrap(), y.try_into().unwrap()) < 4 + { + total += 1; + } + } + } + + println!("{}", total); + + let mut total2 = 0; + loop { + total = 0; + let mut next = map.clone(); + for y in 0..map.len() { + for x in 0..map[y].len() { + if is_paper(&map, x.try_into().unwrap(), y.try_into().unwrap()) + && adjacent(&map, x.try_into().unwrap(), y.try_into().unwrap()) < 4 + { + total += 1; + next[y][x] = 'x'; + } + } + } + if total == 0 { + break; + } + map = next; + total2 += total; + } + + println!("{}", total2); +} -- cgit v1.2.3-70-g09d2