-1

Currently I am trying to partition my lists in clojure into even splits of even values. To explain.

I have

(def a '(1 2 3 4 5 6 7 8 9 10))

What I want to do is give it a partition function and create even lists that are even in count. so if I were to split my list by 2 I would want it to look like

((1 2 3 4 5 6) (7 8 9 10)) or 
((1 2 3 4)(5 6 7 8 9 10)) producing 2 lists with even counts.

or if I want to split by 4 into even lists it would look something like

((1 2)(3 4)(5 6)(7 8 9 10)) 

I will always be splitting by even (ex. 2,4,8,16,32). but I want every return list to have even counts without remainders.

I am at a lost and have created numerous parition functions all which don't work. Any help is appreciated.

2 Answers2

0

Here is how I would do it:

(def a '(1 2 3 4 5 6 7 8 9 10))

(defn trunc-to-even
  "Truncates a value the largest even int less than or equal to value"
  [val]
  (* 2 (Math/floor (/ val 2))))

(defn even-lists [some-list]
  (let [half-even (trunc-to-even (/ (count some-list) 2))]
    (split-at half-even some-list )))

(println (even-lists a))

;=>  [(1 2 3 4) (5 6 7 8 9 10)]
Alan Thompson
  • 29,276
  • 6
  • 41
  • 48
  • That works great if i'm only splitting by two. I want to be able to configure the partition. method to work also with 2,4,6,8 splits of lists with even count values for each list. – Jeffrey Morgan Dec 04 '17 at 20:56
0

Marking the one above as the correct answer. I was able to use this method to further break it down to separate into even lists.

(defn trunc-to-even
"Truncates a value the largest int less than or equal to value"
  [val]
  (* 2 (Math/floor (/ val 2))))

(defn split-2 [some-list]
  (let [half-even (trunc-to-even (/ (count some-list) 2))]
    (split-at half-even some-list )))

(defn split-4 [x]
  (apply concat (pmap split-2(concat (split-2 x)))))

Doing this I can keep building on to split at 8-16-32.