From 3684ca9d1ae7dacde3f862d3426bc898de27d5ff Mon Sep 17 00:00:00 2001 From: Yanick Champoux Date: Mon, 18 Dec 2017 13:45:46 -0500 Subject: [PATCH] day18 --- 18/2.pl | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 18/2.pl diff --git a/18/2.pl b/18/2.pl new file mode 100644 index 0000000..c99c103 --- /dev/null +++ b/18/2.pl @@ -0,0 +1,73 @@ +use 5.20.0; +use experimental qw/ signatures postderef /; +use List::AllUtils qw/ any /; + +my @commands = <>; + +my @prog = map { bless + { q => [], id => $_, reg => { p => $_ }, }, 'Prog' +} 0..1; + +use DDP; + +my $sent1; + + +package Prog { + my $vr = qr/(?-?\d+|.)/; + + sub valof($self, $x) { + $x =~ /\d/ ? $x : $self->{reg}{$x}; + } + + sub run($self) { + while() { + use DDP; + my $i = $self->{i}; + my $c = $commands[$i] or return; + + if( $c =~ /snd (.)/ ) { + warn ++$sent1 if $self->{id}; + push $prog[ 1 - $self->{id} ]->{q}->@*, $self->valof($1); + } + elsif( $c =~ /set (.) $vr/ ) { + $self->{reg}{$1} = $self->valof($2); + } + elsif( $c =~ /add (.) $vr/ ) { + $self->{reg}{$1} += $self->valof($2); + } + elsif( $c =~ /mul (.) $vr/ ) { + $self->{reg}{$1} *= $self->valof($2); + } + elsif( $c =~ /mod (.) $vr/ ) { + $self->{reg}{$1} %= $self->valof($2); + } + elsif( $c =~ /jgz (.) $vr/ ) { + $self->{i} += ($self->valof($1) > 0) ? $self->valof($2) : 1; + next; + } + elsif( $c =~ /rcv (.)/ ) { + return unless $self->{q}->@*; + my $j = shift $self->{q}->@*; + $self->{reg}{$1} = $j; + } + else { die "wut? $_"; } + + $self->{i}++; + + } + } +} + +while() { + $prog[1]->run; + $prog[0]->run; + # p @prog; + # my $dummy = ; + warn join ":", map { $_->{i} } @prog; + last unless any { scalar $_->@* } map { $_->{q} } @prog; + last if 2 == grep { $_ >= @commands } map { $_->{i} } @prog; +} + +say $sent1; +