Java Implementation outputs a digital matrix function example in clockwise or counterclockwise direction, java Matrix
This example describes how Java outputs a digital matrix in clockwise or counterclockwise directions. We will share this with you for your reference. The details are as follows:
Question:Based on the specified length width and output direction, print a Number Matrix starting from 1 in the outward direction. The starting position of the matrix is in the upper left corner. For example
The code and comments are as follows:
Public class NumberMatrix {public static void main (String [] args) {int width = 25; int height = 12; boolean clockwise = false; System. out. println ("helper house Test Result:"); outputMatrix (width, height, clockwise);}/*** according to the specified length width and output direction, print a matrix of numbers starting from 1 in the outward direction. The starting position of the matrix is in the upper left corner. ** @ Param width matrix width * @ param height matrix height * @ param clockwise: clockwise */private static void outputMatrix (int width, int height, boolean clockwise) {// first determine the maximum number of digits to determine how the output alignment int numLength = (int) Math. log10 (width * height) + 1; // determines the output format (maximum number of digits + 1 space) String format = "%" + (numLength + 1) + "d "; // define the two-dimensional array to be output, note that the dimension ranges from high to low. // The values of all elements in the matrix are 0 int [] [] matrix = new int [height] [width]. // define a location The needle and a counter move the position pointer, while the counter increments and increments the number // is filled into the matrix. When the width * height number is filled, this matrix is complete. // Note that the first element of the position pointer corresponds to the first dimension y of matrix, and the second element corresponds to the second dimension x. Int [] pointer = {0, 0}; int counter = 1; // defines the direction of the current movement: 1, 2, 3, and 4 indicate the top, right, bottom, and left, respectively. // The start direction of Clockwise is right, and the START direction of Clockwise is lower. Int direction = clockwise? 2: 3; // starts the cyclic filling. Each filling is divided into three steps for (int I = 1, max = width * height; I <= max; I ++) {// 1. fill in int y = pointer [0]; int x = pointer [1]; matrix [y] [x] = counter; // 2. counter auto-increment counter + = 1; // 3. move to the next location, because this location is complex, so open a method to implement direction = move (matrix, width, height, pointer, direction, clockwise);} // The matrix is filled, you can output the for (int y = 0; y
Running result: