JavaScript實現笛卡爾積
注意:本文中所說的集合是指數學上的集合,不是es6裡的Set。
整體思路如下:
實現代碼如下:
descates.js
/** * Created by Hawk on 2016/6/18. */ var DescartesUtils = { /** * 如果傳入的參數只有一個數組,求笛卡爾積結果 * @param arr1 一維數組 * @returns {Array} */ descartes1:function(arr1){ // 返回結果,是一個二維數組 var result = []; var i = 0; for (i = 0; i < arr1.length; i++) { var item1 = arr1[i]; result.push([item1]); } return result; }, /** * 如果傳入的參數只有兩個數組,求笛卡爾積結果 * @param arr1 一維數組 * @param arr2 一維數組 * @returns {Array} */ descartes2: function(arr1, arr2) { // 返回結果,是一個二維數組 var result = []; 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 二維數組 * @param arr1D 一維數組 * @returns {Array} */ descartes2DAnd1D: function(arr2D, arr1D) { var i = 0, j = 0; // 返回結果,是一個二維數組 var result = []; 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; // 返回結果,是一個二維數組 var result = []; // 為了便於觀察,采用這種順序 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; }, //笛卡兒積組合 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
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="descartes.js"></script> </head> <body> <div id="resultDiv"></div> <script type="text/javascript"> var arr1 = [1,2,3]; var arr2 = ["a", "b", "c", "d"]; var list = [arr1, arr2]; var list2 = [ [1,2,3], ["a", "b", "c"], ["A", "B"], ["啊","把","車","的"] ]; var result = DescartesUtils.descartes(list2); var html = ""; for (var i = 0; i < result.length; i++) { html = html + result[i].join(",") + "<br>"; } document.getElementById("resultDiv").innerHTML = html; </script> </body> </html>
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!