开发者

Arithmetic operation so that 0, 1, & 2 return 0 | 3, 4, & 5 return 1, etc

开发者 https://www.devze.com 2023-01-09 16:00 出处:网络
I\'m trying to take 9x9, 12x12, 15x15, etc. arrays and have the program interpret them as multiple 3x3 squares.

I'm trying to take 9x9, 12x12, 15x15, etc. arrays and have the program interpret them as multiple 3x3 squares.

For example:

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

Will be understood as:

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

Where:

"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]"

.

I can use row % 3 and column % 3 to determine the row and column values within the box, but how can I determine which box a given value in the array is stored in?

This formula could be used in a method such as the one below.

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

    // return new int[2] with coordinates
}

It seems possible and I've been beating my head over this. Perhaps I'm making a simple problem too difficult?

Many thanks for the help!

  • Justian


You're looking for the / operator:

box[0] = rowInArray / 3;
box[1] = columnInArray / 3;


If I understand correctly, it's just simple integer division.

Since you're coding Java (it would be the same in at least C, C++ and C#), it's simply / operator:

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

Just keep both the arguments of division integer - 7 / 3 is 2, but 7 / 3.0 or 7.0 / 3 will be 2.5.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号