Matt23

Combinations with(out) repetitions

Nov 14th, 2015
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function binomial(n, k, e) {
  2.     /**
  3.     **If e is even calculating for combinations with repetitions - (n+k-1)! / (k! * (n-1)!)
  4.     **Else for combinations without repetitions - n! / (k! * (n-k)!)
  5.     ***/
  6.     var numerator = 1, denominator = 1;
  7.     if (k > n - k && e % 2 === 1) k = n - k; //possible reducing k if looking for combinations without repetitions
  8.     for (var i = 0; i < k; i++) {
  9.         numerator *= n + i * Math.pow(-1, e);
  10.         denominator *= k - i;
  11.     }
  12.  
  13.     return formatting(numerator / denominator);
  14. }
  15.  
  16. function formatting(string) {
  17.     return string.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  18. }
  19.  
  20. console.log(binomial(10, 8, 1));
  21. console.log(binomial(10, 8, 2));
Advertisement
Add Comment
Please, Sign In to add comment