AoC 2023 D7P2: Pseudo-Poker Hands with Wildcards

Part 2 redefines J from jack to joker, making jokers wildcards when determining type of hand but the lowest value when comparing individual cards. This requires very little modification to the part 1 program:

my $cardlist = "AKQT98765432J";

Change the card sort order;

my $jokers = grep { $_ eq "J" } @cards;

count the jokers;

++ $tally{$_} foreach grep { $_ ne "J" } @cards;

omit the jokers when counting cards for type of hand;

$ofakind[0] += $jokers;

and in this poker variant, simply add the count of jokers to the count of the most-frequent card when determining type of hand.

Full Program

#!/usr/bin/perl

use warnings;
use strict;

sub cardval;

my @hands;

while (<>) {
my ($cards, $bid) = /(\w+)/g;
my @cards = split(//, $cards);
my @values = map { cardval($_) } @cards;
my $jokers = grep { $_ eq "J" } @cards;

my %tally;
++ $tally{$_} foreach grep { $_ ne "J" } @cards;
my @ofakind = sort { $b <=> $a } values %tally;
$ofakind[0] += $jokers;
my $type = $ofakind[0] == 5 ? 6 # 5 of kind -- 6
: $ofakind[0] == 4 ? 5 # 4 of kind -- 5
: $ofakind[0] == 3 && $ofakind[1] == 2 ? 4 # full house -- 4
: $ofakind[0] == 3 ? 3 # 3 of kind -- 3
: $ofakind[0] == 2 && $ofakind[1] == 2 ? 2 # 2 pair -- 2
: $ofakind[0] == 2 ? 1 # 1 pair -- 1
: 0; # nothing -- 0

push(@hands, { CARDS => [ @cards ], BID => $bid, VALUES => [ @values ],
TYPE => $type });
}

my @sortedhands = sort { ${$a}{TYPE} <=> ${$b}{TYPE}
|| ${$a}{VALUES}[0] <=> ${$b}{VALUES}[0]
|| ${$a}{VALUES}[1] <=> ${$b}{VALUES}[1]
|| ${$a}{VALUES}[2] <=> ${$b}{VALUES}[2]
|| ${$a}{VALUES}[3] <=> ${$b}{VALUES}[3]
|| ${$a}{VALUES}[4] <=> ${$b}{VALUES}[4]
} @hands;

my $sum;
$sum += ($_ + 1) * $sortedhands[$_]{BID} foreach (0 .. scalar @sortedhands - 1);
print "sum is $sum\n";

sub cardval {
my $c = shift;
my $cardlist = "AKQT98765432J";
return length($cardlist) - index($cardlist, $c);
}

Leave a Reply