Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ericnormand
Created August 23, 2021 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ericnormand/435e5e03c4160e92366fbc9e70b7cb9b to your computer and use it in GitHub Desktop.
Save ericnormand/435e5e03c4160e92366fbc9e70b7cb9b to your computer and use it in GitHub Desktop.
440 PurelyFunctional.tv Newsletter

Dealing elements

There's a function in clojure.core called partition-all. It creates subsequences of a given maximum size.

(partition-all 3 [1 2 3 4 5 6 7 8]);=> [[1 2 3] [4 5 6] [7 8]]

Notice that the first sequence gets the first three elements, the second sequence gets the second three elements, etc. We could get the original sequence again by concatenating the sequences back together.

Your task is to write a function that deals out the cards more evenly. That is, the first element goes into the first sequence, the second element goes into the second sequence, etc. We're going to write two versions of this function.

Version one takes the maximum size of the subsequence. That means the number of subsequences will depend on the size of the given sequence.

;; at most 3 elements in each subsequence
(deal-max 3 [1 2 3 4 5 6 7 8]) ;=> [[1 4 7] [2 5 8] [3 6]]

Note that we can put these sequences back together with interleave (except for the behavior when you have a short sequence).

Version two takes the number of subsequences. It is variable in the size of the subsequence.

;; deal out 4 subsequences
(deal-out 4 [1 2 3 4 5 6 7 8]) ;=> [[1 5] [2 6] [3 7] [4 8]]

Note that this also can be put back together with interleave.

Write deal-max and deal-out. How do the implementations compare? Which is easier to write?

Thanks to this site for the problem idea, where it is rated Very Hard in JavaScript. The problem has been modified.

Please submit your solutions as comments on this gist.

To subscribe: https://purelyfunctional.tv/newsletter/

@KingCode
Copy link

KingCode commented Oct 1, 2021

(defn ->composite-index [i div]
  [(rem i div), (quot i div)])

(defn deal [n coll init-f]
  (->> coll
       (reduce (fn [[parts rank] x]
                 [(assoc-in parts
                            (->composite-index rank n)
                            x),
                  (inc rank)])
               [(init-f n coll) 0])
       first))

(defn init-from-maxsize [maxsiz coll]
  (-> coll count (/ maxsiz) Math/ceil int
      (repeat [])
      vec))

(defn init-from-numparts [numparts coll]
  (-> numparts (repeat []) vec))

(defn deal-max [n coll]
  (deal n coll init-from-maxsize))

(defn deal-out [n coll]
  (deal n coll init-from-numparts))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment