-
Notifications
You must be signed in to change notification settings - Fork 0
/
day3.pl
executable file
·53 lines (43 loc) · 939 Bytes
/
day3.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
#!/usr/bin/env perl
use strict;
use warnings;
# Part 1
sub part1 {
my ($data) = @_;
my $sum = 0;
while ($data =~ /mul\((\d+),(\d+)\)/g) {
$sum += $1 * $2;
}
return $sum;
}
# Part 2
sub part2 {
my ($data) = @_;
my $enabled = 1;
my $total_sum = 0;
while ($data =~ /(mul\((\d+),(\d+)\)|don't\(\)|do\(\))/g) {
my $match = $1;
if ($match eq 'do()') {
$enabled = 1;
} elsif ($match eq "don't()") {
$enabled = 0;
} elsif ($enabled && $match =~ /mul\((\d+),(\d+)\)/) {
$total_sum += $1 * $2;
}
}
return $total_sum;
}
my $filename = "input.txt";
if (@ARGV) {
$filename = $ARGV[0];
}
my $data = '';
{
local $/ = undef;
open my $fh, '<', $filename or die "Could not open file '$filename': $!\n";
$data = <$fh>;
close $fh;
}
chomp($data);
print part1($data) . "\n";
print part2($data) . "\n";