遍历一维数组二维数组 [英] Iterating one dimension array as two dimension array

查看:212
本文介绍了遍历一维数组二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,

int[10] oneDim = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, index = 0;

所示<一href=\"http://stackoverflow.com/questions/664927/how-to-convert-a-unidimensional-array-to-a-bidimensional-array-java\">here,我们建立从源头上的二维之一。但我怎么重复我的 oneDim 的(指数= 0;指数小于10,指数++)让我能得到我的列索引行索引 创建一个新的?
我希望它看起来像这样在打印其索引到一个二维数组(2×5)

as shown here, we create the the two dimensional one from the origin. But how do I iterate my oneDim inside for (index = 0; index < 10; index++) so that I could get my column index and row index there without creating a new one? I want it looks like this while printing its indexes to a two dimensional array (2x5):

0,0
0,1
1,0
1,1
2,0
2,1
3,0
3,1
4,0
4,1

我觉得这里的主要问题是获得的列索引行索引,而无需创建二维之一。难道不是吗?

I think the main issue here is getting the column index and row index without creating the two dimensional one. Don't you?

推荐答案

如果你想行优先顺序排列,给定的行的rowIndex ,列参数:columnIndex ,并伪造(由于缺乏一个更好的词)一个二维数组 numberOfColumns 列,其公式为

If you want row-major order, given row rowIndex, column columnIndex and are faking (for lack of a better term) a two-dimensional array with numberOfColumns columns, the formula is

rowIndex * numberOfColumns + columnIndex.

如果你想行优先顺序排列,给定的行的rowIndex ,列参数:columnIndex ,并伪造(因缺乏一个更好的词)一个二维数组 numberOfRow 行,其公式为

If you want row-major order, given row rowIndex, column columnIndex and are faking (for lack of a better term) a two-dimensional array with numberOfRow rows, the formula is

columnIndex * numberOfRows + rowIndex.

因此​​,假设行优先顺序排列:

So, assuming row-major order:

int[10] oneDim = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int rows = 2;
int columns = 5;
for (int row = 0; row < rows; row++) {
    for (int column = 0; column < columns; column++) {
        System.out.println(row + ", " + column + ": " + oneDim[row * columns + column]);
    }
}

输出:

0, 0: 1
0, 1: 2
0, 2: 3
0, 3: 4
0, 4: 5
1, 0: 6
1, 1: 7
1, 2: 8
1, 3: 9
1, 4: 10

如果你的索引坚持使用单一循环,假设行主顺序,公式,你要的是以下内容:

And if you insist on indexing using a single for loop, assuming row-major order, the formula that you want is the following:

int column = index % numberOfColumns;
int row = (index - column) / numberOfColumns;

如果你使用列主顺序,您想要的公式如下:

If you're using column-major order, the formula that you want is the following:

int row = index % numberOfRows;
int column = (index - row) / numberOfRows;

因此​​,

int[10] oneDim = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int rows = 2;
int columns = 5;
for(int index = 0; index < 10; index++) {
    int column = index % columns;
    int row = (index - column) / columns;
    System.out.println(row + ", " + column + ": " + oneDim[index]);
}

将输出

0, 0: 1
0, 1: 2
0, 2: 3
0, 3: 4
0, 4: 5
1, 0: 6
1, 1: 7
1, 2: 8
1, 3: 9
1, 4: 10

如预期。

这篇关于遍历一维数组二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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