Advertisement
krzysz00

ADvent of code, day 22

Dec 22nd, 2017
99
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env run-cargo-script
  2. //cargo-deps: num-complex
  3. extern crate num_complex;
  4. use num_complex::Complex;
  5.  
  6. use std::collections::HashMap;
  7.  
  8. use std::io::{stdin,BufRead};
  9.  
  10. type Coord = Complex<i32>;
  11.  
  12. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
  13. enum State {
  14.     Clean,
  15.     Weakened,
  16.     Infected,
  17.     Flagged,
  18. }
  19.  
  20. impl State {
  21.     pub fn next(self, dir: Coord) -> (State, Coord) {
  22.         use State::*;
  23.         const LEFT: Coord = Coord { re: 0, im: 1};
  24.         const RIGHT: Coord = Coord { re: 0, im: -1};
  25.  
  26.         // For part a, adjust cases to remove Weakened and Flagged
  27.         match self {
  28.             Clean => (Weakened, dir * LEFT),
  29.             Weakened => (Infected, dir),
  30.             Infected => (Flagged, dir * RIGHT),
  31.             Flagged => (Clean, -dir),
  32.         }
  33.     }
  34. }
  35.  
  36. type Grid = HashMap<Coord, State>;
  37.  
  38. fn solve(mut grid: Grid, iterations: usize) -> usize {
  39.  
  40.     let mut solution = 0;
  41.  
  42.     let mut loc = Coord::new(0, 0);
  43.     let mut dir = Coord::i();
  44.  
  45.     for _ in 0..iterations {
  46.         let loc_state = grid.get(&loc).cloned().unwrap_or(State::Clean);
  47.         let (new_state, new_dir) = loc_state.next(dir);
  48.         if new_state == State::Infected {
  49.             solution += 1;
  50.         }
  51.         if new_state != State::Clean {
  52.             grid.insert(loc.clone(), new_state);
  53.         }
  54.         else {
  55.             grid.remove(&loc);
  56.         }
  57.  
  58.         dir = new_dir;
  59.         loc += dir;
  60.     }
  61.  
  62.     solution
  63. }
  64.  
  65. fn parse() -> Grid {
  66.     const GRID_SIZE: i32 = 25;
  67.     const GRID_OFFSET: i32 = 12;
  68.     let mut ret = Grid::new();
  69.  
  70.     let stdin = stdin();
  71.     let handle = stdin.lock();
  72.     for (line_idx, line) in handle.lines().enumerate() {
  73.         let col = ((GRID_SIZE - 1) - line_idx as i32) - GRID_OFFSET;
  74.         let line = line.expect("I/O error");
  75.  
  76.         for (entry_idx, entry) in line.chars().enumerate() {
  77.             let row = (entry_idx as i32) - GRID_OFFSET;
  78.             if entry == '#' {
  79.                 ret.insert(Complex::new(row, col), State::Infected);
  80.             }
  81.         }
  82.     }
  83.     ret
  84. }
  85.  
  86. fn main() {
  87.     const N_ITERATIONS: usize = 10_000_000;
  88.     let grid = parse();
  89.     let answer = solve(grid, N_ITERATIONS);
  90.     println!("{}", answer);
  91. }
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement