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

2 Comments

  1. Sports Betting - Mapyro
    Bet the poormansguidetocasinogambling moneyline from 메이피로출장마사지 1:25 https://deccasino.com/review/merit-casino/ PM to 11:00 PM. See more. MapYO Sportsbook features https://tricktactoe.com/ live odds, live streaming, and detailed information. https://vannienailor4166blog.blogspot.com/

    ReplyDelete
  2. your blog\article is very nice informations vist

    CCNA Online Training

    ReplyDelete
Previous Post Next Post