Last active
August 31, 2015 10:49
-
-
Save maxweber/633d357641b8af50c3fe to your computer and use it in GitHub Desktop.
Cartesian Product
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
(def data [[1 2] [11 22] [111 222]]) | |
(defn combine [a b] | |
(mapcat | |
(fn [x] | |
(map | |
(fn [y] | |
(flatten [x y])) | |
b)) | |
a)) | |
(defn cartesian-product [sets] | |
(reduce | |
(fn [r set] | |
(combine r set)) | |
(first sets) | |
(rest sets))) | |
(cartesian-product data) |
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
var data = [[1,2], [11,22], [111,222]]; | |
var combine = function (a, b) { | |
return mori.mapcat( | |
function(x) { | |
return mori.map( | |
function (y) { | |
return mori.flatten([x,y]);}, b); | |
}, a); | |
}; | |
var cartesian_product = function (sets) { | |
return mori.reduce( | |
function(r, set) { | |
return combine(r,set); | |
}, sets[0], mori.rest(sets)); | |
} | |
console.log(mori.toJs(cartesian_product( | |
data))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://jsbin.com/layiyugute/1/edit?html,js,output