How to populate a 2d array with values from a 1d array?

社会主义新天地 提交于 2021-01-28 11:45:03

问题


I have a single array populated with some values that I receive from another method, and I want to populate a bidimensional array with values from the first, example:

int[] singleArray; // there's no values here to demonstrate,
                   // let's think that's populated

int[][] bidimArray = new int[80][80];

for (int i = 0; i < 80; i++) {
    for (int j = 0; j < 80; j++) {
        for (int x = 0; x < singleArray.length; x++) {
            bidimArray[i][j] = singleArray[x];
        }
    }
}

I thought in the solution above, besides it seems very ugly solution, it only saves the last position of singleArray in bidimArray[][]. May anyone help me, please?


回答1:


There is no need for the third for loop here. This is where you went wrong. The change to your code is to simply increment x for every value entered into the new 2D array and omitting the third for loop.

int[] singleArray;
int[][] bidimArray = new int[80][80];
int x = 0;

for (int i = 0; i < 80; i++) {
    for (int j = 0; j < 80; j++) {
        bidimArray[i][j] = singleArray[x];
        x++;
    }
}

You can also combine the two inner lines in the loop like this:

bidimArray[i][j] = singleArray[x++];

As pointed out in the comments, you should not hard code array sizes. For your approach, you will have to make sure that the singleArray contains at least 80*80 elements. If this is not given, you should make sure to check that constraint beforehand.




回答2:


Circular populating of a 2d array 8x7 with values from a 1d array 6. It works the same with larger and smaller arrays regardless of size:

int[] arr1 = {1, 2, 3, 4, 5, 6};

int m = 8;
int n = 7;
int[][] arr2 = IntStream.range(0, m)
        .mapToObj(i -> IntStream.range(0, n)
                .map(j -> arr1[(j + i * n) % arr1.length])
                .toArray())
        .toArray(int[][]::new);
// output
Arrays.stream(arr2).map(Arrays::toString).forEach(System.out::println);
[1, 2, 3, 4, 5, 6, 1]
[2, 3, 4, 5, 6, 1, 2]
[3, 4, 5, 6, 1, 2, 3]
[4, 5, 6, 1, 2, 3, 4]
[5, 6, 1, 2, 3, 4, 5]
[6, 1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 1]
[2, 3, 4, 5, 6, 1, 2]

See also: Copying a 1d array to a 2d array



来源:https://stackoverflow.com/questions/65627758/how-to-populate-a-2d-array-with-values-from-a-1d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!