Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- my %DIRS = (
- 'R' => [ 1, 0 ],
- 'L' => [ -1, 0 ],
- 'U' => [ 0, 1 ],
- 'D' => [ 0, -1 ],
- );
- my %Grid;
- my @wires = map { chomp; [split /,/] } <>;
- my $bit = 0x01;
- foreach my $wire (@wires) {
- my ($x,$y) = (0, 0);
- my $len = 0;
- foreach my $line (@$wire) {
- my ($dir, $dist) = ($line =~ m#^([RLUD])(\d+)$#);
- if (exists $DIRS{$dir}) {
- foreach my $i (1 .. $dist) {
- $x += $DIRS{$dir}[0];
- $y += $DIRS{$dir}[1];
- $len++;
- $Grid{"$x,$y"}[0] |= $bit;
- $Grid{"$x,$y"}[$bit] //= $len;
- }
- } else {
- die "Unknown direction '$dir', command was '$line'\n";
- }
- print "wire $bit: pos ($x, $y), length: $len \r";
- }
- $bit <<= 1;
- print "\n";
- }
- my $ALL_BITS = $bit - 1;
- my $min_dist = 1000000;
- my $min_len = 1000000;
- print "\nCrosses:\n";
- foreach my $cross (grep { $Grid{$_}[0] == $ALL_BITS } keys %Grid) {
- my ($x,$y) = ($cross =~ m#([-0-9]+),([-0-9]+)#);
- my $dist = abs($x) + abs($y);
- my $len = 0;
- for (my $i = 1; $i < $ALL_BITS; $i <<= 1) {
- $len += $Grid{$cross}[$i];
- }
- $min_dist = ($dist < $min_dist) ? $dist : $min_dist;
- $min_len = ($len < $min_len) ? $len : $min_len;
- printf( "\tpos (%4d, %4d) dist: %4d length: %5d\n", $x, $y, $dist, $len );
- }
- print "\nMinimum distance from origin to a cross: $min_dist\n";
- print "Minimum sum of lengths to a cross: $min_len\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement