Creating a squared loop with java

Full disclosure: homework.

Explanation: I cannot understand my teacher.

Problem:

Write a method called printSquare that takes two integer parameters, a min and a max , and prints numbers in the range from min to max inclusive squared. A square drawing is easier to understand with an example than an explanation, so take a look at the method method call and their final output in the console table below. Each row of the square consists of a circular sequence of increasing integers between min and max . Each line prints a different permutation of this sequence. The first line starts with min, the second line starts with min + 1 , etc. When a sequence on any line reaches max , it wraps back to min . You can assume that the calling method will pass min and a max such that min less than or equal to max

enter image description here

I can’t understand for my whole life how to make numbers stop at the “max” value and start from the middle of the line.

This is what I still apologize for, but I have problems with 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 that I used a string twice, but this is the only way to get the compiler to square with a loop. Does anyone even remotely understand what I'm trying to do?: /

+6
source share
7 answers

This is actually a good math problem. Suppose:

 int side = to - from + 1; /// the size/width of the square. 

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)); } 
+10
source

Since this is homework, I’ll just give a hint.

I can’t understand for my whole life how to make numbers stop at the “max” value and start from the middle of the line.

Here is one way to do it.

  • Create the first number twice in the array. printSquare(1, 5) example, create an int array from 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.

  • Use a loop to loop through an array, starting from element zero and ending with element 4, and another loop to display 5 digits (max - min + 1).

+3
source

you can try

  • from the minimum value to the maximum value and put all numbers in an array
  • now the cycle repeats again from the minimum value to the maximum value

    print an array each time and do a circular shift (for a circular shift you can find many examples in SO)

0
source

try it

  int i,j,k; for(i=min;i<=max;i++) { for(j=i;j<=max;j++) { System.out.print(j); } for(k=min;k<i;k++){ System.out.print(k); } System.out.println(); } 
0
source

I think @rolfl's solution is the cleanest. I would recommend going with that.

You can find another simple solution by noting that each output in your square simply carries the first element to the end of the list of numbers. To emulate this, you can put all the numbers from min to max in a data structure, such as LinkedList or ArrayDeque , where you can easily add / remove elements from both ends, then you must print the contents in order and move the first record to the end. For example, coll.addLast(coll.removeFirst()) . If you repeat this process max - min + 1 times, you should get the desired result.

0
source

There is no array without problems, you can easily solve. It works with any range of numbers.

  static void printSquare(int min, int max){ int len = max - min + 1; int copy_min = min, permanent_min = min; for(int i = 0; i < len; i++){ for(int j = 0; j< len; j++){ if(min > max) if(min % len < permanent_min) System.out.print((min % len )+ len); else System.out.print(min % len); else System.out.print(min); min++; } min = ++copy_min; System.out.println(); } } 
0
source
  public static void printSquare(int min, int max)  {       for (int i = min; i <= (max -min)+min; i++)  {               for( int j =i; j <= max ; j++) {                           System.out.print(j);              }        for (int j1= min; j1<= i * 1 - 1; j1++) {            System.out.print(j1);            }        System.out.println();    }   } 
0
source

Source: https://habr.com/ru/post/957431/


All Articles