简体   繁体   English

从两个或多个不同长度的数组循环索引数组

[英]Indexing array by loop from two or more arrays with different length

Hy, i want to make a method that gives me one array from three different arrays with different length indexing like: Hy,我想制作一种方法,该方法从具有不同长度索引的三个不同数组中获取一个数组,例如:

[number of element in array][number of array] [数组元素个数][数组个数]

[0][0], [0][0],

[0][1], [0][1],

[0][2], [0][2],

[1][0], [1][0],

[1][2] [1][2]

So i made this:所以我做了这个:

    int a = 0;
    for (int i = 0; i < collections[a].length; i++) {
        for (int k = 0; k < collections.length; k++) {
            result[p] = collections[i][k];
            p++;
        }
    }

    return result;

but it only works when arrays are the same size and I have no idea what condition should be added to avoid "out of bounds" when it comes to from second element of the first array to second element of the third array excluding second element of the second array which does not even exist.但它仅在数组大小相同时才有效,并且我不知道应该添加什么条件以避免从第一个数组的第二个元素到第三个数组的第二个元素(不包括第二个元素)时“越界”第二个数组甚至不存在。

int[] array3 = { 10, 20, 30, };
int[] array4 = { 40, 50, };
int[] array5 = { 60, 70, 80, 90 };
A.method(array3, array4, array5);

and the result what i want to get is: 10,40,60,20,50,70,30,80,90我想要得到的结果是:10,40,60,20,50,70,30,80,90

First, I find which array has the max length.首先,我找到哪个数组具有最大长度。 Then I start two loops.然后我开始两个循环。 The "outer" loop index j is used to access the individual arrays' elements, which I increment only after I've cycled through all the individual arrays once. “外部”循环索引j用于访问单个数组的元素,只有在循环遍历所有单个数组一次后,我才会递增这些元素。 I stop incrementing j once j has reached the max length calculated in first step.一旦 j 达到第一步计算的最大长度,我就停止增加j

private static int[] combine(int[]... arrays) {

    int maxArrayLen = Arrays.stream(arrays).mapToInt(array -> array.length).max().getAsInt();

    List<Integer> list = new ArrayList<Integer>();
    for (int j = 0; j < maxArrayLen; j++) {
        for (int i = 0; i < arrays.length; i++) {
            if (arrays[i].length > j) {
                list.add(arrays[i][j]);
            }
        }
    }
    return list.stream().mapToInt(i -> i).toArray();
}

To invoke this: combine(array3, array4, array5);调用这个: combine(array3, array4, array5);

Running demo: https://ideone.com/F2yxKh运行演示: https : //ideone.com/F2yxKh

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM