Create a matrix with alternating rectangles of O and X | Function to print alternating rectangles of 0 and X ; k - starting row index m - ending row index l - starting column index n - ending column index i - iterator ; Store given number of rows and columns for later use ; A 2D array to store the output to be printed ; Iniitialize the character to be stoed in a [ ] [ ] ; Fill characters in a [ ] [ ] in spiral form . Every iteration fills one rectangle of either Xs or Os ; Fill the first row from the remaining rows ; Fill the last column from the remaining columns ; Fill the last row from the remaining rows ; Print the first column from the remaining columns ; Flip character for next iteration ; Print the filled matrix ; Driver Code
function fill0X ( m , n ) { let i , k = 0 , l = 0 ; let r = m , c = n ; let a = new Array ( m ) ; for ( let i = 0 ; i < m ; i ++ ) { a [ i ] = new Array ( n ) ; } let x = ' ' ; while ( k < m && l < n ) { for ( i = l ; i < n ; ++ i ) { a [ k ] [ i ] = x ; } k ++ ; for ( i = k ; i < m ; ++ i ) { a [ i ] [ n - 1 ] = x ; } n -- ; if ( k < m ) { for ( i = n - 1 ; i >= l ; -- i ) a [ m - 1 ] [ i ] = x ; m -- ; } if ( l < n ) { for ( i = m - 1 ; i >= k ; -- i ) { a [ i ] [ l ] = x ; } l ++ ; } x = ( x == ' ' ) ? ' ' : ' ' ; } for ( i = 0 ; i < r ; i ++ ) { for ( let j = 0 ; j < c ; j ++ ) { document . write ( a [ i ] [ j ] + " " ) ; } document . write ( " " ) ; } } document . write ( " " ) ; fill0X ( 5 , 6 ) ; document . write ( " " ) ; fill0X ( 4 , 4 ) ; document . write ( " " ) ; fill0X ( 3 , 4 ) ;