-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday10.pl
80 lines (61 loc) · 1.52 KB
/
day10.pl
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
use strict;
use warnings;
use feature 'say';
use lib './';
use assertions;
open(my $file, "<", "input/day10.txt") or die "Can't open input file";
my @lines = ();
while (my $line = <$file>) {
chomp($line);
push(@lines, $line);
}
close $file;
my $cycle = 1;
my $register = 1;
my $signalSum = 0;
my @crt = ();
sub checkSignalStrength {
if ($cycle == 20 || ($cycle - 20) % 40 == 0) {
# say $cycle . " * " . $register . " = " . $cycle * $register;
$signalSum += $cycle * $register;
}
}
sub drawOnCrt {
my $drawPtr = ($cycle - 1) % 40;
push(@crt, abs($register - $drawPtr) <= 1 ? '#' : '.');
# printf "Start cycle %3d: begin executing %s\n", $cycle, $lines[$drawPtr];
# printf "During cycle %2d: CRT draws pixel in position %d\n", $cycle, $drawPtr;
# printf "Current CRT row: ";
# say @crt;
# printf "Sprite position: %d", $register;
# printf "\n\n";
}
foreach my $line (@lines) {
my $instr = substr($line, 0, 4);
if ($instr eq "noop") {
checkSignalStrength;
drawOnCrt;
$cycle++;
} elsif ($instr eq "addx") {
$line =~ /\w{4} (-?\d+)/;
my $instrValue = $1;
for (my $i = 0; $i < 2; $i++) {
checkSignalStrength;
drawOnCrt;
$cycle++;
}
$register += $instrValue;
} else {
die "Invalid instruction";
}
}
# Part 1
say $signalSum;
# Part 2
for (my $i = 0; $i <= $#crt; $i++) {
if ($i % 40 == 0) {
print "\n";
}
print $crt[$i];
}
print "\n";