4 use std::io::BufReader;
5 use std::io::prelude::*;
19 fn parse(line: &str) -> Instruction {
20 let cpy_lit: Regex = Regex::new(r"cpy ([-\d]+) (a|b|c|d)").unwrap();
21 let cpy_reg = Regex::new(r"cpy (a|b|c|d) (a|b|c|d)").unwrap();
22 let inc = Regex::new(r"inc (a|b|c|d)").unwrap();
23 let dec = Regex::new(r"dec (a|b|c|d)").unwrap();
24 let jnz_lit = Regex::new(r"jnz ([-\d]+) ([-\d]+)").unwrap();
25 let jnz_reg = Regex::new(r"jnz (a|b|c|d) ([-\d]+)").unwrap();
27 if cpy_lit.is_match(line) {
28 let cap = cpy_lit.captures(line).unwrap();
29 let src: i32 = cap.at(1).unwrap().parse().unwrap();
30 let dest = to_register_index(cap.at(2).unwrap());
31 Instruction::CpyLit(src, dest)
33 else if cpy_reg.is_match(line) {
34 let cap = cpy_reg.captures(line).unwrap();
35 let src = to_register_index(cap.at(1).unwrap());
36 let dest = to_register_index(cap.at(2).unwrap());
37 Instruction::CpyReg(src, dest)
39 else if inc.is_match(line) {
40 let cap = inc.captures(line).unwrap();
41 let dest = to_register_index(cap.at(1).unwrap());
42 Instruction::Inc(dest)
44 else if dec.is_match(line) {
45 let cap = dec.captures(line).unwrap();
46 let dest = to_register_index(cap.at(1).unwrap());
47 Instruction::Dec(dest)
49 else if jnz_lit.is_match(line) {
50 let cap = jnz_lit.captures(line).unwrap();
51 let condition: i32 = cap.at(1).unwrap().parse().unwrap();
52 let offset: i32 = cap.at(2).unwrap().parse().unwrap();
54 Instruction::Jmp(offset)
60 else if jnz_reg.is_match(line) {
61 let cap = jnz_reg.captures(line).unwrap();
62 let condition = to_register_index(cap.at(1).unwrap());
63 let offset: i32 = cap.at(2).unwrap().parse().unwrap();
64 Instruction::Jnz(condition, offset)
67 panic!("Invalid instruction line")
73 let program = read_file();
75 let mut registers: [i32; 4] = [0, 0, 1, 0];
76 let mut pc: usize = 0;
78 while pc < program.len() {
79 let mut pc_next: usize = pc+1;
82 Instruction::CpyLit(src, dest) => {
83 registers[dest] = src;
85 Instruction::CpyReg(src, dest) => {
86 registers[dest] = registers[src];
88 Instruction::Inc(dest) => {
91 Instruction::Dec(dest) => {
94 Instruction::Jnz(condition, offset) => {
95 if registers[condition] != 0 {
96 pc_next = (pc as i32 + offset) as usize;
99 Instruction::Jmp(offset) => {
100 pc_next = (pc as i32 + offset) as usize
102 Instruction::Noop => {}
108 println!("a: {}, b: {}, c: {}, d: {}", registers[0], registers[1], registers[2], registers[3]);
112 fn to_register_index(name: &str) -> usize {
118 _ => panic!("Invalid register provided")
122 fn read_file() -> Vec<Instruction> {
123 let file = BufReader::new(File::open("input.txt").unwrap());
125 .map(|line| line.unwrap())
126 .filter(|line| line.len() > 0)
127 .map(|line| Instruction::parse(line.trim()))