-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
276 lines (245 loc) · 7.64 KB
/
main.rs
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
#![warn(clippy::all, clippy::pedantic, clippy::nursery)]
use std::{fmt::Display, str::FromStr};
pub fn main() {
let data = include_str!("input.txt");
println!("Part 1: {}", part_one(data));
}
fn part_one(data: &str) -> u32 {
let limit = get_magic_number(data);
// The series 2^n plus the value from two steps previous will always produce alternating odd
// then even numbers from successive integer division by two.
// By anaylsing the assembly, we can see that this is what we need to get the value of b to
// output alternating 0 and 1
// The magic number extracted above, is variable by input and is added to the required answer,
// so we need to loop up the series until we get to the first value above the limit.
// We can then subtract the two to work out the smallest number we need add to get onto
// this desired series
let out = (0..)
.take(100)
.scan((0, 0), |(a, b), i| {
let c = 2_u32.pow(i) + *a;
*a = *b;
*b = c;
Some(*b)
})
.find(|v| v > &limit)
.unwrap()
- limit;
// Run the programme just to check it works :)
let mut p = Programme::new(data, i32::try_from(out).unwrap());
p.run();
println!();
out
}
fn get_magic_number(data: &str) -> u32 {
let mut all_lines = data.lines();
let mut line1 = all_lines.nth(1).unwrap().split_whitespace();
let mut line2 = all_lines.next().unwrap().split_whitespace();
let (Some("cpy"), Some(x), Some("c"), None) = (line1.next(), line1.next(), line1.next(), line1.next()) else { unreachable!() };
let (Some("cpy"), Some(y), Some("b"), None) = (line2.next(), line2.next(), line2.next(), line2.next()) else { unreachable!() };
let x: u32 = x.parse().unwrap();
let y: u32 = y.parse().unwrap();
x * y
}
#[derive(Debug)]
struct Programme {
instructions: [Instruction; 30],
step: usize,
registers: [i32; 4],
}
impl Display for Programme {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Step: {}, a: {}, b: {}, c: {}, d: {}",
self.step, self.registers[0], self.registers[1], self.registers[2], self.registers[3]
)?;
Ok(())
}
}
impl Programme {
fn new(data: &str, init: i32) -> Self {
let mut instructions = [Instruction::Inc(Operand::Reg(Register::A)); 30];
for (line, instruction) in data.lines().zip(instructions.iter_mut()) {
*instruction = line.parse().unwrap();
}
Self {
instructions,
step: 0,
registers: [init, 0, 0, 0],
}
}
fn run(&mut self) {
let mut counter = 0;
while self.step < 30 && counter < 100_000 {
self.run_step();
counter += 1;
}
}
fn run_step(&mut self) {
match self.instructions.get(self.step).unwrap() {
Instruction::Inc(op) => self.inc(*op),
Instruction::Dec(op) => self.dec(*op),
Instruction::Cpy((op1, op2)) => self.cpy(*op1, *op2),
Instruction::Jnz((op1, op2)) => self.jnz(*op1, *op2),
Instruction::Out(op) => self.out(*op),
}
self.step += 1;
}
fn inc(&mut self, op: Operand) {
match op {
Operand::Reg(r) => *self.get_mut(r) += 1,
Operand::Val(_) => (), // Ignore, can't increment a static number
}
}
fn dec(&mut self, op: Operand) {
match op {
Operand::Reg(r) => *self.get_mut(r) -= 1,
Operand::Val(_) => (), // Ignore, can't decrement a static number
}
}
fn cpy(&mut self, op1: Operand, op2: Operand) {
match (op1, op2) {
(Operand::Reg(from), Operand::Reg(to)) => {
*self.get_mut(to) = self.get(from);
}
(Operand::Val(x), Operand::Reg(to)) => {
*self.get_mut(to) = x;
}
(_, Operand::Val(_)) => (), // can't copy to a static value, do nothing
}
}
fn jnz(&mut self, op1: Operand, op2: Operand) {
match (op1, op2) {
(Operand::Reg(test), Operand::Reg(jump)) => {
if self.get(test) != 0 {
self.jump(self.get(jump));
}
}
(Operand::Reg(test), Operand::Val(jump)) => {
if self.get(test) != 0 {
self.jump(jump);
}
}
(Operand::Val(test), Operand::Reg(jump)) => {
if test != 0 {
self.jump(self.get(jump));
}
}
(Operand::Val(test), Operand::Val(jump)) => {
if test != 0 {
self.jump(jump);
}
}
};
}
fn jump(&mut self, jump: i32) {
if jump < 0 {
self.step -= usize::try_from(jump.abs()).unwrap();
} else {
self.step += usize::try_from(jump).unwrap();
}
self.step -= 1;
}
fn out(&self, op: Operand) {
match op {
Operand::Reg(r) => print!("{}_", self.registers[r.to_index()]),
Operand::Val(_) => (), // No Op
}
}
fn get(&self, r: Register) -> i32 {
*self.registers.get(r.to_index()).unwrap()
}
fn get_mut(&mut self, r: Register) -> &mut i32 {
self.registers.get_mut(r.to_index()).unwrap()
}
}
#[derive(Debug, Clone, Copy)]
enum Instruction {
Inc(Operand),
Dec(Operand),
Jnz((Operand, Operand)),
Cpy((Operand, Operand)),
Out(Operand),
}
impl FromStr for Instruction {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (op, rest) = s.split_once(' ').ok_or("No space in instruction")?;
match op {
"inc" => {
let op = rest.parse()?;
Ok(Self::Inc(op))
}
"dec" => {
let op = rest.parse()?;
Ok(Self::Dec(op))
}
"jnz" => {
let (op1, op2) = rest.split_once(' ').ok_or("jnz needs two operands")?;
let op1 = op1.parse()?;
let op2 = op2.parse()?;
Ok(Self::Jnz((op1, op2)))
}
"cpy" => {
let (op1, op2) = rest.split_once(' ').ok_or("cpy needs two operands")?;
let op1 = op1.parse()?;
let op2 = op2.parse()?;
Ok(Self::Cpy((op1, op2)))
}
"out" => {
let op = rest.parse()?;
Ok(Self::Out(op))
}
_ => unreachable!(),
}
}
}
#[derive(Debug, Clone, Copy)]
enum Operand {
Reg(Register),
Val(i32),
}
impl FromStr for Operand {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"a" => Ok(Self::Reg(Register::A)),
"b" => Ok(Self::Reg(Register::B)),
"c" => Ok(Self::Reg(Register::C)),
"d" => Ok(Self::Reg(Register::D)),
_ => {
let num: i32 = s
.parse()
.map_err(|_| "Operand not a number, and not a register 'a' to 'd'")?;
Ok(Self::Val(num))
}
}
}
}
#[derive(Debug, Clone, Copy)]
enum Register {
A,
B,
C,
D,
}
impl Register {
const fn to_index(self) -> usize {
match self {
Self::A => 0,
Self::B => 1,
Self::C => 2,
Self::D => 3,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one() {
let data = include_str!("test.txt");
assert_eq!(0, part_one(data));
}
}