main.rs (2221B)
1 #[derive(Debug, Clone)]
2 enum Op {
3 Noop,
4 Addx(i32),
5 }
6
7 impl Op {
8 fn from_str(s: &str) -> Option<Self> {
9 let tmp = s.split(' ').collect::<Vec<_>>();
10 match tmp[0] {
11 "noop" => Some(Self::Noop),
12 "addx" => Some(Self::Addx(tmp[1].parse::<i32>().unwrap())),
13 _ => None,
14 }
15 }
16 }
17
18 fn main() {
19 let input = std::fs::read_to_string("input.txt")
20 .unwrap()
21 .trim()
22 .split("\n")
23 .map(|x| Op::from_str(x).unwrap())
24 .collect::<Vec<Op>>();
25 // 13820
26 println!("Part 1: {}", part_1(&input));
27 // ZKGRKGRK
28 println!("Part 2:");
29 part_2(&input)
30 }
31
32 fn part_1(input: &Vec<Op>) -> i32 {
33 let mut res = 0;
34 fn check_signal(res: &mut i32, t: usize, x: i32) {
35 if t == 20 || t == 60 || t == 100 || t == 140 || t == 180 || t == 220 {
36 *res += t as i32 * x;
37 }
38 }
39 let mut x = 1;
40 let mut t = 1;
41
42 for op in input.iter() {
43 check_signal(&mut res, t, x);
44 match op {
45 Op::Noop => {
46 t += 1;
47 }
48 Op::Addx(a) => {
49 t += 1;
50 check_signal(&mut res, t, x);
51 t += 1;
52 x += a;
53 }
54 }
55 }
56 res
57 }
58
59 fn part_2(input: &Vec<Op>) {
60 const CRT_WIDTH: usize = 40;
61 const CRT_HEIGHT: usize = 6;
62 const CRT_PIXELS: usize = CRT_WIDTH * CRT_HEIGHT;
63 let mut crt = [false; CRT_PIXELS];
64 fn draw(crt: &mut [bool; CRT_PIXELS], t: usize, x: i32) {
65 let idx = t - 1;
66 let pos = (idx % CRT_WIDTH) as i32;
67 if pos == x - 1 || pos == x || pos == x + 1 {
68 crt[idx] = true;
69 }
70 }
71 let mut x = 1;
72 let mut t = 1;
73 for op in input.iter() {
74 draw(&mut crt, t, x);
75 match op {
76 Op::Noop => {
77 t += 1;
78 }
79 Op::Addx(a) => {
80 t += 1;
81 draw(&mut crt, t, x);
82 t += 1;
83 x += a;
84 }
85 }
86 }
87 for (i, lit) in crt.iter().enumerate() {
88 print!("{}", if *lit { '#' } else { '.' });
89 if (i + 1) % CRT_WIDTH == 0 {
90 println!();
91 }
92 }
93 }