views:

80

answers:

2

Hello SO community!

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
+2  A: 

You're looking for the / operator:

box[0] = rowInArray / 3;
box[1] = columnInArray / 3;
TreDubZedd
add a `min` to that and you'll be fine (it's not going to be in box 3.6666 x 2.3333).
eykanal
@TreDubZedd: I'm not sure if you understood my question correctly. (0/3 = 0 = 0 |1/3 = 0.33 = 0 | 3/3 = 1 = 1 | 4/3 = 1.33 = 1)
Justian Meyer
If they're ints, then 2 / 3 == 0. If it's a float or double, you'll have the expected problem.
TreDubZedd
@TreDubZedd: Wait. Wait. Wait. I think I see what you're saying. Hold on... Wow. It's far too late here. I skipped 2. Yes. You're right. I *really* overcomplicated this. Many thanks.
Justian Meyer
I'm really gonna regret asking this question in the morning. This is such a beginning programming concept. I blame the jet-lag :P
Justian Meyer
A: 

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.

kFYatek