Last active
August 29, 2015 14:08
-
-
Save yutingzhao1991/a5cafbeb89636d9f3dcc to your computer and use it in GitHub Desktop.
Cartesian product 笛卡尔积 with Javascript
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
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) |
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
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