-
Notifications
You must be signed in to change notification settings - Fork 0
/
day11.pl
executable file
·90 lines (73 loc) · 1.62 KB
/
day11.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
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/perl
#
# $Id: pl.template,v 1.2 2014/07/18 15:01:38 caran Exp $
#
# $ perl day11.pl $(cat input11.txt)
#
use strict;
use warnings;
#
# N and S are twice as far in y-direction as diagonals
#
my $moves = {
n => { x => 0, y => 2 },
ne => { x => 1, y => 1 },
e => { x => 1, y => 0 },
se => { x => 1, y => -1 },
s => { x => 0, y => -2 },
sw => { x => -1, y => -1 },
w => { x => -1, y => 0 },
nw => { x => -1, y => 1 },
};
{ package Grid;
#
# Move as needed in the X direction, then finish in Y
#
sub distance {
my ($self) = @_;
my $distance;
my ($x, $y) = (abs( $self->{ pos_x } ), abs( $self->{ pos_y } ));
if ($x > $y) {
$distance = $x;
}
else {
$distance = int($y - $x + .5)/2 + $x;
}
return $distance;
}
sub farthest {
my ($self) = @_;
return $self->{ max };
}
sub move {
my ($self, $dir) = @_;
my $move = $moves->{ $dir } or die "Illegal direction '$dir'\n";
$self->{ pos_x } += $move->{ x };
$self->{ pos_y } += $move->{ y };
my $dist = $self->distance();
if ($dist > $self->{ max }) {
$self->{ max } = $dist;
}
return $self;
}
sub new {
my $class = shift;
my $input = shift;
my $self = {
pos_x => 0,
pos_y => 0,
max => 0,
};
bless $self, $class;
return $self;
}
}
my $input = $ARGV[0] || die "Please enter the input\n";
my $grid = Grid->new();
my @moves = split /\s*,\s*/, $input;
for my $move (@moves) {
$grid->move( $move );
}
print "The distance is ", $grid->distance(), " away\n";
print "The farthest is ", $grid->farthest(), " away\n";
exit;