求多个队列、数组的笛卡尔集
说明
在开发一个商城产品的时候,遇到一个需要求笛卡尔集的需求,查询相关资料解决问题后,记录下关键算法,以备查询
Js版本
示例
var array =[];
var a1=["红色","蓝色","绿色"];
var a2=["方形","圆形","三角形"];
var a3=["大","中","小"];
array.push(a1);
array.push(a2);
array.push(a3);
//笛卡尔乘积算法
function descartes(array){
let count = 1;
array.forEach(item => count *= item.length);
let lstResult = [];
for (let i = 0; i < count; ++i) {
let lstTemp = [];
let j = 1;
array.forEach(item =>
{
j *= item.length;
lstTemp.push(item[parseInt(i / parseInt(count / j)) % item.length]);
});
lstResult.push(lstTemp);
}
return lstResult;
};
var result = descartes(array);
console.info(result);
运行结果
Java版本
示例
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* description
*
* @author: YH
* @create: 2020-08-21 16:55
**/
public class DescartesUtil {
/**
* 笛卡尔乘积算法
*
* @param lstSplit
* @return
*/
public static<T> List<List<T>> descartes(List<List<T>> lstSplit) {
int count = 1;
for (List<T> item : lstSplit) {
count *= item.size();
}
List<List<T>> lstResult = new ArrayList<List<T>>();
for (int i = 0; i < count; ++i) {
List lstTemp = new ArrayList<T>();
int j = 1;
for (List<T> item : lstSplit) {
j *= item.size();
int index = (i / (count / j)) % item.size();
lstTemp.add(item.get(index));
}
lstResult.add(lstTemp);
}
return lstResult;
}
public static void main(String[] args) {
List<List<String>> list = new ArrayList<>();
List<String> a1=Arrays.asList("红色","蓝色","绿色");
List<String> a2=Arrays.asList("方形","圆形","三角形");
List<String> a3=Arrays.asList("大","中","小");
list.add(a1);
list.add(a2);
list.add(a3);
List<List<String>> result = descartes(list);
result.forEach(System.out::println);
}
}