Advertisement
musifter

AoC 2024, part 1 (Perl)

Dec 24th, 2024 (edited)
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.08 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5. no  warnings        qw(portable);     # because binary number created > 32-bits
  6. use feature         qw(say);
  7.  
  8. $; = ',';
  9. $/ = '';
  10. my ($in_wires, $gate_rules) = map {[split /\n/]} <>;
  11.  
  12. my %wire;
  13. my %gate;
  14.  
  15. foreach (@$in_wires) {
  16.     my ($in, $val) = m#(\w+): ([01])#;
  17.     $wire{$in} = int($val);
  18. }
  19.  
  20. my %logic = ('AND' => '&', 'OR' => '|', 'XOR' => '^');
  21.  
  22. foreach (@$gate_rules) {
  23.     my ($in1, $op, $in2, $out) = m#(\w+) ([A-Z]+) (\w+) -> (\w+)#;
  24.     my @in = sort( $in1, $in2 );
  25.     $gate{$in[0],$in[1],$out} = "\$wire{$out} = \$wire{$in1} $logic{$op} \$wire{$in2}";
  26. }
  27.  
  28. my $done = 0;
  29. while (!$done) {
  30.     $done = 1;
  31.     foreach my $g (keys %gate) {
  32.         my ($in1, $in2, $out)  = split( $;, $g );
  33.         if (defined( $wire{$in1} ) and defined( $wire{$in2} ) and !defined( $wire{$out} )) {
  34.             $done = 0;
  35.             my @in = sort( $in1, $in2 );
  36.             eval( $gate{$in[0],$in[1],$out} );
  37.         }
  38.     }
  39. }
  40.  
  41. say "Part 1: ", oct( "0b".join('',  map {$wire{$_} } sort {$b cmp $a} grep {$_ =~ m#^z#} keys %wire ));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement