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