Advertisement
musifter

AoC 2024, day 9, part 1 (Perl)

Dec 9th, 2024 (edited)
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.66 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::Util      qw(sum);
  8.  
  9. my @input = map { chomp; split // } <>;
  10.  
  11. my @disk;
  12. my $id = 0;
  13. while (@input) {
  14.     my $size = shift @input;
  15.     my $gap  = shift @input;
  16.  
  17.     push( @disk, ($id++) x $size );
  18.     push( @disk, ('.')   x $gap  )   if ($gap);
  19. }
  20.  
  21. my $left  = 0;
  22. my $right = $#disk;
  23.  
  24. while (1) {
  25.     $left++   while ($disk[$left]  ne '.');
  26.     $right--  while ($disk[$right] eq '.');
  27.  
  28.     last if ($left >= $right);
  29.  
  30.     $disk[$left]  = $disk[$right];
  31.     $disk[$right] = '.';
  32. }
  33.  
  34. say "Part 1: ", sum map { ($disk[$_] ne '.') ? $_ * $disk[$_] : 0 } (0 .. $left);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement