combinations.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { factory } from '../../utils/factory.js';
  2. import { combinationsNumber } from '../../plain/number/combinations.js';
  3. var name = 'combinations';
  4. var dependencies = ['typed'];
  5. export var createCombinations = /* #__PURE__ */factory(name, dependencies, _ref => {
  6. var {
  7. typed
  8. } = _ref;
  9. /**
  10. * Compute the number of ways of picking `k` unordered outcomes from `n`
  11. * possibilities.
  12. *
  13. * Combinations only takes integer arguments.
  14. * The following condition must be enforced: k <= n.
  15. *
  16. * Syntax:
  17. *
  18. * math.combinations(n, k)
  19. *
  20. * Examples:
  21. *
  22. * math.combinations(7, 5) // returns 21
  23. *
  24. * See also:
  25. *
  26. * combinationsWithRep, permutations, factorial
  27. *
  28. * @param {number | BigNumber} n Total number of objects in the set
  29. * @param {number | BigNumber} k Number of objects in the subset
  30. * @return {number | BigNumber} Number of possible combinations.
  31. */
  32. return typed(name, {
  33. 'number, number': combinationsNumber,
  34. 'BigNumber, BigNumber': function BigNumberBigNumber(n, k) {
  35. var BigNumber = n.constructor;
  36. var result, i;
  37. var nMinusk = n.minus(k);
  38. var one = new BigNumber(1);
  39. if (!isPositiveInteger(n) || !isPositiveInteger(k)) {
  40. throw new TypeError('Positive integer value expected in function combinations');
  41. }
  42. if (k.gt(n)) {
  43. throw new TypeError('k must be less than n in function combinations');
  44. }
  45. result = one;
  46. if (k.lt(nMinusk)) {
  47. for (i = one; i.lte(nMinusk); i = i.plus(one)) {
  48. result = result.times(k.plus(i)).dividedBy(i);
  49. }
  50. } else {
  51. for (i = one; i.lte(k); i = i.plus(one)) {
  52. result = result.times(nMinusk.plus(i)).dividedBy(i);
  53. }
  54. }
  55. return result;
  56. }
  57. // TODO: implement support for collection in combinations
  58. });
  59. });
  60. /**
  61. * Test whether BigNumber n is a positive integer
  62. * @param {BigNumber} n
  63. * @returns {boolean} isPositiveInteger
  64. */
  65. function isPositiveInteger(n) {
  66. return n.isInteger() && n.gte(0);
  67. }