Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- use List::AllUtils qw(max pairwise);
- $; = ',';
- my %dirs = ( 'R' => [0,1], 'L' => [0,-1], 'U' => [-1,0], 'D' => [1,0] );
- sub vec_sum {
- my ($v, $w) = @_;
- return ([pairwise {$a + $b} @$v, @$w]);
- }
- sub distance {
- my ($h, $t) = @_;
- return (max pairwise {abs($a - $b)} @$h, @$t);
- }
- sub roach_move {
- my ($h, $t) = @_;
- return ([pairwise {$a <=> $b} @$h, @$t]);
- }
- my @rope = map { [0,0] } (0 .. 9);
- my @trails = ({'0,0' => 1}, {'0,0' => 1});
- while (<>) {
- my ($dir, $steps) = m#^(\w) (\d+)#;
- foreach (1 .. $steps) {
- $rope[0] = &vec_sum( $rope[0], $dirs{$dir} );
- foreach my $i (1 .. 9) {
- if (&distance( $rope[$i-1], $rope[$i] ) > 1) {
- $rope[$i] = &vec_sum( $rope[$i], &roach_move( $rope[$i-1], $rope[$i] ) );
- }
- }
- $trails[0]{$rope[1][0],$rope[1][1]}++;
- $trails[1]{$rope[9][0],$rope[9][1]}++;
- }
- }
- print "Part 1: ", scalar keys %{$trails[0]}, "\n";
- print "Part 2: ", scalar keys %{$trails[1]}, "\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement