day10.rs (2382B)
1 use std::ops::Add; 2 3 fn cycles(op: &str) -> usize { 4 match op { 5 "noop" => 1, 6 "addx" => 2, 7 unk => panic!("unknown op {}", unk) 8 } 9 } 10 11 fn op_and_args(instruction: &str) -> (&str, Option<i32>) { 12 let mut toks = instruction.split_whitespace(); 13 let op = toks.next().expect("expected an operator!"); 14 let arg = match op { 15 "noop" => None, 16 "addx" => { 17 let arg1: i32 = toks.next().expect("expected one arg for addx").parse().expect("arg for addx must be i32"); 18 Some(arg1) 19 }, 20 unk => panic!("unknown op {}", unk) 21 }; 22 (op,arg) 23 } 24 25 fn apply(op: &str, arg: Option<i32>, x: i32) -> i32 { 26 match op { 27 "noop" => x, 28 "addx" => x + arg.expect("addx had no argument!"), 29 unk => panic!("unknown op {}", unk) 30 } 31 } 32 33 pub fn run(input: String) { 34 let mut lines = input.lines().into_iter(); 35 // our (single) register 36 let mut x = 1; 37 let mut tick = 1; 38 let first_instruction: &str = lines.next().expect("expected a first instruction!"); 39 let (mut op, mut arg) = op_and_args(first_instruction); 40 let mut circ = cycles(op); 41 //let mut sss = 0; 42 let mut screen = "".to_owned(); 43 loop { 44 // Start of cycle, Load next instruction 45 if circ == 0 { 46 if let Some(next_inst) = lines.next() { 47 (op, arg)= op_and_args(next_inst); 48 circ = cycles(op); 49 } else { 50 break; 51 } 52 } 53 // Time passes.... 54 circ -= 1; 55 56 // Pt1, signal strength 57 // if (tick + 20) % 40 == 0 { 58 // let ss = tick*x; 59 // //println!("tick {} x {} ss {}", tick, x, ss); 60 // sss += ss; 61 // } 62 63 // Pt2, Draw pixels! note crt_col is one less(!) than tick 64 let crt_col = (tick-1) % 40; 65 //println!("tick {} x {} crt_col {}", tick, x, crt_col); 66 screen = screen.add(if crt_col >= (x-1) && crt_col <= (x+1) { 67 "#" 68 } else { 69 "." 70 }); 71 if crt_col == 39 { 72 screen = screen.add("\n"); 73 } 74 75 // End of cycle, apply instruction 76 if circ == 0 { 77 x = apply(op, arg, x); 78 } 79 // increase cycle counter 80 tick += 1; 81 } 82 //println!("Day 10: {}",sss); 83 println!("Day 10:"); 84 print!("{}", screen); 85 }