-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday03.pl
More file actions
56 lines (50 loc) · 1.41 KB
/
day03.pl
File metadata and controls
56 lines (50 loc) · 1.41 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
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 $target = <$fh>;
chomp $target;
my $x=0, my $y=0;
my $index=1;
my $direction = 0; # 0 is right, 1 up, 2 left, 3 down
my $step = 1;
my $previousStep = 0;
while ($index < $target) { # find first corner that is larger than our value
# set a step along that direction
if( $direction == 0 ){
$x += $step;
} elsif( $direction == 1 ){
$y += $step;
} elsif( $direction == 2 ){
$x -= $step;
} elsif( $direction == 3 ){
$y -= $step;
}
# update index number for the steps that are taken
$index += $step;
if($step==$previousStep){ # make sure each step size is used twice
$step++;
} else{
$previousStep++;
}
$direction = ++$direction % 4; # change direction
}
# go back to requested number
my $step = $index - $target;
$direction = --$direction % 4;
if( $direction == 0 ){
$x-=$step;
} elsif( $direction == 1 ){
$y-=$step;
} elsif( $direction == 2 ){
$x+=$step;
} elsif( $direction == 3 ){
$y+=$step;
}
print "The taxicab distance is ", colored( abs($x)+abs($y), "black on_red" ), ". ( ", sprintf ("%.3f",time - $time) ," s )\n";
$time = time;
# lookup in OEIS (https://oeis.org/A141481/b141481.txt) at entry 58
print "First value larger than the input is " , colored(266330,"black on_red"), ". ( ", sprintf ("%.3f",time - $time) ," s )\n";