题目
给出一个二维数组,得到所有想要结果的二维数组。
比如:
let arr = [
['red','yellow'],
['s','m']
];
希望得到的结果
[
['red','s'],
['red','m'],
['yellow','s'],
['yellow','m']
]
再比如:
let arr = [
['red','yellow'],
['s','m'],
['a','b','c']
];
希望得到的结果:
[
['red','s','a'],
['red','s','b'],
['red','s','c'],
['red','m','a'],
['red','m','b'],
['red','m','c'],
['yellow','s','a'],
['yellow','s','b'],
['yellow','s','c'],
['yellow','m','a'],
['yellow','m','b'],
['yellow','m','c'],
];
我的算法:
let arr =[
['红色','绿色','黄色','绿色'],
["大",'小','超大'],
['100m','150m']
];
function getResult(array){
let result = [[]];
for(let i=0;i<array.length;i++){
result=twoDimensional(result,array[i]);
}
return result;
}
function twoDimensional(a,b){
let result = [];
let copy;
for(let i=0;i<a.length;i++){
for(let j=0;j<b.length;j++){
copy=a[i].concat();
copy.push(b[j]);
result.push(copy);
}
}
return result;
}
getResult(arr);
结果:
[ [ '红色', '大', '100m' ],
[ '红色', '大', '150m' ],
[ '红色', '小', '100m' ],
[ '红色', '小', '150m' ],
[ '红色', '超大', '100m' ],
[ '红色', '超大', '150m' ],
[ '绿色', '大', '100m' ],
[ '绿色', '大', '150m' ],
[ '绿色', '小', '100m' ],
[ '绿色', '小', '150m' ],
[ '绿色', '超大', '100m' ],
[ '绿色', '超大', '150m' ],
[ '黄色', '大', '100m' ],
[ '黄色', '大', '150m' ],
[ '黄色', '小', '100m' ],
[ '黄色', '小', '150m' ],
[ '黄色', '超大', '100m' ],
[ '黄色', '超大', '150m' ],
[ '绿色', '大', '100m' ],
[ '绿色', '大', '150m' ],
[ '绿色', '小', '100m' ],
[ '绿色', '小', '150m' ],
[ '绿色', '超大', '100m' ],
[ '绿色', '超大', '150m' ] ]