简体   繁体   中英

Java Print number square with revolving numbers using nested for loops

/*Here's the full question:
Write a method called printSquare that takes in two integer parameters, a min and a max, and prints the numbers in the range from min to max 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 between min and max. Each line prints a different permutation of this sequence. The first line begins with min, the second line begins with min + 1, and so on. When the sequence in any line reaches max, it wraps around back to min.

You may assume the caller of the method will pass a min and a max parameter such that min is less than or equal to max. */

Hi guys I've got this problem I can't solve. It's to call this method printSquare(1,5) ; to get this output:

12345

23451

34512

45123

51234

so far here's my code. I cant seem to get the front numbers to shift to the back.

public static void printSquare (int startNum, int height){

        if (startNum == height){
            System.out.print(height);
            return;
        }

        for (int i = startNum; i <= height; i++){
            int max = startNum;
            int j = i;
            for (j = i; j <= height; j++){
                System.out.print (j); 
            }

        System.out.println();
        }            
}

If your inner loop starts with i , it has to end with height + i , not just height for the output to be square, otherwise it will be a triangle. You want to learn about the modulo operator % to determine the remainder of a division in order to handle the "overflow".

The specification you gave is unclear about what should happen regarding the "overflow" if startNum != 1 .

Besides, the guard condition (startNum == height) is clearly wrong if height actually means height (and, because it says printSquare , the width ). I would expect printSquare(4, 4) to print four rows and columns, not just one row and one column. Something seems to be wrong with the naming. In general such guards are suspicious. The code of algorithms should be so generic that it doesn't need to handle such special cases separately.

Here's a possible implementation which works for the cases printSquare(1, 5); and printSquare(1, 1); . For other cases, your specification wasn't clear enough.

public class Main {
    public static void main(final String... args) {
        printSquare(1, 5);
        printSquare(1, 1);
        //printSquare(2, 6);
        //printSquare(4, 4);
    }

    public static void printSquare(int startNum, int height) {
        for (int i = startNum; i < startNum + height; i++) {
            for (int j = i; j < height + i; j++) {
                System.out.print((j - 1) % height + 1);
            }
            System.out.println();
        }
        System.out.println();
    }
}

If the end number is not determined by height alone but by startNum + height - 1 , a possible solution looks like this:

    public static void printSquare(int startNum, int height) {
        for (int i = startNum; i < startNum + height; i++) {
            for (int j = 0; j < height; j++) {
                System.out.print((j + i - startNum) % (height) + startNum);
            }
            System.out.println();
        }
        System.out.println();
    }

Providing an alternative java 8 solution using lambdas. It could be an overkill for a simple task

public static void printSquaresJava8(int x, int y) {
  int count = y - x + 1;
  IntStream sequence = (IntStream.rangeClosed(x, y).<Integer>flatMap(i -> IntStream.rangeClosed(i, i + y).limit(count).<Integer>map(j -> j > y ? j - count : j)));
  List<Integer> numbers = sequence.boxed().collect(Collectors.<Integer>toList());

  IntStream.<Integer>rangeClosed(0,count-1).forEach(i ->
                                           {numbers.subList(count * i, count + count*i).forEach(j -> System.out.print(j + " "));
                                             System.out.println();
                                           }
  );

}

//Written in c++. Call numberSquare(1, 5) Your first for-loop is your row, the second nested for-loop is your column(s). k starts at min value. the col for loop will print out k from min to max, in the first iteration it will print out 1 2 3 4 5 horizontally. once k is equal to max, reset it to min so that the outer loop. can print out the rows from 1 to 5. think if it like a 2D array or a grid.

 void numberSquare(int min, int max) {
    for(int i = min; i <= max; i++) {
        int k = i;
        for(int j = min; j <= max; j++) {
            cout << k;
            if (k == max) {
                k = min;
            } 
            else k = k+1;
        }
        cout << endl;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM