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
|
use std::fs;
use std::io::{self, BufRead};
fn probe(cycle: &i32, register: &i32) -> Option<i32> {
let probes = vec![20, 60, 100, 140, 180, 220];
if probes.contains(cycle) {
Some(cycle * register)
} else {
None
}
}
fn draw_pixel(cycle: &i32, register: &i32) {
let pixel = (cycle - 1) % 40;
if pixel == 0 {
println!("");
}
let mark = if (register - 1) <= pixel && pixel <= (register + 1) {
"#"
} else {
"."
};
print!("{}", mark);
}
fn main() {
let file = fs::File::open("input").unwrap();
let lines = io::BufReader::new(file).lines();
let mut register = 1;
let mut cycle = 1;
let mut measures = Vec::<i32>::new();
for line in lines {
draw_pixel(&cycle, ®ister);
cycle += 1;
let step1 = probe(&cycle, ®ister);
let inst = line.expect("valid instruction");
let inst = inst.split(" ").collect::<Vec<&str>>();
let step2 = if inst[0] == "addx" {
draw_pixel(&cycle, ®ister);
cycle += 1;
register += inst[1].parse::<i32>().unwrap();
probe(&cycle, ®ister)
} else {
None
};
match [step1, step2] {
[Some(x), _] => measures.push(x),
[None, Some(y)] => measures.push(y),
_ => (),
}
}
println!("\n{:?} {}", measures, measures.iter().sum::<i32>());
}
|