简体   繁体   English

如何用一维数组中的值填充二维数组?

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

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[][] .我认为在上面的解决方案中,除了看起来非常丑陋的解决方案之外,它只保存了bidimArray[][]singleArray的最后一个 position 。 May anyone help me, please?有人可以帮我吗?

There is no need for the third for loop here.这里不需要第三个for循环。 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.对代码的更改是为输入新二维数组的每个值简单地增加x并省略第三个 for 循环。

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.对于您的方法,您必须确保singleArray至少包含80*80元素。 If this is not given, you should make sure to check that constraint beforehand.如果没有给出,您应该确保事先检查该约束。

Circular populating of a 2d array 8x7 with values from a 1d array 6 .使用 1d 数组6中的值循环填充 2d 数组8x7 It works the same with larger and smaller arrays regardless of size:无论大小如何,它都适用于更大和更小的 arrays:

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另请参阅:将一维数组复制到二维数组

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

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