setMultiplicity.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { flatten } from '../../utils/array.js';
  2. import { factory } from '../../utils/factory.js';
  3. var name = 'setMultiplicity';
  4. var dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index'];
  5. export var createSetMultiplicity = /* #__PURE__ */factory(name, dependencies, _ref => {
  6. var {
  7. typed,
  8. size,
  9. subset,
  10. compareNatural,
  11. Index
  12. } = _ref;
  13. /**
  14. * Count the multiplicity of an element in a multiset.
  15. * A multi-dimension array will be converted to a single-dimension array before the operation.
  16. *
  17. * Syntax:
  18. *
  19. * math.setMultiplicity(element, set)
  20. *
  21. * Examples:
  22. *
  23. * math.setMultiplicity(1, [1, 2, 2, 4]) // returns 1
  24. * math.setMultiplicity(2, [1, 2, 2, 4]) // returns 2
  25. *
  26. * See also:
  27. *
  28. * setDistinct, setSize
  29. *
  30. * @param {number | BigNumber | Fraction | Complex} e An element in the multiset
  31. * @param {Array | Matrix} a A multiset
  32. * @return {number} The number of how many times the multiset contains the element
  33. */
  34. return typed(name, {
  35. 'number | BigNumber | Fraction | Complex, Array | Matrix': function numberBigNumberFractionComplexArrayMatrix(e, a) {
  36. if (subset(size(a), new Index(0)) === 0) {
  37. // if empty, return 0
  38. return 0;
  39. }
  40. var b = flatten(Array.isArray(a) ? a : a.toArray());
  41. var count = 0;
  42. for (var i = 0; i < b.length; i++) {
  43. if (compareNatural(b[i], e) === 0) {
  44. count++;
  45. }
  46. }
  47. return count;
  48. }
  49. });
  50. });