1

我正在尝试采用 9x9、12x12、15x15 等数组,并让程序将它们解释为多个 3x3 正方形。

例如:

0 0 1 0 0 0 0 0 0
0 0 0 0 0 2 0 0 0
0 0 0 0 0 0 0 3 0
0 0 0 0 0 0 6 0 0
0 0 4 0 0 0 0 0 0
0 0 0 0 0 5 0 0 0
0 0 0 0 0 0 0 0 0
0 7 0 0 0 0 0 0 0
0 0 0 0 8 0 0 0 9

会被理解为:

0 0 1 | 0 0 0 | 0 0 0
0 0 0 | 0 0 2 | 0 0 0
0 0 0 | 0 0 0 | 0 3 0
------+-------+------
0 0 0 | 0 0 0 | 6 0 0
0 0 4 | 0 0 0 | 0 0 0
0 0 0 | 0 0 5 | 0 0 0
------+-------+------
0 0 0 | 0 0 0 | 0 0 0
0 7 0 | 0 0 0 | 0 0 0
0 0 0 | 0 8 0 | 0 0 9

在哪里:

"1" @ [0][2] is in box "[0][0]"
"2" @ [1][5] is in box "[0][1]"
...
"6" @ [3][6] is in box "[1][2]"
...
"9" @ [8][8] is in box "[2][2]"

.

我可以使用row % 3andcolumn % 3来确定框中的行和列值,但是如何确定数组中的给定值存储在哪个框中?

该公式可用于如下方法。

public int[] determineCoordinatesOfBox(int rowInArray, int columnColumnInArray) {
    // determine row value
    // determine column value

    // return new int[2] with coordinates
}

这似乎是可能的,我一直在努力解决这个问题。也许我让一个简单的问题变得太难了?

非常感谢您的帮助!

  • 贾斯蒂安
4

2 回答 2

2

您正在寻找/运营商:

box[0] = rowInArray / 3;
box[1] = columnInArray / 3;
于 2010-07-27T21:14:02.487 回答
0

如果我理解正确,这只是简单的整数除法。

由于您正在编写 Java(至少在 C、C++ 和 C# 中是相同的),因此它只是/运算符:

int rowInArray = 3;
int columnInArray = 7;

int boxY = rowInArray / 3;    // will evaluate to 1
int boxX = columnInArray / 3; // will evaluate to 2

int rowInBox = rowInArray % 3;       // will evaluate to 0
int columnInBox = columnInArray % 3; // will evaluate to 1

只需保留除法整数的两个参数 - 7 / 3is 2, but 7 / 3.0or 7.0 / 3will be 2.5

于 2010-07-27T21:19:58.507 回答