simple-squiggle

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

setCartesian.js (2282B)


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