Advertisement
musifter

AoC 2022, day 7 (Perl, non-recursive)

Dec 7th, 2022 (edited)
1,369
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.26 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use v5.12;
  4. use warnings;
  5.  
  6. use List::Util  qw(sum min);
  7.  
  8. use constant DISK_SIZE => 70_000_000;
  9. use constant NEED      => 30_000_000;
  10.  
  11. $/ = '$ ';          # break input on cmd prompts
  12.  
  13. # read input, throwing out the cmd prompts
  14. my @input = map { [grep { $_ ne '$ ' } split /\n/] } <>;
  15. shift( @input );    # empty, because $ is a prompt not a divider
  16.  
  17. my %dirs;   # directory path name => size
  18. my @path;   # path of directories to cwd
  19.  
  20. foreach (@input) {
  21.     my ($cmd, @res) = @$_;
  22.  
  23.     if ($cmd =~ m#cd (.*)#) {
  24.         if ($1 eq '/') {
  25.             @path = ('/');
  26.         } elsif ($1 eq '..') {
  27.             pop( @path );
  28.         } else {
  29.             push( @path, $1 );
  30.         }
  31.  
  32.     } else {
  33.         # cmd is ls, parse result
  34.         foreach (@res) {
  35.             my ($type, $name) = m#(.*) (.*)#;   # Bright eyes, Elven device!
  36.  
  37.             if ($type ne 'dir') {
  38.                 my $path;
  39.                 foreach my $lvl (@path) {
  40.                     $path .= "$lvl/";
  41.                     $dirs{ $path } += $type;
  42.                 }
  43.             }
  44.         }
  45.     }
  46. }
  47.  
  48. say "Part 1: ", sum grep { $_ <= 100_000 } values %dirs;
  49.  
  50. my $needed = NEED - (DISK_SIZE - $dirs{'//'});
  51. say "Part 2: ", min grep { $_ >= $needed } values %dirs;
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement