Last active
December 15, 2015 11:09
-
-
Save joyrexus/5250531 to your computer and use it in GitHub Desktop.
Cartesian product.
This file contains 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
{test, ok, arrayEq} = require 'testy' | |
Array::uniq = -> | |
U = {} | |
U[@[i]] = @[i] for i in [0...@length] | |
v for k, v of U | |
flatten = (arr) -> arr.reduce ((x, y) -> x.concat y), [] | |
product = (sets...) -> | |
merge = (X, Y) -> flatten(x.concat y for y in Y.uniq() for x in X) | |
sets.reduce merge, [[]] | |
test 'flatten method', -> arrayEq [1, 2], flatten [1, [2]] | |
test 'product method', -> | |
result = product ['x', 'x', 'x'], ['a', 'b'] | |
arrayEq result, [['x', 'a'], ['x', 'b']] | |
result = product ['a', 'b'], ['x', 'x', 'x'] | |
arrayEq result, [['a', 'x'], ['b', 'x']] | |
result = product ['a', 'b'], ['c', 'd'], ['p', 'q'] | |
ok result.length is 8 | |
result = product [1..4], [1..4], [1, 2] | |
ok result.length is 32 | |
expected = [[ 1, 4, 5 ], | |
[ 1, 4, 6 ], | |
[ 2, 4, 5 ], | |
[ 2, 4, 6 ], | |
[ 3, 4, 5 ], | |
[ 3, 4, 6 ]] | |
arrayEq expected, product [1, 2, 3], [4], [5, 6] | |
test.status() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment