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
|
use std::env;
use std::fs;
#[derive(Eq, PartialEq)]
enum Ins {
Noop,
Addr(i32)
}
fn main() {
let args = env::args().nth(1).expect("missing input");
let input = fs::read_to_string(args).unwrap();
let instructions: Vec<Ins> = input.trim().split("\n")
.map(|x| {
if x == "noop" {
return Ins::Noop;
} else {
let val = x.split_whitespace().nth(1).unwrap();
return Ins::Addr(val.parse::<i32>().unwrap());
}
}).collect();
let mut sum = 0;
let mut clock = 1;
let mut register = 1;
for ins in instructions {
render(&clock, ®ister);
tick(&mut clock);
compare(&clock, ®ister, &mut sum);
if let Ins::Addr(x) = ins {
render(&clock, ®ister);
tick(&mut clock);
write(&mut register, x);
compare(&clock, ®ister, &mut sum);
}
}
println!("{}", sum);
}
fn render(clock: &i32, register: &i32) {
if i32::abs(register - ((clock-1) % 40)) < 2 {
print!("#");
} else {
print!(".");
}
if clock % 40 == 0 {
print!("\n");
}
}
fn tick(clock: &mut i32) {
*clock += 1;
}
fn compare(clock: &i32, register: &i32, sum: &mut i32) {
if clock % 40 == 20 {
*sum += *register * *clock;
}
}
fn write(register: &mut i32, value: i32) {
*register += value;
}
|