-
Notifications
You must be signed in to change notification settings - Fork 0
/
d02_2.pl
58 lines (51 loc) · 1.65 KB
/
d02_2.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
#!/usr/bin/perl
# Advent of Code 2016 Day 2 - part 2
# Problem link: http://adventofcode.com/2016/day/2
# Discussion: http://gerikson.com/blog/comp/Advent-of-Code-2016.html#d02
# License: http://gerikson.com/files/AoC2016/UNLICENSE
###########################################################
use 5.016; # implies strict, provides 'say'
use warnings;
use autodie;
#### INIT - load input data into array
my $testing = 0;
my @input;
my $file = $testing ? 'test.txt' : 'input.txt';
{
open( my $fh, '<', "$file" );
while (<$fh>) { chomp; s/\r//gm; push @input, $_; }
}
### CODE
# Layout - circle in taxicab geometry!
#
# 1
# 2 3 4
# 5 6 7 8 9
# A B C
# D
# Cartesian coordinates, center the origin at 7, x,y for the keys as below
my $keypad = { -2 => { 0 => 5 },
-1 => { -1 => 'A', 0 => 6, 1 => 2 },
0 => { -2 => 'D', -1 => 'B', 0 => 7, 1 => 3, 2 => 1 },
1 => { -1 => 'C', 0 => 8, 1 => 4 },
2 => { 0 => 9 } };
my $next_move = { U => [ 0, 1 ],
D => [ 0, -1 ],
L => [ -1, 0 ],
R => [ 1, 0 ] };
my $key = [ -2, 0 ];
my $solution;
foreach my $line (@input) {
my @instructions = split( //, $line );
foreach my $move (@instructions) {
my $next = [ $key->[0] + $next_move->{$move}->[0],
$key->[1] + $next_move->{$move}->[1] ];
if ( abs( $next->[0] ) + abs( $next->[1] ) > 2 ) {
next;
} else {
$key = $next;
}
}
$solution .= $keypad->{ $key->[0] }->{ $key->[1] };
}
say $solution;