Skip to content

Instantly share code, notes, and snippets.

@apeckham
Last active January 29, 2023 20:14
Show Gist options
  • Save apeckham/61228ac402604c041b332db60b542e6a to your computer and use it in GitHub Desktop.
Save apeckham/61228ac402604c041b332db60b542e6a to your computer and use it in GitHub Desktop.
(defn partition-before
"Partition the input before (pred this-partition) returns true"
[pred items]
(if (seq items)
(reduce (fn [lists item]
(if (pred (concat (last lists) [item]))
(concat lists [[item]])
(concat (butlast lists) [(concat (last lists) [item])])))
[[(first items)]]
(rest items))
[]))
(deftest partition-before-test
(let [sum-gt-10 #(< 10 (apply + %))]
(is (not (sum-gt-10 [])))
(is (not (sum-gt-10 [5])))
(is (not (sum-gt-10 [5 5])))
(is (sum-gt-10 [5 5 5]))
(is (= [[0 0 0 6 1] [6 3] [9 0] [2]] (partition-before sum-gt-10 [0 0 0 6 1 6 3 9 0 2])))
(is (= [[0 7 3] [5] [9] [4 4 2] [7 2]] (partition-before sum-gt-10 [0 7 3 5 9 4 4 2 7 2])))
(is (= [[5]] (partition-before sum-gt-10 [5])))
(is (= [] (partition-before sum-gt-10 [])))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment