Full Disclosure: Homework.
Explanation: I cant understand my teacher.
Problem:
Write a method called
printSquare
that takes in two integer
parameters, amin
and amax
, and prints the numbers in the range from
min
tomax
inclusive in a square pattern. The square pattern is
easier to understand by example than by explanation, so take a look at
the sample method calls and their resulting console output in the
table below. Each line of the square consists of a circular sequence
of increasing integers betweenmin
andmax
. Each line prints a
different permutation of this sequence. The first line begins with
min, the second line begins withmin + 1
, and so on. When the
sequence in any line reachesmax
, it wraps around back tomin
. You
may assume the caller of the method will pass amin
and amax
parameter such thatmin
is less than or equal tomax
I cannot for the life of me figure out how to make the numbers stop at the 'max' value and start over in the middle of the line.
This is what I have so far, apologies but I have trouble with for loops.
for(int i = 0; i < row; i++)
{
for(int d = 0; d < row; d++)
{
System.out.print(d+1);
}
System.out.println(i);
}
I know I used row twice, but its the only way i can get the compiler to form a square shape with the loop. Does anyone even remotely understand what i'm trying to do? :/
Best Answer
This is actually a nice mathematical problem. Assume:
the value at any point in the square (row, col) is:
you should be able to put that in your loops and "smoke it".
Edit based on comment asking for explanation.
The trick is to loop through all the positions in the 'matrix'. Given that the matrix is square, the loops are relatively simple, just two loops (nested) that traverse the system:
Now, in this loop, we have the variables
row
andcol
which represent the cell in the matrix we are interested in. The value in that cell needs to be proportional to the distance it is from the origin..... let me explain.... If the origin is the top left (which it is), then the distances from the origin are:The distance is the sum of the row and the column...... (rows and columns start counting from 0).
The values we put in each matrix are limited to a fixed range. For the above example, with a square of size 5, it could have been specified as
printSquare(1,5)
.The value in each cell is the from value (1 in this example) plus the distance from the origin... naively, this would look like:
here the values in the cell have exceeded the limit of 5, and we need to wrap them around... so, the trick is to 'wrap' the distances from the origin..... and the 'modulo' operator is great for that. First, consider the original 'origin distance' matrix:
if we instead populate this matrix with 'the remainder of the distance when dividing by 5' (the modulo 5, or %5) we get the matrix:
Now, if we add this 'modulo' result to the from value (1), we get our final matrix:
in a sense, all you need to know is that the value at each cell is:
Here's the code I tested with: