Create a matrix with alternating rectangles of O and X .

Problem :  User will inputs two numbers m and n and creates a matrix of size m x n (m rows and n columns) in which every elements is either X or 0.
         

                
Solution :  Here outermost layer having X then O then again inner one is X and so on,It reminds me to apply  similar concept which is discussed here(Spiral movement of matrix) .
Instead of printing the elements we will fill matrix with X or O and after each iteration we will change next character to be considered from X to O and vice versa.
 Sample code in java which will display our pattern as needed.

 import java.util.Scanner;  
 public class MatrixPatternXandO {  
   public MatrixPatternXandO() {  
     super();  
   }  
   public static void generatePatternXandOMatrix(int m, int n) {  
     int r = m, c = n;  
     int col = 0, row = 0;  
     int i;  
     char ch = 'X';  
     // A 2D array to store the output to be printed  
      char mat[][] = new char[m][n];  
     while (row < m && col < n) {  
       for (i = col; i < n; i++) {  
         mat[row][i] = ch;  
       }  
       row++;  
       for (i = row; i < m; i++) {  
         mat[i][n - 1] = ch;  
       }  
       n--;  
       if (row < m) {  
         for (i = n - 1; i >= col; i--) {  
           mat[m - 1][i] = ch;  
         }  
         m--;  
       }  
       if (col < n) {  
         for (i = m - 1; i >= row; i--) {  
           mat[i][col] = ch;  
         }  
         col++;  
       }  
       ch = (ch == 'X') ? 'O' : 'X';  
     }  
     for (int j = 0; j < r; j++) {  
       for (int k = 0; k < c; k++) {  
         System.out.print(mat[j][k] + " ");  
       }  
       System.out.println();  
     }  
   }  
   public static void main(String[] args) {  
     MatrixPatternXandO matrixPatternXandO = new MatrixPatternXandO();  
     Scanner scanner = new Scanner(System.in);  
     System.out.println("Enter number of row for pattern :");  
     int row = scanner.nextInt();  
     System.out.println("Enter number of row for pattern :");  
     int column = scanner.nextInt();  
     matrixPatternXandO.generatePatternXandOMatrix(row, column);  
   }  
 }  
Sample output :
Enter number of row for pattern : 5
Enter number of row for pattern : 5

X X X X X
X O O O X
X O X O X
X O O O X
X X X X X

1 Comments

Previous Post Next Post