simple-squiggle

A restricted subset of Squiggle
Log | Files | Refs | README

setCartesian.js (1990B)


      1 import { flatten } from '../../utils/array.js';
      2 import { factory } from '../../utils/factory.js';
      3 var name = 'setCartesian';
      4 var dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix'];
      5 export var createSetCartesian = /* #__PURE__ */factory(name, dependencies, _ref => {
      6   var {
      7     typed,
      8     size,
      9     subset,
     10     compareNatural,
     11     Index,
     12     DenseMatrix
     13   } = _ref;
     14 
     15   /**
     16    * Create the cartesian product of two (multi)sets.
     17    * Multi-dimension arrays will be converted to single-dimension arrays
     18    * and the values will be sorted in ascending order before the operation.
     19    *
     20    * Syntax:
     21    *
     22    *    math.setCartesian(set1, set2)
     23    *
     24    * Examples:
     25    *
     26    *    math.setCartesian([1, 2], [3, 4])        // returns [[1, 3], [1, 4], [2, 3], [2, 4]]
     27    *    math.setCartesian([4, 3], [2, 1])        // returns [[3, 1], [3, 2], [4, 1], [4, 2]]
     28    *
     29    * See also:
     30    *
     31    *    setUnion, setIntersect, setDifference, setPowerset
     32    *
     33    * @param {Array | Matrix}    a1  A (multi)set
     34    * @param {Array | Matrix}    a2  A (multi)set
     35    * @return {Array | Matrix}    The cartesian product of two (multi)sets
     36    */
     37   return typed(name, {
     38     'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) {
     39       var result = [];
     40 
     41       if (subset(size(a1), new Index(0)) !== 0 && subset(size(a2), new Index(0)) !== 0) {
     42         // if any of them is empty, return empty
     43         var b1 = flatten(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural);
     44         var b2 = flatten(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural);
     45         result = [];
     46 
     47         for (var i = 0; i < b1.length; i++) {
     48           for (var j = 0; j < b2.length; j++) {
     49             result.push([b1[i], b2[j]]);
     50           }
     51         }
     52       } // return an array, if both inputs were arrays
     53 
     54 
     55       if (Array.isArray(a1) && Array.isArray(a2)) {
     56         return result;
     57       } // return a matrix otherwise
     58 
     59 
     60       return new DenseMatrix(result);
     61     }
     62   });
     63 });