问题1
12345678 取三位数组成一个新数组,可重复,求所有组合
function foo(str, sNum, result, ret) {
if (typeof ret === 'undefined') {
ret = [];
}
if (typeof result === 'undefined') {
result = [];
} else {
if (result.length == sNum) {
ret.push(result.concat());
return false;
}
}
var i = 0;
for (; i < str.length; i++) {
result.push(str[i]);
foo(str, sNum, result, ret);
result.pop();
}
return ret;
}
var ret = foo('12345678', 3);
console.log(ret);
[[1,2,3],[4],[5,6],[7,8,9,0]] n个第二维数组中取1位数组成一个新数组,求所有组合
var wocao = [[1,2,3],[4],[5,6],[7,8,9,0]]
function nima(wocao,aaa,bbb,result){
if(!aaa){aaa=0}
if(!bbb){bbb=[]}
if(!result){result=[]}
if(bbb.length==wocao.length){
result.push(bbb.slice(0))
return false
}
for(var i=0;i<wocao[aaa].length;i++){
bbb.push(wocao[aaa][i])
aaa++;
nima(wocao,aaa,bbb,result)
bbb.pop();
aaa--;
}
return result
}
console.log(nima(wocao))
优化版
var data = [[1, 2, 3], [4], [5, 6], [7, 8, 9, 0]]
var foo = (function() {
var index = 0
var tmp = []
var result = []
return function (data) {
if (tmp.length == data.length) {
result.push(tmp.slice(0))
return false
}
for (var i = 0; i < data[index].length; i++) {
tmp.push(data[index][i])
index++;
foo(data)
tmp.pop();
index--;
}
// aa++
return result
}
})()
console.log(foo(data))