-2

I am writing a betting calculator for the dutching strategy and cannot figure out how to get the sum of couples multiplied to each other:

var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var c = document.getElementById("c").value;

I would like to know in which way I can get the following a short way:

var total = (a * b) + (a * c) + (b * c)

If I just had a, b and c, this still would be manageable but I will have more than 10 values and I am sure there is a better way to do this with a short code regardless of the number of inputs I have. Otherwise, this will be unmanageable.

Thank you.

370147
  • 57
  • 5
  • 1
    desn't seems like permutation – xdeepakv May 17 '20 at 05:32
  • 1
    there is no inbuilt function, u can find code snippet in google – xdeepakv May 17 '20 at 05:33
  • @370147 the keyword you are looking for is not permutation but combination. It is the same as perm except perm considers a,b and b,a while combi only considers a,b (order does not matter). You have some js libs, [e.g](https://www.npmjs.com/package/js-combinatorics) but writing a function is trivial enough – grodzi May 17 '20 at 05:40
  • sorry yes, it is a combination, just picked a wrong word – 370147 May 17 '20 at 05:42

1 Answers1

1

lets say we have array of numbers we want to calc permutations: [a,b,c] Instead of (a * b) + (a * c) + (b * c), we can use a*(b+c) + b*c.

With larger array we will do the same: [a,b,c,d,e,f,g]. Instead of (a*b) + (a*c) + (a*d) + ... + (b*c) + (b*d) + ... we will do a*(b+c+d+..+g) + b*(c+d+..+g) +..).

And this is what we get:

function calc(arr) {
  let total = 0;
  for (let i = 0; i < arr.length; i++) {
    let sum = 0;
    for (let j = i + 1; j < arr.length; j++) {
      sum += arr[j];
    }
    total += sum * arr[i];
  }
  return total;
}
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 21];
console.log(calc(arr));
arr = [2, 4, 6];
console.log(calc(arr));
Omri Attiya
  • 3,917
  • 3
  • 19
  • 35