-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday08.pl
More file actions
75 lines (65 loc) · 1.7 KB
/
day08.pl
File metadata and controls
75 lines (65 loc) · 1.7 KB
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
use strict;
use Term::ANSIColor;
use Win32::Console::ANSI;
use Time::HiRes qw/time/;
my $time = time;
my $filename = "${0}_input";
open(my $fh, $filename);
my %registers;
my ($globalMax,$globalMaxvar);
while(my $input = <$fh>){
my @input = split " ",$input;
my $register = $input[0];
my $operator = $input[1];
my $value = $input[2];
my $conditionRegister = $input[4];
my $conditionOperator = $input[5];
my $conditionValue = $input[6];
if(evalCondition($conditionRegister,$conditionOperator,$conditionValue)){
execute($register,$operator,$value);
my ($currentMax, $currentMaxvar) = calculateMaxValue();
if($globalMax<$currentMax){
$globalMax=$currentMax;
$globalMaxvar=$currentMaxvar;
}
}
}
my ($max, $maxvar) = calculateMaxValue();
print "The maximum value at the end is ", colored( $max, "black on_red" ), " (stored in '$maxvar').\n";
print "The maximum value ever stored is ", colored( $globalMax, "black on_red" ), " (stored in '$globalMaxvar'). ( ", sprintf ("%.3f",time - $time) ," s )\n";
sub evalCondition {
my $register = shift;
my $operator = shift;
my $value = shift;
if(! $registers{$register}){
$registers{$register} = 0;
}
return eval($registers{$register}.$operator.$value);
}
sub execute {
my $register = shift;
my $operator = shift;
my $value = shift;
if(! $registers{$register}){
$registers{$register} = 0;
}
if($operator eq "inc") {
$registers{$register} += $value;
} elsif($operator eq "dec") {
$registers{$register} -= $value;
}
}
sub calculateMaxValue{
my ($max, $maxvar);
while (my ($key, $value) =each %registers) {
if(! $max){
$max = $value;
$maxvar = $key;
}
if($max<$value){
$max = $value;
$maxvar = $key;
}
}
return ($max,$maxvar);
}