From: Jan "Yenya" Kasprzak Date: Tue, 21 Dec 2021 07:20:44 +0000 (+0100) Subject: 42.pl: a bit cleaner version X-Git-Url: https://www.fi.muni.cz/~kas/git//home/kas/public_html/git/?a=commitdiff_plain;h=1ab60ad03ad16aece7dbf059f873fd2b6ef9071c;p=aoc2021.git 42.pl: a bit cleaner version --- diff --git a/42.pl b/42.pl index 520496d..c8af64b 100755 --- a/42.pl +++ b/42.pl @@ -3,11 +3,6 @@ use v5.16; use bigint; -my (@p) = @ARGV; -my @s = (0, 0); -my $d = 1; -my $dc = 0; - my %state_count = ( 3 => 1, 4 => 3, @@ -19,49 +14,41 @@ my %state_count = ( ); use Array::Heap; -my @queue = [ 0, $p[0], $p[1], 0, 0 ]; +my @queue = [ 0, 0, $ARGV[0], $ARGV[1], 0, 0 ]; -$; = ','; -my %states = ( "$p[0],$p[1],0,0" => 1 ); +my %states = ( join(',', @{ $queue[0] }) => 1 ); my @wins = (0, 0); while (my $q = pop_heap @queue) { - my @p1add; - my $count = $states{$q->[1],$q->[2],$q->[3],$q->[4]}; - # say "pop: ", join(',', @$q); - for my $d1 (3 .. 9) { - my ($sum, $p1, $p2, $s1, $s2) = @$q; - $p1 += $d1; - $p1 -= 10 while $p1 > 10; - $s1 += $p1; - my $c1 = $count * $state_count{$d1}; - if ($s1 >= 21) { - $wins[0] += $c1; + my $count = $states{join(',', @$q)}; + for my $dice (3 .. 9) { + my $player = $q->[1]; + my $pos = $q->[2+$player]; + my $score = $q->[4+$player]; + $pos += $dice; + $pos -= 10 while $pos > 10; + $score += $pos; + my $ncount = $count * $state_count{$dice}; + if ($score >= 21) { + $wins[$player] += $ncount; next; } - for my $d2 (3 .. 9) { - my ($np2, $ns2, $c2) = ($p2, $s2, $c1); - $np2 += $d2; - $np2 -= 10 while $np2 > 10; - $ns2 += $np2; - $c2 *= $state_count{$d2}; - if ($ns2 >= 21) { - $wins[1] += $c2; - next; - } - my $key = "$p1,$np2,$s1,$ns2"; - # say "key=$key"; - if ($states{$key}) { - $states{$key} += $c2; - } else { - $states{$key} = $c2; - push_heap @queue, [ $s1+$ns2, $p1, $np2, $s1, $ns2 ]; - } + my @nq = @$q; + $nq[0] += $pos; + $nq[1] = 1-$player; + $nq[2+$player] = $pos; + $nq[4+$player] = $score; + my $key = join(',', @nq); + if ($states{$key}) { + $states{$key} += $ncount; + } else { + $states{$key} = $ncount; + push_heap @queue, \@nq; } } - # say "queue: ", scalar @queue, " states ", scalar keys %states; } -say $wins[0], ' vs ', $wins[1], " winner is ", $wins[0] > $wins[1] ? 'first' : 'second'; +say $wins[0], ' vs ', $wins[1], " winner is ", + $wins[0] > $wins[1] ? 'first' : 'second';