Advertisement
musifter

AoC 2023, day 5, part 1 (Perl)

Dec 5th, 2023
919
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.11 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use v5.32;
  4. use warnings;
  5.  
  6. use List::Util      qw(min);
  7.  
  8. # Paragraph mode, array of sections
  9. $/ = '';
  10. my @section = map {[split /\n/]} <>;
  11.  
  12. # Read in seeds from first line of first section
  13. my @seeds = ($section[0][0] =~ m#(\d+)#g);
  14.  
  15. # Read in sections, building maps
  16. my %Map;        # hash of table -> array of struct (src, dst, len) hash
  17.  
  18. shift @section;
  19. foreach my $sect (@section) {
  20.     shift(@$sect) =~ m#-(\w+) map#;
  21.     my $type = $1;
  22.  
  23.     foreach my $line (@$sect) {
  24.         my ($dst, $src, $len) = split( ' ', $line );
  25.         push( $Map{$type}->@*, {src => $src, dst => $dst, len => $len} );
  26.     }
  27. }
  28.  
  29. my @order = qw(soil fertilizer water light temperature humidity location);
  30.  
  31. sub transform_seed {
  32.     my $val = shift;
  33.  
  34.     foreach my $step (@order) {
  35.         foreach my $range ($Map{$step}->@*) {
  36.             if ($range->{src} <= $val <= $range->{src} + $range->{len}) {
  37.                 $val = $range->{dst} + ($val - $range->{src});
  38.                 last;
  39.             }
  40.         }
  41.     }
  42.     return ($val);
  43. }
  44.  
  45. say "Part 1: ", min map { &transform_seed($_) } @seeds;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement