gpt4 book ai didi

arrays - 多数组的笛卡尔积

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:04:14 26 4
gpt4 key购买 nike

我认为这基本上是一个简单的问题,但我被卡住了。脑子被这个问题给堵住了,希望大家能帮帮我。我有 2 到 N 个整数数组,比如

{1,2,3,4,5}
{1,2,3,4,5,6}
{1,3,5}
.....

现在我想要一个包含 int[N] 数组的列表,每个可能性都像

{1,1,1}
{1,1,3}
{1,1,5}
{1,2,1}
....
{1,3,1}
....
{2,1,1}
{2,1,3}
....
{5,6,5}

所以里面有6*5*3(90)个元素。

有没有简单的算法可以做到?我认为语言并不重要,但我更喜欢 Java。

最佳答案

谢谢你的帮助!我为下一个有同样问题的人添加了一个有效的 Java 实现答案。我也做它是通用的,所以你可以在任何对象上使用任何 CartesianProduct,而不仅仅是整数:

public class Product {

@SuppressWarnings("unchecked")
public static <T> List<T[]> getCartesianProduct(T[]... objects){
List<T[]> ret = null;
if (objects != null){
//saves length from first dimension. its the size of T[] of the returned list
int len = objects.length;
//saves all lengthes from second dimension
int[] lenghtes = new int[len];
// arrayIndex
int array = 0;
// saves the sum of returned T[]'s
int lenSum = 1;
for (T[] t: objects){
lenSum *= t.length;
lenghtes[array++] = t.length;
}
//initalize the List with the correct lenght to avoid internal array-copies
ret = new ArrayList<T[]>(lenSum);
//reusable class for instatiation of T[]
Class<T> clazz = (Class<T>) objects[0][0].getClass();
T[] tArray;
//values stores arrayIndexes to get correct values from objects
int[] values = new int[len];

for (int i = 0; i < lenSum; i++){
tArray = (T[])Array.newInstance(clazz, len);
for (int j = 0; j < len; j++){
tArray[j] = objects[j][values[j]];
}
ret.add(tArray);
//value counting:
//increment first value
values[0]++;
for (int v = 0; v < len; v++){
//check if values[v] doesn't exceed array length
if (values[v] == lenghtes[v]){
//set it to null and increment the next one, if not the last
values[v] = 0;
if (v+1 < len){
values[v+1]++;
}
}
}

}
}
return ret;
}
}

关于arrays - 多数组的笛卡尔积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7945555/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com