Created
February 7, 2020 22:15
-
-
Save celwell/62daff5d32e73266e2668c546cf2941e to your computer and use it in GitHub Desktop.
Answer to 4Clojure #178 - Best Hand
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; http://www.4clojure.com/problem/178 | |
(fn [card-strs] | |
(let [card-str->map (fn [[suit-char rank-char]] | |
{:suit ({\S :spade | |
\H :heart | |
\D :diamond | |
\C :club} suit-char) | |
:rank (case rank-char | |
\A 12 | |
\K 11 | |
\Q 10 | |
\J 9 | |
\T 8 | |
(- (Integer/parseInt (str rank-char)) 2))}) | |
cards (map card-str->map card-strs) | |
flush? (fn [cards] | |
(let [suit (:suit (first cards))] | |
(every? (comp (partial = suit) :suit) cards))) | |
consecutive? (fn [ranks] | |
(let [sorted-ranks (sort ranks) | |
first-rank (first sorted-ranks)] | |
(= sorted-ranks | |
(range first-rank (+ first-rank 5))))) | |
straight? (fn [cards] | |
(let [ranks (map :rank cards)] | |
(or (consecutive? ranks) | |
;; what about if Ace is treated as 1? | |
(consecutive? (map #(if (= % 12) -1 %) ranks))))) | |
sorted-rank-frequency (fn [cards] | |
(sort > (vals (frequencies (map :rank cards))))) | |
n-of-a-kind? (fn [n cards] | |
(= n (first (sorted-rank-frequency cards)))) | |
four-of-a-kind? (partial n-of-a-kind? 4) | |
three-of-a-kind? (partial n-of-a-kind? 3) | |
pair? (partial n-of-a-kind? 2) | |
two-pair? (fn [cards] | |
(apply = 2 ((juxt first second) (sorted-rank-frequency cards)))) | |
full-house? (fn [cards] | |
(= [3 2] ((juxt first second) (sorted-rank-frequency cards))))] | |
(cond | |
(and (flush? cards) | |
(straight? cards)) :straight-flush | |
(four-of-a-kind? cards) :four-of-a-kind | |
(full-house? cards) :full-house | |
(flush? cards) :flush | |
(straight? cards) :straight | |
(three-of-a-kind? cards) :three-of-a-kind | |
(two-pair? cards) :two-pair | |
(pair? cards) :pair | |
:else :high-card))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment