[英]unary operator prefix execution in recursion is not working as expected
I am trying to count number of combinations in given range and length of combinations.我正在尝试计算给定范围和组合长度内的组合数。 Here is following code.这是以下代码。
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();
the console log for total
variable always print 0. but following code works as expected with little change in for
loop code. total
变量的控制台日志始终打印 0。但以下代码按预期工作, for
循环代码几乎没有变化。 I couldn't understand how the prefix is works here (somex = somex + fn()).我无法理解前缀是如何在这里工作的(somex = somex + fn())。 Can someone please help here?有人可以在这里帮忙吗?
// 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();
My question is, I don't understand, why solution 1 (top one) is not working as expected (printing total
as 0
rather than 56
)?我的问题是,我不明白,为什么解决方案 1(顶部)没有按预期工作(打印total
为0
而不是56
)?
Thanks谢谢
You could move total
into getCombinations
and return this value on exit.您可以将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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.