JavaScript implements Cartesian product
Note: The set mentioned in this article refers to a mathematical set, not a set in ES6.
The whole idea is as follows:
- The user passes in a two-dimensional array, each of which is a set of Cartesian product computations. Returns a two-dimensional array, each of which is an ordered pair or N-ary ordered group.
- When the user passes in a collection, in order to be compatible with the business, the return form is as follows: [[A],[b] ...] Two-dimensional array.
- When a user passes in only two sets of calculations, the normal nesting calculation can be done.
- When a user passes in 3 or more than 3 sets, the result of the last two sets is computed, followed by the previous set.
The implementation code is as follows:
Descates.js
/** * Created by Hawk on 2016/6/18. * * var descartesutils = {/** * If the incoming parameter has only one array, the Cartesian product result * @param arr1 one-dimensional array * @returns {array} * * Descartes1
: function (ARR1) {//return result, is a two-dimensional array of var results = [];
var i = 0;
for (i = 0; i < arr1.length i++) {var item1 = arr1[i];
Result.push ([item1]);
return result; /** * If the incoming parameter has only two arrays, Cartesian product result * @param arr1 one-dimensional array * @param arr2 one-dimensional array * @returns {array} * * Descartes2:
function (arr1, ARR2) {//return result, is a two-dimensional array of var results = [];
var i = 0, j = 0;
for (i = 0; i < arr1.length i++) {var item1 = arr1[i];
for (j = 0; J < Arr2.length; J + +) {var item2 = arr2[j];
Result.push ([Item1, item2]);
} return result; },/** * * @param arr2d two-dimensional array * @param arr1d one-dimensional array * @returns {array} * * Descartes2dand1d:function (ARR2
D, arr1d) {var i = 0, j = 0;
Returns the result, which is a two-dimensional array of var results = []; for (i = 0; i< Arr2d.length;
i++) {var arrof2d = arr2d[i];
for (j = 0; J < Arr1d.length; J + +) {var item1d = arr1d[j];
Result.push (Arrof2d.concat (item1d));
} return result;
}, Descartes3:function (list) {var listlength = list.length;
var i = 0, j = 0;
Returns the result, which is a two-dimensional array of var results = [];
In order to facilitate observation, the use of this sequence of var arr2d = Descartesutils.descartes2 (List[0], list[1]);
for (i = 2; i < listlength i++) {var arroflist = list[i];
arr2d = descartesutils.descartes2dand1d (arr2d, arroflist);
return arr2d;
},//Cartesian product combination descartes:function (list) {if (!list) {return [];
} if (list.length <= 0) {return [];
} if (list.length = = 1) {return descartesutils.descartes1 (list[0]);
} if (list.length = = 2) {return Descartesutils.descartes2 (list[0], list[1]);
} if (List.length >= 3) {return descartesutils.descartes3 (list);
}
}
};
Descartes.html
Thank you for reading, I hope to help you, thank you for your support for this site!