Search code examples
algorithmclojure

Deal x Number of Hands of Cards in Clojure - vs Partition


What is the most idiomatic and efficient way within Clojure to deal a hand of cards to a certain number of players. Clojure's partition doesn't actually simulate real world physical dealing of cards.

Note: I'd like to be able to deal to any number of players. Doesn't matter if cards are fully dealt unequally. I'd like to be very generic as to handle sub 52 cards... or multiple decks mixed.

Example data structure of available cards and empty function signature:

(def sample-cards 
    [[:5 :Heart]
    [:8 :Spade]
    [:7 :Club]
    [:9 :Diamond]
    [:J :Spade]
    [:Q :Heart]
    [:5 :Spade]
    [:8 :Club]
    [:6 :Diamond]])


(defn deal-cards [players deck]
    ; some logic/looping 
    ; then return give the args 4 and sample-cards
    [[[:5 :Heart] [:J :Spade] [:6 :Diamond]]
    [[:8 :Spade] [:Q :Heart]]
    [[:7 :Club]  [:5 :Spade]]
    [[:9 :Diamond] [:8 :Club]]])

Solution

  • Here is a fairly compact implementation using lazy sequences:

    (defn deal-cards [n deck]
      (map (partial take-nth n)
           (take n (iterate rest deck))))
    

    An example:

    (deal-cards 4 sample-cards)
    ;; => (([:5 :Heart] [:J :Spade] [:6 :Diamond]) ([:8 :Spade] [:Q :Heart]) ([:7 :Club] [:5 :Spade]) ([:9 :Diamond] [:8 :Club]))