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. I couldn't understand how the prefix is works here (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
)?
Thanks
You could move total
into getCombinations
and return this value on exit.
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();