The problem seems to me that you are using the index i to determine both the value to display and the position to display it. Since you want to change the order the numbers are displayed there is no simple formulae linking the value to position, you need a more elaborate algorithm.
If we number the rows and columns in the initial state we have
The display position of any cell is determined using c and r.
To calculate the value to be displayed I will introduce 2 new variables c1 and r1 as it will simplify the problem later. I also introduce a new variable gs which is the grid square size, in this example, 4
So in the initial state we calculate the value to be stored with c1 = c; r1 = r; v = 1 + c1 + r1 * gs;
Amazing! Thank you very much, I can come up with an answer along your lines, but understanding it is still a bit difficult for me, I will study and learn it carefully.
Your reply helped me a lot and I wish you all the best
In Java strings should not be compared with the == operator, instead you should use the equals() method so str == "ld"
becomes str.equals("id")
I will leave you to google it for an explanation.
Apart from that congratulations on a nice implementation.
Just to avoid any possible confusion to others, you might wish to edit the two comments just preceding drawGrid(…): ‘lb’ and ‘rb’ should be ‘ld’ and ‘rd’ respectively. Your code is correct (apart from the use of == for string comparison mentioned by @quark )
I would not recommend the use of a switch statement inside the inner loop although it does make sense to keep the string comparisons outside the loop. The drawGrid method below shows how to do this elegantly and efficiently.
// lt -> left top
// rt -> right top
// ld -> left down
// rd -> right down
// Any other value will be treaed as lt
void drawGrid(String str) {
int r1 = 0;
int c1 = 0;
boolean flipY = str.equals("ld") || str.equals("rd");
boolean flipX = str.equals("rt") || str.equals("rd");
for (int r = 0; r < total; r++) {
r1 = flipY ? total - r - 1 : r;
for (int c = 0; c < total; c++) {
c1 = flipX ? total-c-1 : c;
int v = 1 + c1 + r1 * total;
float x = (c + 0.5) * itemSize;
float y = (r + 0.5) * itemSize;
fill(-1);
square(x, y, itemSize * 0.8);
fill(0);
text(v, x, y);
}
}
}
Note I use the ternary operator statements inside the loop like this