-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday11.pl
More file actions
76 lines (66 loc) · 1.83 KB
/
day11.pl
File metadata and controls
76 lines (66 loc) · 1.83 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
76
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);
while(my $input = <$fh>){
chomp $input;
my @input = split ",",$input;
my $north = 0;
my $northeast = 0;
my $northwest = 0;
my $maxDistance = 0;
foreach (@input) {
if($_ eq "n"){
$north++;
} elsif($_ eq "s"){
$north--;
} elsif($_ eq "ne"){
$northeast++;
} elsif($_ eq "sw"){
$northeast--;
} elsif($_ eq "nw"){
$northwest++;
} elsif($_ eq "se"){
$northwest--;
}
my $currentDistance = 0;
foreach my $x (calculateDistance($north,$northeast,$northwest)) {
$currentDistance+=abs($x);
}
if ($maxDistance < $currentDistance) {
$maxDistance = $currentDistance;
}
}
($north,$northeast,$northwest) = calculateDistance($north,$northeast,$northwest);
print "The required number of steps is ", colored( abs($north)+abs($northeast)+abs($northwest), "black on_red" ), ". ( ", sprintf ("%.3f",time - $time) ," s )\n";
print "The furthest away was ", colored( $maxDistance, "black on_red" ), ". ( ", sprintf ("%.3f",time - $time) ," s )\n";
}
sub calculateDistance {
my $north = shift;
my $northeast = shift;
my $northwest = shift;# NE + NW = N
while( ($northeast!=0) && ($northwest!=0) && (($northeast<0) == ($northwest<0)) ){
my $sign = $northeast/abs($northeast);
$northeast -= $sign;
$northwest -= $sign;
$north += $sign;
}
# N - NE = NW
while( ($north!=0) && ($northeast!=0) && (($north<0) != ($northeast<0)) ){
my $sign = $north/abs($north);
$north -= $sign;
$northeast -= -$sign;
$northwest += $sign;
}
# N-NW = NE
while( ($north!=0) && ($northwest!=0) && (($north<0) != ($northwest<0)) ){
my $sign = $north/abs($north);
$north -= $sign;
$northwest -= -$sign;
$northeast += $sign;
}
return ($north,$northeast,$northwest);
}