setPowerset.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { flatten } from '../../utils/array.js';
  2. import { factory } from '../../utils/factory.js';
  3. var name = 'setPowerset';
  4. var dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index'];
  5. export var createSetPowerset = /* #__PURE__ */factory(name, dependencies, _ref => {
  6. var {
  7. typed,
  8. size,
  9. subset,
  10. compareNatural,
  11. Index
  12. } = _ref;
  13. /**
  14. * Create the powerset of a (multi)set. (The powerset contains very possible subsets of a (multi)set.)
  15. * A multi-dimension array will be converted to a single-dimension array before the operation.
  16. *
  17. * Syntax:
  18. *
  19. * math.setPowerset(set)
  20. *
  21. * Examples:
  22. *
  23. * math.setPowerset([1, 2, 3]) // returns [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
  24. *
  25. * See also:
  26. *
  27. * setCartesian
  28. *
  29. * @param {Array | Matrix} a A (multi)set
  30. * @return {Array} The powerset of the (multi)set
  31. */
  32. return typed(name, {
  33. 'Array | Matrix': function ArrayMatrix(a) {
  34. if (subset(size(a), new Index(0)) === 0) {
  35. // if empty, return empty
  36. return [];
  37. }
  38. var b = flatten(Array.isArray(a) ? a : a.toArray()).sort(compareNatural);
  39. var result = [];
  40. var number = 0;
  41. while (number.toString(2).length <= b.length) {
  42. result.push(_subset(b, number.toString(2).split('').reverse()));
  43. number++;
  44. }
  45. // can not return a matrix, because of the different size of the subarrays
  46. return _sort(result);
  47. }
  48. });
  49. // create subset
  50. function _subset(array, bitarray) {
  51. var result = [];
  52. for (var i = 0; i < bitarray.length; i++) {
  53. if (bitarray[i] === '1') {
  54. result.push(array[i]);
  55. }
  56. }
  57. return result;
  58. }
  59. // sort subsests by length
  60. function _sort(array) {
  61. var temp = [];
  62. for (var i = array.length - 1; i > 0; i--) {
  63. for (var j = 0; j < i; j++) {
  64. if (array[j].length > array[j + 1].length) {
  65. temp = array[j];
  66. array[j] = array[j + 1];
  67. array[j + 1] = temp;
  68. }
  69. }
  70. }
  71. return array;
  72. }
  73. });