Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package demo;
- public class HelloJava {
- public static void main(String[] args) {
- int N = 4;
- int[][] arr = new int[N][N];
- int counter = 1;
- // Columns matrix
- for(int col = 0; col < arr.length; col++){
- for(int row = 0; row < arr[col].length; row++){
- arr[row][col] = counter;
- counter++;
- }
- }
- printMatrix(arr);
- System.out.println();
- // Alternating columns matrix
- counter = 1;
- for(int col = 0; col < arr.length; col++){
- if(col % 2 == 0){
- for(int row = 0; row < arr[col].length; row++){
- arr[row][col] = counter;
- counter++;
- }
- }else{
- for(int row = arr[col].length - 1; row >= 0; row--){
- arr[row][col] = counter;
- counter++;
- }
- }
- }
- printMatrix(arr);
- System.out.println();
- // Diagonal matrix
- counter = 1;
- int row = N - 1;
- int col = 0;
- while(counter <= (N * N)){
- arr[row][col] = counter;
- counter++;
- if(row == N - 1 && col != N - 1){
- row = N - 2 - col;
- col = 0;
- }else if(col == N - 1){
- col = col - row + 1;
- row = 0;
- }else{
- row++;
- col++;
- }
- }
- printMatrix(arr);
- System.out.println();
- for(int i = 0; i < arr.length; i++){
- for(int j = 0; j < arr[i].length; j++){
- arr[i][j] = 0;
- }
- }
- // Spiral matrix
- counter = 1;
- row = 0;
- col = 0;
- String direction = "down";
- while(counter <= (N * N)){
- arr[row][col] = counter;
- counter++;
- if(direction == "down"){
- row++;
- if(arr[row][col] != 0){
- direction = "right";
- row--;
- col++;
- }else if(row == (N - 1)){
- direction = "right";
- }
- }else if(direction == "right"){
- col++;
- if(arr[row][col] != 0){
- direction = "up";
- col--;
- row--;
- }else if(col == (N - 1)){
- direction = "up";
- }
- }else if(direction == "up"){
- row--;
- if(arr[row][col] != 0){
- direction = "left";
- row++;
- col--;
- }else if(row == 0){
- direction = "left";
- }
- }else if(direction == "left"){
- col--;
- if(col == (N - 1)){
- direction = "down";
- }else if(arr[row][col] != 0){
- direction = "down";
- col++;
- row++;
- }
- }
- }
- printMatrix(arr);
- System.out.println();
- }
- public static void printMatrix(int[][] arr){
- int spaces = Integer.toString(arr.length * arr.length).length();
- for(int i = 0; i < arr.length; i++){
- for(int j = 0; j < arr[i].length; j++){
- System.out.print(padSpace(arr[i][j], spaces));
- System.out.print((j != arr[i].length - 1) ? " " : "");
- }
- System.out.println();
- }
- }
- public static String padSpace(int num, int spaces){
- String result = String.valueOf(num);
- int difference = spaces - result.length();
- if(difference > 0){
- for(int i = 0; i < difference; i++){
- result = " " + result;
- }
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement