Guest User

Untitled

a guest
Dec 11th, 2021
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.99 KB | None | 0 0
  1. fn flash(input: &mut [Vec<u8>], flashed: &mut Vec<(usize, usize)>, i: i32, j: i32) {
  2.     if input[i as usize][j as usize] < 10 {
  3.         return;
  4.     }
  5.  
  6.     // This one is flashing and hasn't been counted yet...
  7.     if !flashed.contains(&(i as usize, j as usize)) {
  8.         flashed.push((i as usize, j as usize));
  9.         let neighbors = [
  10.             (i - 1, j - 1), (i - 1, j), (i - 1, j + 1),
  11.             (i, j - 1), (i, j + 1),
  12.             (i + 1, j - 1), (i + 1, j), (i + 1, j + 1),
  13.         ];
  14.         for &(c, r) in &neighbors {
  15.             if c < 0 || r < 0 {
  16.                 continue;
  17.             }
  18.             if input.get(c as usize).and_then(|row| row.get(r as usize)).is_none() {
  19.                 continue;
  20.             }
  21.             input[c as usize][r as usize] += 1;
  22.             flash(input, flashed, c, r);
  23.         }
  24.     }
  25. }
  26.  
  27. fn step(input: &mut [Vec<u8>]) -> usize {
  28.     let mut flashed: Vec<(usize, usize)> = Vec::new();
  29.     // Step : each level of octopuses increase by one...
  30.     input.iter_mut().flatten().for_each(|e| *e += 1);
  31.     // Step: octopuses flash
  32.     for i in 0..10 {
  33.         for j in 0..10 {
  34.             flash(input, &mut flashed, i, j);
  35.         }
  36.     }
  37.     // Step: octopuses reset to 0...
  38.     input.iter_mut().flatten().for_each(|e| if *e > 9 { *e = 0 });
  39.  
  40.     flashed.len()
  41. }
  42.  
  43. fn aoc_11_part1(input: &mut Vec<Vec<u8>>) -> usize {
  44.     let mut c = input.clone();
  45.     (0..100).map(|_| step(&mut c)).sum::<usize>()
  46. }
  47.  
  48. fn aoc_11_part2(input: &mut Vec<Vec<u8>>) -> usize {
  49.     let mut c = input.clone();
  50.     (0..1000).find(|_| step(&mut c) == 100).unwrap_or(0) + 1
  51. }
  52.  
  53. fn main() {
  54.     let mut s: Vec<Vec<u8>> = include_str!("../input.txt").lines().into_iter()
  55.         .map(|line| line.chars().filter_map(|c| c.to_string().parse::<u8>().ok()).collect::<Vec<u8>>())
  56.         .collect();
  57.  
  58.     let result = aoc_11_part1(&mut s);
  59.     println!("Result 1 is: {}", result);
  60.  
  61.     let result = aoc_11_part2(&mut s);
  62.     println!("Result 2 is: {}", result);
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment