Poker hand analyser: Difference between revisions

m
syntax highlighting fixup automation
m (→‎{{header|J}}: slightly clearer, and illustrate use)
m (syntax highlighting fixup automation)
Line 87:
{{trans|D}}
 
<langsyntaxhighlight lang="11l">F analyzeHandHelper(faceCount, suitCount)
V
p1 = 0B
Line 163:
‘4H 4C KC 5D TC’,
‘QC TC 7C 6C 4C’]
print(hand‘: ’analyzeHand(hand))</langsyntaxhighlight>
 
{{out}}
Line 179:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">PokerHand(hand){
StringUpper, hand, hand
Sort, hand, FCardSort D%A_Space%
Line 202:
b := (b = "T") ? 10 : (b = "J") ? 11 : (b = "Q") ? 12 : (b = "K") ? 13 : b
return a > b ? 1 : a < b ? -1 : 0
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">hands =
(join`r`n
2♥ 2♦ 2♣ k♣ q♦
Line 220:
res .= PokerHand(A_LoopField) "`n"
MsgBox, 262144, , % res
return</langsyntaxhighlight>
Outputs:<pre>2♦ 2♣ 2♥ Q♦ K♣ Three of a Kind
2♥ 5♥ 7♦ 8♣ 9♠ High Card
Line 235:
=={{header|C}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <ctype.h>
#include <string.h>
Line 363:
}
return 0;
}</langsyntaxhighlight>
 
{{output}}
Line 381:
=={{header|C sharp}}==
{{works with|C sharp|8}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using static System.Linq.Enumerable;
Line 542:
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 570:
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">
<lang Cpp>
#include <iostream>
#include <sstream>
Line 645:
cout << p.analyze( "qc tc 7c 6c 4c" ) << endl << endl; return system( "pause" );
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 660:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn rank [card]
(let [[fst _] card]
(if (Character/isDigit fst)
Line 740:
["QC" "TC" "7C" "6C" "4C"]])
(run! println (map #(str % " : " (check-hand %)) hands))
</syntaxhighlight>
</lang>
 
{{out}}
Line 759:
No bonus for this simple version.
{{trans|C++}}
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.algorithm, std.range;
 
string analyzeHand(in string inHand) pure /*nothrow @safe*/ {
Line 844:
"QC TC 7C 6C 4C"])
writeln(hand, ": ", hand.analyzeHand);
}</langsyntaxhighlight>
{{out}}
<pre>2H 2D 2S KS QD: three-of-a-kind
Line 859:
{{trans|Ruby}}
{{works with|Elixir|1.2}}
<langsyntaxhighlight lang="elixir">defmodule Card do
@faces ~w(2 3 4 5 6 7 8 9 10 j q k a)
@suits ~w(♥ ♦ ♣ ♠) # ~w(h d c s)
Line 985:
best = Enum.map(cards_list, &Hand.new &1) |> Enum.max
IO.puts "#{hand}:\t#{elem(best,3)}"
end)</langsyntaxhighlight>
 
{{out}}
Line 1,022:
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
type Card = int * int
 
Line 1,122:
]
|> List.iter showHandRank
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,152:
=={{header|Factor}}==
Factor comes with a poker hand evaluator.
<langsyntaxhighlight lang="factor">USING: formatting kernel poker sequences ;
{
"2H 2D 2C KC QD"
Line 1,163:
"4H 4S KS 5D TS"
"QC TC 7C 6C 4C"
} [ dup string>hand-name "%s: %s\n" printf ] each</langsyntaxhighlight>
{{out}}
<pre>
Line 1,180:
{{trans|Kotlin}}
===Basic Version===
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,305:
fmt.Printf("%s: %s\n", hand, analyzeHand(hand))
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,322:
 
===Extra Credit Version===
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,537:
fmt.Printf("%s: %s\n", hand, analyzeHand(hand))
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,560:
=={{header|Haskell}}==
===Basic Version===
<langsyntaxhighlight Haskelllang="haskell">{-# LANGUAGE TupleSections #-}
 
import Data.Function (on)
Line 1,654:
 
main :: IO ()
main = mapM_ (putStrLn . (fst <> const ": " <> nameHand . snd)) testHands</langsyntaxhighlight>
{{out}}
<pre>2♥ 2♦ 2♣ k♣ q♦: Three of a kind
Line 1,670:
=={{header|J}}==
 
<langsyntaxhighlight Jlang="j">parseHand=: ' ' cut 7&u: NB. hand must be well formed
Suits=: <"> 7 u: '♥♦♣♦' NB. or Suits=: 'hdcs'
Faces=: <;._1 ' 2 3 4 5 6 7 8 9 10 j q k a'
Line 1,717:
4♥ 4♠ k♠ 5♦ 10♠
q♣ 10♣ 7♣ 6♣ 4♣
}}</langsyntaxhighlight>
 
Note that * acts as "logical and" on logical values (if you need to deal with boolean values in the original sense - which were not constrained to logical values - you should use *. instead of * to achieve boolean multiplication, but that's not needed here).
Line 1,753:
{{works with|Java|7}}
This code does not qualify for extra credit. Although it supports wildcards, it does not allow for duplicates.
<langsyntaxhighlight lang="java">import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
Line 1,932:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,982:
=={{header|JavaScript}}==
{{works with|JavaScript|ECMAScript 6}}
<langsyntaxhighlight JavaScriptlang="javascript">const FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'j', 'q', 'k', 'a'];
const SUITS = ['♥', '♦', '♣', '♠'];
 
Line 2,012:
else if (groups[0] === 2) return 'one-pair'
else return 'high-card';
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight JavaScriptlang="javascript">let testHands = [
"2♥ 2♦ 2♣ k♣ q♦",
"2♥ 5♥ 7♦ 8♣ 9♠",
Line 2,033:
];
for(hand of testHands) console.log(hand + ": " + analyzeHand(hand));</langsyntaxhighlight>
{{out}}
<pre>
Line 2,055:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">sorteddeck = [string(r) * s for s in "♣♦♥♠", r in "23456789TJQKA"]
 
cardlessthan(card1, card2) = indexin(x, sorteddeck)[1] < indexin(y, sorteddeck)[1]
Line 2,175:
println("Hand $hand is a ", scorehand(hand), " hand.")
end
</langsyntaxhighlight>{{output}}<pre>
Hand ["2♥", "2♦", "2♣", "K♣", "Q♦"] is a three-of-a-kind hand.
Hand ["2♥", "5♥", "7♦", "8♣", "9♠"] is a high-card hand.
Line 2,192:
=={{header|Kotlin}}==
===Basic Version===
<langsyntaxhighlight lang="scala">// version 1.1.2
 
class Card(val face: Int, val suit: Char)
Line 2,267:
println("$hand: ${analyzeHand(hand)}")
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,284:
 
===Extra Credit Version===
<langsyntaxhighlight lang="scala">// version 1.1.2
 
class Card(val face: Int, val suit: Char)
Line 2,411:
println("$hand : ${analyzeHand(hand)}")
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,433:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">-- Check whether t is a valid poker hand
function valid (t)
if #t ~= 5 then return false end
Line 2,555:
"qc 10c 7c 6c 4c" -- flush
}
for _, case in pairs(testCases) do print(case, ": " .. rank(case)) end</langsyntaxhighlight>
{{out}}
<pre>2h 2d 2c kc qd : three-of-a-kind
Line 2,568:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import algorithm, sequtils, strutils, tables, unicode
 
type
Line 2,691:
for handString in HandStrings:
let hand = handString.split(' ').map(toCard)
echo hand.map(`$`).join(" "), " → ", hand.value</langsyntaxhighlight>
 
{{out}}
Line 2,708:
I dont like jokers. Instead I decided to give hands proper names. For example, "Kings full of Tens" rather than just "full-house".
 
<langsyntaxhighlight lang="perl">
use strict;
use warnings;
Line 2,851:
say Hand::describe($_) for @cards;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,880:
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/poker_hand.htm here].
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">poker</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">hand</span><span style="color: #0000FF;">)</span>
Line 2,977:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d. %s %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">11</span><span style="color: #0000FF;">-</span><span style="color: #000000;">rank</span><span style="color: #0000FF;">,</span><span style="color: #000000;">hand</span><span style="color: #0000FF;">,</span><span style="color: #000000;">desc</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,005:
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">go =>
Hands = [
[[2,h], [7,h], [2,d], [3,c], [3,d]], % two-pair
Line 3,152:
% high card
analyse1(_Hand,Value) =>
Value = high_card.</langsyntaxhighlight>
 
 
Line 3,194:
 
For generating and checking random hands:
<langsyntaxhighlight Picatlang="picat">go2 =>
_ = random2(),
Hand = random_hand(5),
Line 3,213:
M.put([oneof(Faces),oneof(Suites)],1)
end,
Hand = [C : C=_ in M].sort().</langsyntaxhighlight>
 
{{out}}
Line 3,222:
=={{header|PicoLisp}}==
(rassoc) function in picolisp after 3.1.9.10.
<langsyntaxhighlight PicoLisplang="picolisp">(setq *Rank
'(("2" . 0) ("3" . 1) ("4" . 2)
("5" . 3) ("6" . 4) ("7" . 5)
Line 3,257:
'two-pair )
((rassoc 2 R) 'pair)
(T 'high-card) ) ) )</langsyntaxhighlight>
 
=={{header|Prolog}}==
{{works with|GNU Prolog|1.4.4}}
Not very efficient version.
<langsyntaxhighlight lang="python">:- initialization(main).
 
 
Line 3,332:
, write(Cards), write('\t'), write(H), nl
.
main :- findall(_, run_tests, _), halt.</langsyntaxhighlight>
{{out}}
<pre>[c(2,♥),c(2,♦),c(2,♣),c(k,♣),c(q,♦)] three-of-a-kind(2)
Line 3,346:
=={{header|Python}}==
Goes a little further in also giving the ordered tie-breaker information from the wikipedia page.
<langsyntaxhighlight lang="python">from collections import namedtuple
 
class Card(namedtuple('Card', 'face, suit')):
Line 3,495:
for cards in hands:
r = rank(cards)
print("%-18r %-15s %r" % (cards, r[0], r[1]))</langsyntaxhighlight>
{{out}}
<pre>HAND CATEGORY TIE-BREAKER
Line 3,509:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
(require (only-in srfi/1 car+cdr))
 
Line 3,673:
(five-of-a-kind 7) (straight-flush 14) (one-pair 13 10 5 4) (flush 14 13 7 6 4) (straight 6)
(straight 14) (straight-flush 14) (four-of-a-kind 2)))
(for ((h e.g.-hands) (r expected-results)) (check-equal? (analyse-hand/string h) r)))</langsyntaxhighlight>
 
{{out}}
Line 3,703:
(formerly Perl 6)
This solution handles jokers. It has been written to use a Raku grammar.
<syntaxhighlight lang="raku" perl6line>use v6;
grammar PokerHand {
Line 3,812:
say "$_: $rank";
}
</syntaxhighlight>
</lang>
{{out}}
<pre>2♥ 2♦ 2♣ k♣ q♦: three-of-a-kind
Line 3,840:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 10.12.2013 Walter Pachl
*--------------------------------------------------------------------*/
Line 3,937:
err:
Say deck 'Error:' arg(1)
Return 0</langsyntaxhighlight>
{{out}}
<pre>2h 2d 2s ks qd three-of-a-kind
Line 3,963:
::* &nbsp; the dealt hands can be in a file &nbsp; (blank lines are ignored)
::* &nbsp; dealt hands in the file can have comments after a semicolon (''';''')
<langsyntaxhighlight lang="rexx">/*REXX program analyzes an N─card poker hand, and displays what the poker hand is. */
parse arg iFID .; if iFID=='' | iFID=="," then iFID= 'POKERHAN.DAT'
/* [↓] read the poker hands dealt. */
Line 4,002:
if kinds==2 & pairs==2 then return 'two-pair'
if kinds==2 then return 'one-pair'
return 'high-card'</langsyntaxhighlight>
Programming note: some older REXXes don't have the '''countstr''' BIF, so that REXX statement (above, line '''48''') can be replaced with:
<langsyntaxhighlight lang="rexx">pairs= 13 - length( space( translate( pips, , 2), 0) ) /*count # of 2's in PIPS.*/</langsyntaxhighlight>
 
{{out|input|text=&nbsp; file:}}
Line 4,041:
::* &nbsp; supports up to two ''jokers''
::* &nbsp; the ''joker'' card may be abbreviated (and can be in upper/lower/mixed case)
<langsyntaxhighlight lang="rexx">/*REXX program analyzes an N-card poker hand, and displays what the poker hand is, */
/*──────────────────────────────────────────── poker hands may contain up to two jokers.*/
parse arg iFID .; if iFID=='' | iFID=="," then iFID= 'POKERHAJ.DAT'
Line 4,099:
if kinds==2 & pairs==2 then return 'two-pair'
if kinds==2 then return 'one-pair'
return 'high-card'</langsyntaxhighlight>
Programming note: &nbsp; the method used for analyzing hands that contain jokers are limited to a maximum of two jokers.
 
Line 4,157:
=={{header|Ruby}}==
Joker-less hands are sorted high to low.
<langsyntaxhighlight lang="ruby">class Card
include Comparable
attr_accessor :ordinal
Line 4,300:
best = all_tries.max
puts "#{line.strip}: #{best.rank}"
end</langsyntaxhighlight>
 
{{out}}
Line 4,337:
=={{header|Rust}}==
Unicode version with jokers. Also checks for Royal Flush (AKQJ10 suited).
<syntaxhighlight lang="rust">
<lang Rust>
fn main() {
let hands = vec![
Line 4,446:
(face, suit)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,469:
=={{header|Scala}}==
Including jokers, but not special suit characters. Aiming for readability more than performance.
<langsyntaxhighlight lang="scala">val faces = "23456789TJQKA"
val suits = "CHSD"
sealed trait Card
Line 4,542:
val possibleHands = possibleRealHands(hand)
allHandTypes.find(t => possibleHands.exists(t.check)).map(_.name).getOrElse("high-card")
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="scala">val testHands = List(
"2H 2D 2S KS QD",
"2H 5H 7D 8S 9D",
Line 4,569:
for (hand <- testHands) {
println(s"$hand -> ${analyzeHand(parseHand(hand))}")
}</langsyntaxhighlight>
 
{{out}}
Line 4,595:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "console.s7i";
 
Line 4,669:
analyze("4♥ 4♣ k♣ 5♦ t♣");
analyze("q♣ t♣ 7♣ 6♣ 4♣");
end func;</langsyntaxhighlight>
 
{{out}}
Line 4,685:
 
=={{header|Standard ML}}==
<syntaxhighlight lang="standard ml">
<lang Standard ML>
local
val rec ins = fn x : int*'a => fn [] => [x]
Line 4,749:
end;
</syntaxhighlight>
</lang>
Example (interpreter):
<syntaxhighlight lang="standard ml">
<lang Standard ML>
val rec printio = fn
[] => ()
Line 4,779:
ac ah ac ad 10h : invalid
val it = (): unit
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
namespace eval PokerHandAnalyser {
proc analyse {hand} {
Line 4,898:
return 0
}
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">foreach hand {
"2♥ 2♦ 2♣ k♣ q♦" "2♥ 5♥ 7♦ 8♣ 9♠" "a♥ 2♦ 3♣ 4♣ 5♦" "2♥ 3♥ 2♦ 3♣ 3♦"
"2♥ 7♥ 2♦ 3♣ 3♦" "2♥ 7♥ 7♦ 7♣ 7♠" "10♥ j♥ q♥ k♥ a♥" "4♥ 4♠ k♠ 5♦ 10♠"
Line 4,906:
} {
puts "${hand}: [PokerHandAnalyser::analyse $hand]"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,921:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
option explicit
class playingcard
Line 5,047:
next
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,066:
{{libheader|Wren-seq}}
===Basic Version===
<langsyntaxhighlight lang="ecmascript">import "/dynamic" for Tuple
import "/sort" for Sort
import "/str" for Str
Line 5,136:
for (hand in hands) {
System.print("%(hand): %(analyzeHand.call(hand))")
}</langsyntaxhighlight>
 
{{out}}
Line 5,152:
</pre>
===Extra Credit Version===
<langsyntaxhighlight lang="ecmascript">import "/dynamic" for Tuple
import "/sort" for Sort
import "/seq" for Lst
Line 5,265:
for (hand in hands) {
System.print("%(hand): %(analyzeHand.call(hand))")
}</langsyntaxhighlight>
 
{{out}}
10,333

edits