summary refs log tree commit diff homepage
path: root/2016/src/bin/day23.rs
blob: 4a54983490afd39105ac7159b9c1a1b11a633890 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
use std::io::{self, Read};

#[derive(Clone, Copy)]
enum Operand {
    Register(u8),
    Immediate(i32),
}

impl<'a> From<&'a str> for Operand {
    fn from(s: &'a str) -> Self {
        match s {
            "a" => Operand::Register(0),
            "b" => Operand::Register(1),
            "c" => Operand::Register(2),
            "d" => Operand::Register(3),
            _ => Operand::Immediate(s.parse().unwrap()),
        }
    }
}

#[derive(Clone, Copy)]
enum Operation {
    Cpy(Operand, Operand),
    Inc(Operand),
    Dec(Operand),
    Jnz(Operand, Operand),
    Tgl(Operand),
}

impl<'a> From<&'a str> for Operation {
    fn from(s: &'a str) -> Self {
        let mut iter = s.split_whitespace();
        match (iter.next().unwrap(), iter.next().unwrap()) {
            ("cpy", a) => Operation::Cpy(Operand::from(a), Operand::from(iter.next().unwrap())),
            ("inc", a) => Operation::Inc(Operand::from(a)),
            ("dec", a) => Operation::Dec(Operand::from(a)),
            ("jnz", a) => Operation::Jnz(Operand::from(a), Operand::from(iter.next().unwrap())),
            ("tgl", a) => Operation::Tgl(Operand::from(a)),
            _ => panic!("invalid instruction {}", s),
        }
    }
}

impl Operation {
    fn toggle(self) -> Self {
        match self {
            Operation::Inc(a) => Operation::Dec(a),
            Operation::Dec(a) | Operation::Tgl(a) => Operation::Inc(a),
            Operation::Jnz(a, b) => Operation::Cpy(a, b),
            Operation::Cpy(a, b) => Operation::Jnz(a, b),
        }
    }
}

#[derive(Default)]
struct Vm {
    registers: [i32; 4],
    operations: Vec<Operation>,
    index: i32,
}

impl<'a> From<&'a str> for Vm {
    fn from(s: &'a str) -> Self {
        let mut vm = Self::default();
        for line in s.lines() {
            vm.operations.push(Operation::from(line));
        }
        vm
    }
}

impl Vm {
    fn step(&mut self) -> bool {
        match self.operations[self.index as usize] {
            Operation::Cpy(Operand::Immediate(imm), Operand::Register(reg)) => {
                self.registers[reg as usize] = imm;
                self.index += 1;
            },
            Operation::Cpy(Operand::Register(src), Operand::Register(dest)) => {
                self.registers[dest as usize] = self.registers[src as usize];
                self.index += 1;
            },
            Operation::Inc(Operand::Register(reg)) => {
                self.registers[reg as usize] += 1;
                self.index += 1;
            },
            Operation::Dec(Operand::Register(reg)) => {
                self.registers[reg as usize] -= 1;
                self.index += 1;
            },
            Operation::Jnz(Operand::Immediate(cond), Operand::Immediate(jump)) => {
                if cond != 0 {
                    self.index += jump;
                } else {
                    self.index += 1;
                }
            },
            Operation::Jnz(Operand::Register(reg), Operand::Immediate(jump)) => {
                if self.registers[reg as usize] != 0 {
                    self.index += jump;
                } else {
                    self.index += 1;
                }
            },
            Operation::Jnz(Operand::Immediate(cond), Operand::Register(reg)) => {
                if cond != 0 {
                    self.index += self.registers[reg as usize];
                } else {
                    self.index += 1;
                }
            },
            Operation::Tgl(Operand::Register(reg)) => {
                let index = self.index + self.registers[reg as usize];
                if let Some(operation) = self.operations.get_mut(index as usize) {
                    *operation = operation.toggle();
                }
                self.index += 1;
            },
            _ => {
                self.index += 1;
            },
        }

        (self.index as usize) < self.operations.len()
    }
}

fn solve(initial: i32, input: &str) -> i32 {
    let mut vm = Vm::from(input);
    vm.registers[0] = initial;
    while vm.step() { }
    vm.registers[0]
}

fn main() {
    let mut input = String::new();
    io::stdin().read_to_string(&mut input).unwrap();

    println!("Part 1: {}", solve(7, &input));
    println!("Part 2: {}", solve(12, &input));
}

#[test]
fn part1() {
    let input = "
cpy 2 a
tgl a
tgl a
tgl a
cpy 1 a
dec a
dec a
";
    let mut vm = Vm::from(input.trim());
    while vm.step() { }
    assert_eq!(3, vm.registers[0]);
}
d/> 2020-02-11Add startup GPLv3 note and URLJune McEnroe I am a degenerate. 2020-02-11Make sure -D_GNU_SOURCE ends up in CFLAGS on LinuxJune McEnroe 2020-02-11Add note about setting PKG_CONFIG_PATHJune McEnroe 2020-02-11Rename query ID on nick changeJune McEnroe 2020-02-11Call completeClear when closing a windowJune McEnroe 2020-02-11Don't insert color codes for non-mentionsJune McEnroe 2020-02-11Take first two words in colorMentionsJune McEnroe This lets phrases like "hi june" get colored, but still doesn't get carried away. 2020-02-11Use time_t for save signatureJune McEnroe It's actually more likely to be 64-bit than size_t anyway, and it eliminates some helper functions. Also don't error when reading an empty save file. 2020-02-11Set self.nick to * initiallyJune McEnroe Allows removing a bunch of checks that self.nick is set, and it's what the server usually calls you before registration. Never highlight notices as mentions. 2020-02-11Define ColorCap instead of hardcoding 100June McEnroe 2020-02-11Move hash to top of chat.hJune McEnroe 2020-02-11Move base64 out of chat.hJune McEnroe 2020-02-11Move XDG_SUBDIR out of chat.hJune McEnroe 2020-02-11Fix whois idle unit calculationJune McEnroe Rookie mistake. 2020-02-11Cast towupper to wchar_tJune McEnroe For some reason it takes and returns wint_t... 2020-02-11Cast set but unused variables to voidJune McEnroe 2020-02-11Declare strlcatJune McEnroe 2020-02-11Check if VDSUSP existsJune McEnroe 2020-02-11Fix completeReplace iterationJune McEnroe 2020-02-11Use pkg(8) to configure on FreeBSDJune McEnroe 2020-02-11Remove legacy codeJune McEnroe 2020-02-11Add INSTALLING section to READMEJune McEnroe