This is actually a good math problem. Suppose:
int side = to - from + 1;
the value at any point in the square (row, col) is:
from + ((row + col) % side)
you should be able to put this in your loops and "smoke."
Modify based on comment requesting explanation.
The trick is to iterate over all the positions in the “matrix”. Given that the matrix is square, the loops are relatively simple, there are only two loops (nested) that intersect the system:
final int side = to - from + 1; for (int row = 0; row < side; row++) { for(int col = 0; col < side; col++) { ... magic goes here.... } }
Now in this loop we have the row and col variables that represent the cell in the matrix of interest to us. The value in this cell should be proportional to the distance from the origin ..... let me explain .... If the origin is the upper left (that is), then the distances from the origin:
0 1 2 3 4 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8
The distance is the sum of the row and column ...... (rows and columns start at 0).
The values that we put in each matrix are limited to a fixed range. In the above example with a square of size 5, it could be specified as printSquare(1,5) .
The value in each cell is equal to the value (1 in this example) plus the distance from the beginning ... naively, it would look like this:
1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9
here the values in the cell exceeded the limit of 5, and we need to wrap them ... so the trick is to "wrap" the distance from the origin ..... and "modulo", the operator is great for this. First, consider the original distance matrix:
0 1 2 3 4 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8
if instead we fill this matrix with "the rest of the distance when dividing by 5" (modulo 5 or% 5), we get the matrix:
0 1 2 3 4 1 2 3 4 0 2 3 4 0 1 3 4 0 1 2 4 0 1 2 3
Now, if we add this 'modulo' result to the value from (1), we get our final matrix:
1 2 3 4 5 2 3 4 5 1 3 4 5 1 2 4 5 1 2 3 5 1 2 3 4
in a sense, all you need to know is what the value in each cell is:
the from value plus the remainder when you divide the 'distance' by the width.
Here is the code I tested:
public static final String buildSquare(final int from, final int to) { final StringBuilder sb = new StringBuilder(side * side); final int side = to - from + 1; for (int row = 0; row < side; row++) { for(int col = 0; col < side; col++) { sb.append( from + ((row + col) % side) ); } sb.append("\n"); } return sb.toString(); } public static void main(String[] args) { System.out.println(buildSquare(1, 5)); System.out.println(buildSquare(3, 9)); System.out.println(buildSquare(5, 5)); System.out.println(buildSquare(0, 9)); System.out.println(buildSquare(0, 3)); }