For loop matrix index

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
g1

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;

Now if we look at the other 3 grids

The first is flipped horizontally so use
c1 = gs - c - 1; r1 = r; v = 1 + c1 + r1 * gs;

the second is flipped vertically so use
c1 = c; r1 = gs - r - 1; v = 1 + c1 + r1 * gs;

and the final one flipped in both directions so use
c1 = gs - c - 1; r1 = gs - r - 1; v = 1 + c1 + r1 * gs;

So use a double loop like this replacing the ??? depending on which grid you are using.

  for (int r = 0; r < grid_size; r++) {
    int r1 = ?????;
    for (int c = 0; c < grid_size; c++) {
      int c1 =?????;
      int v = 1 + c1 + r1 * grid_size;
      float x = (c + 0.5) * itemSize;
      float y = (r + 0.5) * itemSize;
      fill(-1);
      square(x, y, itemSize * 0.8);
      fill(0);
      textSize(40);
      text(v, x, y);
    }
  }

I have tested this and it works fine.

2 Likes