Skip to content

Instantly share code, notes, and snippets.

@yutingzhao1991
Last active August 29, 2015 14:08
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 yutingzhao1991/a5cafbeb89636d9f3dcc to your computer and use it in GitHub Desktop.
Save yutingzhao1991/a5cafbeb89636d9f3dcc to your computer and use it in GitHub Desktop.
Cartesian product 笛卡尔积 with Javascript
var test = [[1,2],[3,4,5],[7,8]]
var result = []
var count = 1
for (var i = 0 ; i < test.length ; i ++) {
count *= test[i].length
}
for (var i = 0 ; i < count ; i ++) {
result.push([])
}
var loopLength = count
for (var i = 0 ; i < test.length ; i ++) {
var loopUnit = loopLength / test[i].length
for (var j = 0 ; j < count ; j ++) {
var sit = parseInt(j / loopUnit) % test[i].length
result[j].push(test[i][sit])
}
loopLength = loopUnit
}
console.log(result)
var test = [[1,2],[3,4,5],[7,8]]
function generate(position, pre) {
if (position >= test.length) {
console.log(pre.join(','))
return
}
for (var i = 0 ; i < test[position].length ; i ++) {
generate(position + 1, pre.concat([test[position][i]]))
}
}
generate(0, [])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment