Advertisement
krzysz00

Advent of code, day 25

Dec 25th, 2017
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.85 KB | None | 0 0
  1. use std::collections::HashMap;
  2. use std::fmt::Debug;
  3.  
  4. #[derive(PartialEq, Eq, Debug, Clone)]
  5. struct TuringMachine<S: Eq + Debug + Copy> {
  6.     pc: isize,
  7.     tape: HashMap<isize, bool>,
  8.     state: S,
  9.     transitions: fn (S, bool) -> (S, bool, isize),
  10. }
  11.  
  12. impl<S: Eq + Debug + Copy> TuringMachine<S> {
  13.     pub fn new(transitions: fn(S, bool) -> (S, bool, isize),
  14.                start_state: S) -> Self {
  15.         TuringMachine { pc: 0, tape: HashMap::new(), state: start_state,
  16.                         transitions: transitions }
  17.     }
  18.  
  19.     pub fn step(&mut self) {
  20.         let loc = self.tape.entry(self.pc);
  21.         let val = loc.or_insert(false);
  22.         let (new_state, write, delta_pc) = (self.transitions)(self.state, *val);
  23.         *val = write;
  24.         self.state = new_state;
  25.         self.pc += delta_pc;
  26.     }
  27.  
  28.     pub fn checksum(&self) -> usize {
  29.         self.tape.values().map(|&x| x as usize).sum()
  30.     }
  31. }
  32.  
  33. #[derive(Clone, Copy, Debug, PartialEq, Eq)]
  34. enum State { A, B, C, D, E, F }
  35.  
  36. impl State {
  37.     pub fn step(self, read: bool) -> (Self, bool, isize) {
  38.         use State::*;
  39.         match (self, read) {
  40.             (A, false) => (B, true, 1),
  41.             (A, true) => (F, false, -1),
  42.             (B, false) => (C, false, 1),
  43.             (B, true) => (D, false, 1),
  44.             (C, false) => (D, true, -1),
  45.             (C, true) => (E, true, 1),
  46.             (D, false) => (E, false, -1),
  47.             (D, true) => (D, false, -1),
  48.             (E, false) => (A, false, 1),
  49.             (E, true) => (C, true, 1),
  50.             (F, false) => (A, true, -1),
  51.             (F, true) => (A, true, 1),
  52.         }
  53.     }
  54. }
  55.  
  56. fn main() {
  57.     const N_ITERATIONS: usize = 12994925;
  58.     let mut tm = TuringMachine::new(State::step, State::A);
  59.     for _ in 0..N_ITERATIONS {
  60.         tm.step();
  61.     }
  62.     println!("{}", tm.checksum());
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement