Reputation: 644
I have a matrix of 3x3 which looks like
1 2 3
4 5 6
7 8 9
Behind each number is an object. So I wrote this code which will return which position in the matrix I'm currently at. But it feels very repetitive, Im curious if it would be possible to optimize that piece of code. If so, how?
public int findPos(int i, int k) {
if (i == 0 && k == 0) {
return 1;
}
if (i == 0 && k == 1) {
return 2;
}
if (i == 0 && k == 2) {
return 3;
}
if (i == 1 && k == 0) {
return 4;
}
if (i == 1 && k == 1) {
return 5;
}
if (i == 1 && k == 2) {
return 6;
}
if (i == 2 && k == 0) {
return 7;
}
if (i == 2 && k == 1) {
return 8;
}
if (i == 2 && k == 2) {
return 9;
}
return 0;
}
The method is later applied in this type of fashion
if (myMatrix[i][k] == 2) {
position = findPos(i, k);
drawAtPos(position);
}
Upvotes: 0
Views: 54
Reputation: 40669
What's the matter with this?
(i*3 + k) + 1
Why does it work? Well, subtract 1 from your matrix, so it looks like this:
0 1 2
3 4 5
6 7 8
so it should be obvious.
Upvotes: 1
Reputation: 7057
Can you just covert it to:
public int findPos(int i, int k) {
if (0 <= i && i < COLUMN_COUNT && 0 <= k && k < row_COUNT){ // out of bounds
return 0;
}
return (i * 3) + (k + 1);
}
All this is doing is reducing your conditions into math as each column returns an offset of 1 each position to the right, and each row needs to be incremented by 3.
For a more generic solution, it would be:
public int findPos(int i, int k) {
if (0 <= i && i < COLUMN_COUNT && 0 <= k && k < row_COUNT){ // out of bounds
return 0;
}
return (i * COLUMN_COUNT) + (k + 1);
}
where COLUMN_COUNT is the number of columns you have. So it would work for things like:
1 2 3 4 5 6
7 8 9 10 11 12
where COLUMN_COUNT = 6
Upvotes: 1
Reputation: 11
You can calculate your position with:
if (0 <= i && i < 3 &&
0 <= k && k < 3) {
// number of rows passed * size of each row + current column + 1 for 0-to-1-based-conversion
return (i * 3) + (k + 1);
} else {
return 0;
}
Upvotes: 1