commit 84799e7071da85569c019594c977092b41c4979c
parent fe3669a04ddea58eaef3c57e676126c0f314561e
Author: Shimmy Xu <shimmy.xu@shimmy1996.com>
Date: Fri, 10 Dec 2021 23:41:42 -0600
Add 2021 day 11
Diffstat:
2 files changed, 103 insertions(+), 0 deletions(-)
diff --git a/2021/day11/input.txt b/2021/day11/input.txt
@@ -0,0 +1,10 @@
+3322874652
+5636588857
+7755117548
+5854121833
+2856682477
+3124873812
+1541372254
+8634383236
+2424323348
+2265635842
diff --git a/2021/day11/main.rs b/2021/day11/main.rs
@@ -0,0 +1,93 @@
+#[derive(Debug, Clone)]
+struct Board {
+ board: std::collections::HashMap<(usize, usize), u32>,
+}
+
+impl Board {
+ fn new(input: &Vec<Vec<u32>>) -> Self {
+ let mut board = std::collections::HashMap::<(usize, usize), u32>::new();
+ for x in 0..input.len() {
+ for y in 0..input[0].len() {
+ board.insert((x, y), input[x][y]);
+ }
+ }
+ Board { board }
+ }
+
+ fn step_forward(&mut self) -> i32 {
+ for v in self.board.values_mut() {
+ *v += 1;
+ }
+ let mut tot_flash_count = 0;
+ loop {
+ let mut flash_count = 0;
+ let mut flashed = Vec::<(usize, usize)>::new();
+ for (k, v) in self.board.iter_mut() {
+ if *v > 9 {
+ flash_count += 1;
+ *v = 0;
+ flashed.push(*k);
+ }
+ }
+ for (x, y) in flashed {
+ for dx in -1..=1 {
+ for dy in -1..=1 {
+ if let Some(v) = self
+ .board
+ .get_mut(&((x as i32 + dx) as usize, (y as i32 + dy) as usize))
+ {
+ if *v != 0 {
+ *v += 1;
+ }
+ }
+ }
+ }
+ }
+ tot_flash_count += flash_count;
+ if flash_count == 0 {
+ break;
+ }
+ }
+ tot_flash_count
+ }
+}
+
+fn main() {
+ let input = std::fs::read_to_string("input.txt")
+ .unwrap()
+ .trim()
+ .split('\n')
+ .map(|s| {
+ s.chars()
+ .map(|c| c.to_digit(10).unwrap())
+ .collect::<Vec<u32>>()
+ })
+ .collect::<Vec<_>>();
+ let board = Board::new(&input);
+ // 1613
+ println!("Part 1: {}", part_1(&board));
+ // 510
+ println!("Part 2: {}", part_2(&board));
+}
+
+fn part_1(board: &Board) -> i32 {
+ let mut board = board.clone();
+ let mut total_flashed = 0;
+ for _ in 0..100 {
+ let flashed = board.step_forward();
+ total_flashed += flashed;
+ }
+ total_flashed
+}
+
+fn part_2(board: &Board) -> i32 {
+ let mut board = board.clone();
+ let mut step = 0;
+ loop {
+ let flashed = board.step_forward();
+ step += 1;
+ if flashed as usize == board.board.len() {
+ return step;
+ }
+ }
+}