Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Last active December 15, 2015 11:09
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 joyrexus/5250531 to your computer and use it in GitHub Desktop.
Save joyrexus/5250531 to your computer and use it in GitHub Desktop.
Cartesian product.
{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