这是一个想法:
var a = [4, 5, 6];
for (var m = 0; m < a[0]; m++)
for (var n = 0; n < a[1]; n++)
for (var p = 0; p < a[2]; p++)
console.log(`${m} + ${n} + ${p} = ${m+n+p}`);
实时复制:
// This just tells the Stack Snippets in-snippet console not
// to throw away entries once it reaches a max (the default max
// is just the last 50 logs).
console.config({maxEntries: Infinity});
var a = [4, 5, 6];
for (var m = 0; m < a[0]; m++)
for (var n = 0; n < a[1]; n++)
for (var p = 0; p < a[2]; p++)
console.log(`${m} + ${n} + ${p} = ${m+n+p}`);
/* This just makes the console take up the full output area */
.as-console-wrapper {
max-height: 100% !important;
}
如果数组 a 有更多索引,代码会变长。可以使用 Array.map 或过滤器或函数来缩短代码吗?
另一种不消耗大量内存且相当有效的解决方案是使用一个表示索引值的数组并在每次迭代时更新它。首先,您创建一个数组,在每个元素中表示您需要运行的迭代次数,以便分别更新索引,例如对于[1, 2, 3 ,4 ,5]
您将获得的此数组:[280, 140, 20, 5, 1]
这意味着 index[0] 将每 280 次迭代更新一次,index[ 1] 将每 140 次迭代更新一次,依此类推.. 完全你将像你一样运行 arr[n] * arr[n-1] * arr[n-2] * .... * arr[0] 迭代普通的嵌套 for 循环。
var arr = [1, 2, 7, 4, 5];
var indexes = Array.from({length: arr.length}, () => 0);
iterationsPerElement = arr.map((_, i) => arr.slice(i+1).reduce((acc, elem) => acc * elem, 1));
var totalIterations = iterationsPerElement[0] * arr[0];
for(var iteration = 1; iteration <= totalIterations; iteration++) {
// sum those indexes
console.log(`sum = ${indexes.reduce((acc, index) => acc + index, 0)}`);
// update indexes
for(i = 0; i < indexes.length; i++) {
if(iteration % iterationsPerElement[i] == 0) {
indexes[i]++;
// empty the indexes on the right
for(var j=i+1; j <indexes.length; j++) {
indexes[j] = 0;
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句