Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- no warnings qw(portable); # because binary number created > 32-bits
- use feature qw(say);
- $; = ',';
- $/ = '';
- my ($in_wires, $gate_rules) = map {[split /\n/]} <>;
- my %wire;
- my %gate;
- foreach (@$in_wires) {
- my ($in, $val) = m#(\w+): ([01])#;
- $wire{$in} = int($val);
- }
- my %logic = ('AND' => '&', 'OR' => '|', 'XOR' => '^');
- foreach (@$gate_rules) {
- my ($in1, $op, $in2, $out) = m#(\w+) ([A-Z]+) (\w+) -> (\w+)#;
- my @in = sort( $in1, $in2 );
- $gate{$in[0],$in[1],$out} = "\$wire{$out} = \$wire{$in1} $logic{$op} \$wire{$in2}";
- }
- my $done = 0;
- while (!$done) {
- $done = 1;
- foreach my $g (keys %gate) {
- my ($in1, $in2, $out) = split( $;, $g );
- if (defined( $wire{$in1} ) and defined( $wire{$in2} ) and !defined( $wire{$out} )) {
- $done = 0;
- my @in = sort( $in1, $in2 );
- eval( $gate{$in[0],$in[1],$out} );
- }
- }
- }
- 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