summaryrefslogtreecommitdiff
path: root/day04/src/main.rs
diff options
context:
space:
mode:
Diffstat (limited to 'day04/src/main.rs')
-rw-r--r--day04/src/main.rs96
1 files changed, 96 insertions, 0 deletions
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<char>], 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<char>], 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<char>], 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<char>> = 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);
+}