Advertisement
musifter

AoC 2024, day 8 (Perl)

Dec 8th, 2024 (edited)
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.97 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use feature                     qw(say);
  7.  
  8. use Math::Vector::Real;
  9. use Algorithm::Combinatorics    qw(combinations);
  10.  
  11. my %Grid;
  12. my %Antennae;
  13.  
  14. # Read in grid, make lists of antennae of same frequency
  15. while (<>) {
  16.     chomp;
  17.     my $x = 0;
  18.     foreach my $chr (split //) {
  19.         $Grid{ V($.,++$x) } = $chr;
  20.         push( $Antennae{$chr}->@*, V($.,$x) )  if ($chr ne '.');
  21.     }
  22. }
  23.  
  24. # Takes a list of harmonics from an antenna to count
  25. sub countAntinodes {
  26.     my %Antinodes;
  27.  
  28.     foreach my $list (values %Antennae) {
  29.         foreach my $pair (combinations( $list, 2 )) {
  30.             my $delta = $pair->[0] - $pair->[1];
  31.  
  32.             foreach my $node (map { $pair->[0] + $_ * $delta } @_) {
  33.                 $Antinodes{$node}++ if (exists $Grid{$node});
  34.             }
  35.         }
  36.     }
  37.  
  38.     return (scalar keys %Antinodes);
  39. }
  40.  
  41. say "Part 1: ", &countAntinodes(1, -2);
  42. say "Part 2: ", &countAntinodes(-$. .. $.);
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement