Skip to content

Instantly share code, notes, and snippets.

@ericnormand
Last active March 13, 2020 13:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericnormand/bc08ce8609f85478071ae5c99c0e7fa1 to your computer and use it in GitHub Desktop.
Save ericnormand/bc08ce8609f85478071ae5c99c0e7fa1 to your computer and use it in GitHub Desktop.

Number of hands of poker

Poker users a 52-card deck, where each card is unique. After shuffling, a player gets five random cards. How many different hands are there? Remember, in poker, the order of the cards in your hand does not matter.

Write a function that takes the number of cards in a hand h and the number of cards in the deck d and calculates how many possible hands there are.

(defn combinations [d h]
  .....
)

Hint: there is a mathematical formula for combinations already!

Combination formula

(defn factorial [n]
(reduce * (range 1N (inc n))))
(defn combinations [deck hand]
(let [d! (factorial deck)
h! (factorial hand)]
(/ d! (* h! (factorial (- deck hand))))))
(ns deck-combinations
(:require [clojure.test :refer :all]))
(defn factorial [x]
"Calculates the factorial of a number. Casts as a BigInteger upon integer overflow"
(reduce *' (range 1 (inc x))))
(defn combinations [d h]
(/ (factorial d) (* (factorial h) (factorial (- d h)))))
;; TESTS
(deftest hand-combinations-test
(is (= 1 (combinations 5 5)))
(is (= 2598960 (combinations 52 5))))
(defn combinations [d h]
(assert (int? d))
(assert (int? h))
(assert (pos? h))
(assert (> d h))
(let [s (- d h) [b t] (sort [h s])]
(loop [u (inc t) l b acc 1]
(if (zero? l)
acc
(recur (inc u) (dec l) (/ (* acc u) l))))))
=> #'user/combinations
(combinations 10 8)
=> 45N
(combinations 10 2)
=> 45N
(combinations 52 5)
=> 2598960N
(defn fac [n]
(reduce *' (range 1 (inc n))))
(defn combinations
"possible hands of h cards from deck size d"
[d h]
(int (/ (fac d) (*' (fac h) (fac (- d h))))))
(combinations 52 5) ;; 52 card deck
;; 2598960
(combinations 52 7) ;; 7 cards
;; 20358520
(combinations 104 5) ;; 2 decks
;; 91962520
(defn fact [n] (reduce * (range (bigint 1) (bigint (+ n 1)))))
(defn combs [deck choose] (/ (fact deck) (* (fact choose) (fact (- deck choose)))))
(combs 52 5)
2598960N
(defn fact [n]
(reduce *' (range 1 (inc n))))
;; Number of combinations of size 'n' taken from
;; a total collection of size 'pool-size'.
(defn n-combinations [pool-size n]
(/ (fact pool-size)
(*' (fact n)
(fact (- pool-size n)))))
(def num-poker-hands (n-combinations 52 5)) ; => 2598960
(defn factorial [n] (apply *' (map inc (range n))))
(defn combinations [d h] (/ (factorial d) (*' (factorial h) (factorial (-' d h)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment