如何使用1d数组中的值填充2d数组? [英] How to populate a 2d array with values from a 1d array?

查看:57
本文介绍了如何使用1d数组中的值填充2d数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,其中填充了从其他方法接收到的一些值,并且我想用第一个示例中的值填充一个二维数组:

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];
        }
    }
}

我在上面的解决方案中认为,除了看起来非常丑陋的解决方案之外,它仅将 singleArray 的最后位置保存在 bidimArray [] [] 中.有人可以帮我吗?

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?

推荐答案

这里不需要第三个 for 循环.这是您出问题的地方.对代码的更改是,对于输入到新2D数组中的每个值,只需简单地增加 x ,并省略第三个for循环.

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++];

正如注释中指出的那样,您不应该对数组大小进行硬编码.对于您的方法,您必须确保 singleArray 至少包含 80 * 80 个元素.如果未指定,则应确保事先检查该约束.

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.

这篇关于如何使用1d数组中的值填充2d数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆