我正在尝试计算给定组合范围和长度内的组合数量。下面是代码。
function generateCombination() {
const perm = [];
const permLength = 2;
const numberRange = 8;
let total = 0;
const getCombinations = (result, permLength, numberRange) => {
if (result.length === permLength) {
//console.log('result: ', result);
return 1;
}
for (var i = 0; i < numberRange; i++) {
if (result.indexOf(i) === -1) {
result.push(i);
total = total + getCombinations(result, permLength, numberRange);
result.pop();
}
}
return 0;
}
getCombinations(perm, permLength, numberRange);
console.log("total: ", total); // expected value "total: 56"
}
generateCombination();
CCD_ 1变量的控制台日志总是打印0。但下面的代码如预期的那样工作,CCD_ 2循环代码几乎没有变化。我不明白前缀在这里是如何工作的(somex=somex+fn(((。有人能帮忙吗?
// working solution
function generateCombination() {
const perm = [];
const permLength = 2;
const numberRange = 8;
let total = 0;
const getCombinations = (result, permLength, numberRange) => {
if (result.length === permLength) {
//console.log('result: ', result);
return 1;
}
for (var i = 0; i < numberRange; i++) {
if (result.indexOf(i) === -1) {
result.push(i);
if (getCombinations(result, permLength, numberRange)) {
total += 1;
}
result.pop();
}
}
return 0;
}
getCombinations(perm, permLength, numberRange);
console.log("total: ", total); // expected value is "total: 56" and working here
}
generateCombination();
我的问题是,我不明白,为什么解决方案1(顶部的解决方案(没有按预期工作(将total
打印为0
而不是56
(?
感谢
您可以将total
移动到getCombinations
中,并在退出时返回此值。
function generateCombination() {
const perm = [];
const permLength = 2;
const numberRange = 8;
const getCombinations = (result, permLength, numberRange) => {
if (result.length === permLength) return 1;
let total = 0;
for (let i = 0; i < numberRange; i++) {
if (result.indexOf(i) === -1) {
result.push(i);
total += getCombinations(result, permLength, numberRange);
result.pop();
}
}
return total;
}
console.log("total: ", getCombinations(perm, permLength, numberRange)); // expected value "total: 56"
}
generateCombination();