Skip to content

Instantly share code, notes, and snippets.

@phiat
Created April 4, 2014 05:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phiat/9968800 to your computer and use it in GitHub Desktop.
Save phiat/9968800 to your computer and use it in GitHub Desktop.
clojure best hand
(defn best-hand [hand]
(let [suit (fn [c] (first c))
rank (fn [c] (last c))
ranks [\2 \3 \4 \5 \6 \7 \8 \9 \T \J \Q \K \A]
four-of-a-kind? (fn [h] (if (some #(= 4 %) (vals (frequencies (map rank h)))) true false))
flush? (fn [h] (= 1 (count (vals (frequencies (map suit h))))))
straight? (fn [h] (let [indexed-ranks (sort (map #(.indexOf ranks %) (map rank h)))
ends-diff (- (first indexed-ranks) (last indexed-ranks))]
(cond
(and (= 5 (count (frequencies indexed-ranks)))
(= ends-diff -4)) true
(= indexed-ranks '(0 1 2 3 12)) true
:else false)))
trips? (fn [h] (if (some #(= 3 %) (vals (frequencies (map rank h)))) true false))
two-pair? (fn [h](if (= 3 (count (frequencies (map rank h)))) true false))
pair? (fn [h](if (some #(= 2 %) (vals (frequencies (map rank h)))) true false))
straight-flush? (fn [h] (and (straight? h) (flush? h)))
full-house? (fn [h] (= 2 (count (frequencies (map rank h) ))))
]
(cond
(straight-flush? hand) :straight-flush
(four-of-a-kind? hand) :four-of-a-kind
(full-house? hand) :full-house
(flush? hand) :flush
(straight? hand) :straight
(trips? hand) :three-of-a-kind
(two-pair? hand) :two-pair
(pair? hand) :pair
:else :high-card )))
(best-hand ["DA" "DK" "DQ" "DJ" "DT"])
(best-hand ["H4" "D4" "C4" "HJ" "HT"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment