更新时间:2023-02-10 15:35:04
您猜这就是您要找的吗?
guess this is what you're after?
function cartesian_product(xs, ys) {
var result = [];
for(var i = 0; i < xs.length; i++) {
for (var j = 0; j < ys.length; j++) {
// transform [ [1, 2], 3 ] => [ 1, 2, 3 ] and append it to result []
result.push([].concat.apply([], [ xs[i], ys[j] ]));
}
}
return result;
}
function cartesian_power(xs, n) {
var result = xs;
for(var i = 1; i < n; i++) {
result = cartesian_product(result, xs)
}
return result;
}
// in your case params are [ 1, 2... 30] and 7
console.log(cartesian_power([1, 2, 3, 4], 2));
输出为:
[ [ 1, 1 ],
[ 1, 2 ],
[ 1, 3 ],
[ 1, 4 ],
[ 2, 1 ],
[ 2, 2 ],
[ 2, 3 ],
[ 2, 4 ],
[ 3, 1 ],
[ 3, 2 ],
[ 3, 3 ],
[ 3, 4 ],
[ 4, 1 ],
[ 4, 2 ],
[ 4, 3 ],
[ 4, 4 ] ]
更新
这将需要更少的内存,因为它不会存储任何内容,只会打印输出.但仍然怀疑它是否实用.
this one will require much less memory, since it will not store anything, it will just print the output. but still doubt it's practical.
function print_combs(arr, n, out) {
if (n === 0) {
console.log(out);
} else {
for(var i = 0; i < arr.length; i++) {
print_combs(arr, n-1, out+arr[i]);
}
}
}
print_combs([1, 2, 3, 4], 2, "");