Number of combinations in a given number array in javascript

155 views Asked by At
var ans = (49*48*47*46*45*44)/(6*5*4*3*2*1)

alert(ans.toLocaleString())

This will output 13,983,816 and it's the correct number of possible combinations from a number array of 1 to 49.

How do I implement this with numbers that I can get from 2 variables?

For example if I want to calculate the number of combinations possible for 5 numbers out of 40 I need to have (40*39*38*37*36)/(5*4*3*2*1) and I need this to be replaced like: 40*39*38*37*36 with var n and (5*4*3*2*1) with var t but output the correct order of numbers.

Just to be clear, I don't want to write these operations manually in the variables, I want the number specified in the variables to generate the operations based on their value. If I specify 6 selections I need to generate 6*5*4*3*2*1, if I specify 5 selections it needs to generate 5*4*3*2*1 and so on.

Thanks for the help!

3

There are 3 answers

0
Lucian On BEST ANSWER

Nevermind, I managed to figure it out after some good hours:

function getChance(numbers, out_of) {
    return numbers>0?out_of/numbers*getChance(numbers-1,out_of-1):1;   

}

var np = 6; //numbers picked
var tn = 49; //total numbers

var ntm = 6; //numbers to match

var picks = getChance(np-ntm, tn-ntm);
var combs = getChance(np, tn);

var probs = combs/picks;

document.getElementById('chance').innerHTML = (probs | 0).toLocaleString();
4
Walter Chapilliquen - wZVanG On

Updated, (with loops):

Number.prototype.to = function(to){
  var result = 1;
  while(this >= to) result *= to++;
  return result
};

var n = 49..to(44); //49*48*47*46*45*44
var t = 6..to(1); //6*5*4*3*2*1

document.writeln((n/t).toLocaleString())

0
Oriol On

You can try for loops:

function binom(a,b) {
  if(a < 2*b) b = a-b;
  var n = 1;
  for(var i=a-b+1; i<=a; ++i) n *= i;
  for(var i=2; i<=b; ++i) n /= i;
  return n;
}