you will write a Java program that generates an n × n matrix filled with elements from 1 to n 2 in spiral order, where n is a given input size.
In this assignment, you will write a Java program that generates an n × n matrix filled with elements from 1 to n 2 in spiral order, where n is a given input size. A spiral matrix is a matrix of the type which puts numbers in a circular fashion rather than in row-major or column-major fashion. The elements stored in the spiral matrix can be in clockwise (See Figure 1), or in counter clockwise (See Figure 2). Figure 1: A clockwise values Figure 2: A counter-clockwise values You may name your Java file name as MatrixApp.java, and write two methods that generate two versions of spiral matrices given any input matrix size n, and print out secondary diagonal values (See Figures 3-4 red-colored values). The detailed descriptions of two methods are as follows: 1 Figure 3: A clockwise spiral matrix with red-colored values should be printed /* * @n: input matrix size * * print out the secondary diagonal values from top to down * e.g., for n = 6, you will print 6, 24, 34, 36, 30, 16 */ public static void clockwise_spiralmatrix_diagonals(int n)) { // The Big Picture: // 1) create a matrix (mat) with n by n // 2) now fill the elements as follows, starting with cell mat[0][0]: // a) move right, fill up the first row // b) move down, fill up the last column // c) move left, fill up the last row // d) move up, fill up the first column // 3) repeat the process but moving insider cells now, // until all elements have been filled // Question: how do you know you complete this process? // Answer: all n x n numbers have been used // now you can print out the secondary diagonal values } 2 Figure 4: A counter clockwise spiral matrix with red-colored values should be printed /* * @n: input matrix size * * print out the secondary diagonal values from top to down * e.g., for n = 6, you will print 16, 30, 36, 34, 24, 6 */ public static void clockwise_spiralmatrix_diagonals(int n)) { // The Big Picture: // 1) create a matrix (mat) with n by n // 2) now fill the elements as follows, starting with cell mat[0][0]: // a) move down, fill up the first column // b) move right, fill up the last row // c) move up, fill up the last column // d) move left, fill up the first row // 3) repeat the process but moving insider cells now, // until all elements have been filled // Question: how do you know you complete this process? // Answer: all n x n numbers have been used // now you can print out the secondary diagonal values } 3 In your main() method, you will test two methods for input matrix sizes of 6, 7, 8, 9, and 10. Your outputs should labeled clearly like the followings. clockwise (n=6): 6, 24, 34, 36, 30, 16 counterclockwise (n=6): 16, 30, 36, 34, 24, 6 ...
Trending now
This is a popular solution!
Step by step
Solved in 3 steps with 2 images