Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- use feature qw(say);
- use List::AllUtils qw(sum product pairwise indexes);
- use Array::Heap::PriorityQueue::Numeric;
- my @input = map {[split /,/]} <>;
- my $part1stop = (@input == 1000) ? 999 : 9; # where part 1 stops (different for test)
- # Calculate list of squared Euclidean distances
- my $Dist = Array::Heap::PriorityQueue::Numeric->new();
- for (my $i = 0; $i < @input; $i++) {
- for (my $j = 0; $j < $i; $j++) {
- my $dist = sum pairwise {($a - $b) ** 2} @{$input[$i]}, @{$input[$j]};
- $Dist->add( [$i,$j], $dist );
- }
- }
- # Initialize each junction box to it's own circuit
- my @Circ = map {{$_ => 1}} (0 .. $#input);
- # Connect shortest edges into circuit graphs
- for (my $i = 0; ; $i++) {
- my $conx = $Dist->get();
- my @graphs = indexes {$_->{$conx->[0]} or $_->{$conx->[1]}} @Circ;
- # If ends are in separate graphs, merge them:
- if (@graphs == 2) {
- $Circ[$graphs[0]] = {map { $Circ[$_]->%* } @graphs};
- splice( @Circ, $graphs[1], 1 );
- }
- if ($i == $part1stop) {
- my @size = sort {$b<=>$a} map { scalar %$_ } @Circ;
- say "Part 1: ", product @size[0..2];
- }
- if (@Circ == 1) {
- say "Part 2: ", product map { $input[$_][0] } @$conx;
- last;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment