setDistinct.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { flatten } from '../../utils/array.js';
  2. import { factory } from '../../utils/factory.js';
  3. var name = 'setDistinct';
  4. var dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix'];
  5. export var createSetDistinct = /* #__PURE__ */factory(name, dependencies, _ref => {
  6. var {
  7. typed,
  8. size,
  9. subset,
  10. compareNatural,
  11. Index,
  12. DenseMatrix
  13. } = _ref;
  14. /**
  15. * Collect the distinct elements of a multiset.
  16. * A multi-dimension array will be converted to a single-dimension array before the operation.
  17. *
  18. * Syntax:
  19. *
  20. * math.setDistinct(set)
  21. *
  22. * Examples:
  23. *
  24. * math.setDistinct([1, 1, 1, 2, 2, 3]) // returns [1, 2, 3]
  25. *
  26. * See also:
  27. *
  28. * setMultiplicity
  29. *
  30. * @param {Array | Matrix} a A multiset
  31. * @return {Array | Matrix} A set containing the distinc elements of the multiset
  32. */
  33. return typed(name, {
  34. 'Array | Matrix': function ArrayMatrix(a) {
  35. var result;
  36. if (subset(size(a), new Index(0)) === 0) {
  37. // if empty, return empty
  38. result = [];
  39. } else {
  40. var b = flatten(Array.isArray(a) ? a : a.toArray()).sort(compareNatural);
  41. result = [];
  42. result.push(b[0]);
  43. for (var i = 1; i < b.length; i++) {
  44. if (compareNatural(b[i], b[i - 1]) !== 0) {
  45. result.push(b[i]);
  46. }
  47. }
  48. }
  49. // return an array, if the input was an array
  50. if (Array.isArray(a)) {
  51. return result;
  52. }
  53. // return a matrix otherwise
  54. return new DenseMatrix(result);
  55. }
  56. });
  57. });