musifter

AoC 2025 day 8, quicker (Perl)

Dec 8th, 2025 (edited)
308
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.30 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use feature         qw(say);
  7. use List::AllUtils  qw(sum product pairwise indexes);
  8. use Array::Heap::PriorityQueue::Numeric;
  9.  
  10. my @input = map {[split /,/]} <>;
  11.  
  12. my $part1stop = (@input == 1000) ? 999 : 9;  # where part 1 stops (different for test)
  13.  
  14. # Calculate list of squared Euclidean distances
  15. my $Dist = Array::Heap::PriorityQueue::Numeric->new();
  16. for (my $i = 0; $i < @input; $i++) {
  17.     for (my $j = 0; $j < $i; $j++) {
  18.         my $dist = sum pairwise {($a - $b) ** 2} @{$input[$i]}, @{$input[$j]};
  19.         $Dist->add( [$i,$j], $dist );
  20.     }
  21. }
  22.  
  23. # Initialize each junction box to it's own circuit
  24. my @Circ = map {{$_ => 1}} (0 .. $#input);
  25.  
  26. # Connect shortest edges into circuit graphs
  27. for (my $i = 0; ; $i++) {
  28.     my $conx = $Dist->get();
  29.     my @graphs = indexes {$_->{$conx->[0]} or $_->{$conx->[1]}} @Circ;
  30.  
  31.     # If ends are in separate graphs, merge them:
  32.     if (@graphs == 2) {
  33.         $Circ[$graphs[0]] = {map { $Circ[$_]->%* } @graphs};
  34.         splice( @Circ, $graphs[1], 1 );
  35.     }
  36.  
  37.     if ($i == $part1stop) {
  38.         my @size = sort {$b<=>$a} map { scalar %$_ } @Circ;
  39.         say "Part 1: ", product @size[0..2];
  40.     }
  41.  
  42.      if (@Circ == 1) {
  43.         say "Part 2: ", product map { $input[$_][0] } @$conx;
  44.         last;
  45.      }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment