Last active
April 9, 2017 13:51
-
-
Save emlun/e8a9b85c052d7e224686b1a2331bcbcd to your computer and use it in GitHub Desktop.
two-combinations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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