Advertisement
musifter

AoC 2022, day 11 (perl)

Dec 11th, 2022 (edited)
1,215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.54 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use Math::Utils  qw(lcm floor);
  7. use Clone        qw(clone);
  8.  
  9. $| = 1;
  10. $/ = '';
  11.  
  12. my @monkeys;
  13. my $modulus = 1;
  14.  
  15. foreach (<>) {
  16.     my @desc = split /\n/;
  17.     my ($n)  = (shift @desc) =~ m#(\d+)#;
  18.  
  19.     # Simple parse of label -> numbers
  20.     my %p = map { (m#(\w+):#) => [m#(\d+)#g] } @desc;
  21.  
  22.     $monkeys[$n]{start} = $p{items};    # starting items
  23.  
  24.     # parse inspection rule
  25.     $desc[1] =~ s#new = (.*)#$1#;
  26.     $desc[1] =~ s#old#\$_[0]#g;
  27.     $monkeys[$n]{op} = eval "sub { $desc[1] }";
  28.  
  29.     # make test rule sub
  30.     $monkeys[$n]{pass} = eval "sub {(\$_[0] % $p{Test}[0] == 0) ? $p{true}[0] : $p{false}[0]}";
  31.     $modulus = lcm( $modulus, $p{Test} );
  32. }
  33.  
  34.  
  35. sub run_monkeys {
  36.     my ($rounds, $reduce) = @_;
  37.  
  38.     # Initialize
  39.     foreach (@monkeys) {
  40.         $_->{inspect} = 0;
  41.         $_->{items} = clone( $_->{start} );
  42.     }
  43.  
  44.     # Run rounds
  45.     foreach (1 .. $rounds) {
  46.         foreach my $monk (@monkeys) {
  47.             $monk->{inspect} += @{$monk->{items}};
  48.             while (my $item = shift @{$monk->{items}}) {
  49.                 $item = &$reduce( $monk->{op}( $item ) );
  50.                 push( @{$monkeys[$monk->{pass}($item)]{items}}, $item );
  51.             }
  52.         }
  53.     }
  54.  
  55.     # Get results
  56.     my @sort = sort { $b->{inspect} <=> $a->{inspect} } (@monkeys);
  57.     return ($sort[0]->{inspect} * $sort[1]->{inspect});
  58. }
  59.  
  60. print "Part 1: ", &run_monkeys(    20, sub { floor( $_[0] / 3 ) } ), "\n";
  61. print "Part 2: ", &run_monkeys( 10000, sub { $_[0] % $modulus   } ), "\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement