Advertisement
Guest User

Untitled

a guest
Dec 3rd, 2019
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.57 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. my %DIRS = (
  7.     'R' => [  1,  0 ],
  8.     'L' => [ -1,  0 ],
  9.     'U' => [  0,  1 ],
  10.     'D' => [  0, -1 ],
  11. );
  12.  
  13.  
  14. my %Grid;
  15. my @wires = map { chomp; [split /,/] } <>;
  16.  
  17. my $bit = 0x01;
  18. foreach my $wire (@wires) {
  19.     my ($x,$y) = (0, 0);
  20.     my $len = 0;
  21.  
  22.     foreach my $line (@$wire) {
  23.         my ($dir, $dist) = ($line =~ m#^([RLUD])(\d+)$#);
  24.  
  25.         if (exists $DIRS{$dir}) {
  26.             foreach my $i (1 .. $dist) {
  27.                 $x += $DIRS{$dir}[0];
  28.                 $y += $DIRS{$dir}[1];
  29.                 $len++;
  30.  
  31.                 $Grid{"$x,$y"}[0] |= $bit;
  32.                 $Grid{"$x,$y"}[$bit] //= $len;
  33.             }
  34.         } else {
  35.             die "Unknown direction '$dir', command was '$line'\n";
  36.         }
  37.  
  38.         print "wire $bit: pos ($x, $y), length: $len      \r";
  39.     }
  40.  
  41.     $bit <<= 1;
  42.     print "\n";
  43. }
  44.  
  45. my $ALL_BITS = $bit - 1;
  46. my $min_dist = 1000000;
  47. my $min_len  = 1000000;
  48.  
  49. print "\nCrosses:\n";
  50. foreach my $cross (grep { $Grid{$_}[0] == $ALL_BITS } keys %Grid) {
  51.     my ($x,$y) = ($cross =~ m#([-0-9]+),([-0-9]+)#);
  52.     my $dist = abs($x) + abs($y);
  53.  
  54.     my $len = 0;
  55.     for (my $i = 1; $i < $ALL_BITS; $i <<= 1) {
  56.         $len += $Grid{$cross}[$i];
  57.     }
  58.  
  59.     $min_dist = ($dist < $min_dist) ? $dist : $min_dist;
  60.     $min_len  = ($len  < $min_len)  ? $len  : $min_len;
  61.  
  62.     printf( "\tpos (%4d, %4d)  dist: %4d length: %5d\n", $x, $y, $dist, $len );
  63. }
  64.  
  65. print "\nMinimum distance from origin to a cross: $min_dist\n";
  66. print "Minimum sum of lengths to a cross: $min_len\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement