Play Best Card in Euchre
Perl - 557 532 511 490 482 384 363

($p,$t,$h)=@ARGV;%L=(H=&gt;D,D=&gt;H,C=&gt;S,S=&gt;C);$B=%L{$t};$_="\]$p$h\[";s/(.$t)/0$1/g;s/J$B/01$B/;s/0J/00/;s/J/R/g;s/9/Z/g;($T,@C)=split/\]\[/,$_;$s=$C[0];$s=~s/.+(.)/$1/;$s=~s/$t/0/;$X=(sort@C[0..2])[0];@M=@C[3..6];@F=(grep{/$s/}@M);@M=@F if@F;$w=(sort@M)[@M-1];push@M,$X;foreach$g(sort@M){$g ne$X?$b=$g:last}$_=$C[1]eq$X||!$b?$w:$b;s/.(..)/$1/;s/Z/9/;s/0|1|R/J/;print


How it works

Try it online!

First it reads args and finds the left-bauer's suit (jack of the same color as trump) with a hash lookup:

($p,$t,$h)=@ARGV;
%L=(H=&gt;D,D=&gt;H,C=&gt;S,S=&gt;C);
$B=%L{$t};


Then it combines all cards into one string and does some replacements, making the cards naturally sort in the correct order for euchre:

$_="\]$p$h\[";
s/(.$t)/0$1/g; # trump cards start with '0'
s/J$B/01$B/;   # left-bauer's 'J' changes to '01', making it trump
s/0J/00/;      # right-bauer's 'J' changes to '0'
s/J/R/g;       # all other jacks have 'J' changed to 'R'
s/9/Z/g;       # all 9s change to Z
($T,@C)=split/\]\[/,$_;


At the end of this block, the card string is then split on the brackets, which builds an array of all cards where:


index 0 = opponent's lead card
index 1 = teammate's card
index 2 = other opponent's card
indices 3-6 represent the hand


The lead suit is parsed from the first card, but the suit changes to '0' to represent trump if trump was led:

$s=$C[0];
$s=~s/.+(.)/$1/;
$s=~s/$t/0/;


The best card in-play is found by sorting the first three cards and retrieving the first card:

$X=(sort@C[0..2])[0];


The playable cards are found. If any cards in-hand match the lead suit, then only those cards remain. Otherwise all cards are considered playable:

@M=@C[3..6];
@F=(grep{/$s/}@M);
@M=@F if@F;


The 'throwaway' card is found by returning the last card in the sorted array of playable cards:

$w=(sort@M)[@M-1];


The lowest 'winning' card that can win the trick is found by adding the highest card in-play to the array of playable cards, sorting the array, and iterating over it until the highest card in-play is found. The 'winning' card is the card from the previous iteration:

push@M,$X;
foreach$g(sort@M){$g ne$X?$b=$g:last}


The correct play is then evaluated. The 'throwaway' card is chosen if any of the following are true:


The best card on the table has an index of 1 in the unsorted array of all cards, meaning it belongs to our teammate
The search for the lowest 'winning' card came up null, meaning our opponent's best card is higher than all cards in the hand


Otherwise the 'winning' card is returned:

$_=$C[1]eq$X||!$b?$w:$b;
s/.(..)/$1/; # remove the '0' that indicated trump
s/Z/9/;      # get those 9s back
s/0|1|R/J/;  # fix the jacks
print