Advertisement
musifter

AoC 2022, day 21 (perl part 2)

Dec 21st, 2022
1,529
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.30 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. my %monkey;
  7. while (<>) {
  8.     chomp;
  9.     my ($monk, $yell) = split ':';
  10.  
  11.     if ($yell =~ m#(\d+)#) {
  12.         $monkey{$monk} = [$1];
  13.     } else {
  14.         $yell =~ m#(\w+) (.) (\w+)#;
  15.         $monkey{$monk} = [$2, $1, $3];
  16.     }
  17. }
  18.  
  19. sub recurse_parse_tree {
  20.     my $monk = shift @_;
  21.     my $node = $monkey{$monk};
  22.  
  23.     return ($node->[0]) if (@$node == 1);
  24.  
  25.     my @arg;
  26.     foreach my $i (1 .. 2) {
  27.         if ($node->[$i] eq 'humn') {
  28.             $arg[$i] = ' $humn ';
  29.         } else {
  30.             $arg[$i] = &recurse_parse_tree( $node->[$i] );
  31.         }
  32.     }
  33.  
  34.     my $res = "($arg[1] $node->[0] $arg[2])";
  35.     if ($res !~ m#humn#) {
  36.         $res = eval( $res );
  37.     }
  38.  
  39.     return ($res);
  40. }
  41.  
  42. my $targ1 = &recurse_parse_tree( $monkey{root}[1] );
  43. my $targ2 = &recurse_parse_tree( $monkey{root}[2] );
  44.  
  45. my ($cmd, $num) = ($targ1 =~ m#humn#) ? ($targ1, $targ2) : ($targ2, $targ1);
  46.  
  47. print "Looking to balance: $num\n";
  48. print "Expression: $cmd\n";
  49.  
  50. my $humn = 0;
  51. my $zero = eval( $cmd );
  52.  
  53. $humn = 1;
  54. my $diff = eval( $cmd ) - $zero;
  55.  
  56. $humn = ($num - $zero) / $diff;
  57.  
  58. print "Human yells 0: $zero\n";
  59. print "Differnce between human yell values: $diff\n";
  60. print "Interpolation: $humn\n";
  61.  
  62. print "Part 2: $humn\n"  if (eval( $cmd ) == $num);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement