Skip to content

Instantly share code, notes, and snippets.

@emlun
Last active April 9, 2017 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emlun/e8a9b85c052d7e224686b1a2331bcbcd to your computer and use it in GitHub Desktop.
Save emlun/e8a9b85c052d7e224686b1a2331bcbcd to your computer and use it in GitHub Desktop.
two-combinations
(defn pair-with-all-in
{ :test #(let [f pair-with-all-in]
(is (= [] (f 0 [])))
(is (= [ [0 1] ] (f 0 [1])))
(is (= [ [0 1] [0 2] ] (f 0 [1 2])))
)
}
[ x ys ]
(map (fn [y] [x y]) ys))
(defn two-combinations
"Returns a lazy sequence of all pairs of elements in coll.
If the second argument is a map with :mirror-pairs set to logical false, then i < k for the corresponding indices [i k] of the returned pairs."
{:test #(let [f two-combinations]
(is (empty? (f [])))
(is (empty? (f [1])))
(is (empty? (f [4])))
(is (= (f [1 2]) [[1 2] [2 1]]))
(is (= (f [1 2 3]) [[1 2] [1 3] [2 1] [2 3] [3 1] [3 2]]))
(is (= (f [1 2 3 4]) [[1 2] [1 3] [1 4] [2 1] [2 3] [2 4] [3 1] [3 2] [3 4] [4 1] [4 2] [4 3]]))
(is (= (f [1 2 3 4] { :mirror-pairs false }) [[1 2] [1 3] [1 4] [2 3] [2 4] [3 4]]))
)}
([ coll ] (two-combinations coll { :mirror-pairs true }))
([ coll { :keys [mirror-pairs] } ]
(lazy-seq
(apply concat
(map-indexed
(fn [n middle]
(let [
[prefix [middle-again & suffix]] (split-at n coll)
right-halves (if mirror-pairs
(lazy-cat prefix suffix)
suffix)
]
(pair-with-all-in middle right-halves)
)
)
coll
)
)
))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment