-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.

4
  • 1
    desn't seems like permutation Commented May 17, 2020 at 5:32
  • 1
    there is no inbuilt function, u can find code snippet in google Commented May 17, 2020 at 5: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 but writing a function is trivial enough Commented May 17, 2020 at 5:40
  • sorry yes, it is a combination, just picked a wrong word Commented May 17, 2020 at 5:42

1 Answer 1

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));

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.