Program to print the chess board pattern in javascript

An algorithm to print the chess board pattern in javascript.

We will be writing a program to print the chess board pattern. '#' will represent the black box and ' ' white space will represent the white box on the chessboard.

Example

Input:
8 8

Output:
 # # # #
# # # #
 # # # #
# # # #
 # # # #
# # # #
 # # # #
# # # #

Implementation

The chess board can be of any dimension so we will have to create a dynamic function.

  • We will create a function that will accept the rows and columns of the chess board as an input and print the the pattern.
  • We will use nested loops to print the pattern, In each row we will check if the current iteration is odd then will start the pattern with ' ' else we will start with '#'.
  • In the inner loop we will check if the current pattern is '#' then swap it with ' ' and vice versa.
  • Join the pattern together and print them after the end of the inner loop.
  • Repeat this for each row.
let chessboard = (row, column) => {
  
  for(let i = 0; i < row; i++){
    //If odd then start with ' '
    //Else start with '#'
    let start = i % 2 === 1 ? ' ' : '#';
    
    //Temp str to stor the pattern of the column
    let str = '';
    for(let j = 0; j < column; j++){
      //Swap current pattern with another one in each iteration
      start = start == '#' ? ' ' : '#';
      str += start;
    }
    
    //Print the pattern for the current row
    console.log(str);
  }
}
Input:
chessboard(3, 5);
chessboard(8, 8);

Output:
" # # "
"# # #"
" # # "

" # # # #"
"# # # # "
" # # # #"
"# # # # "
" # # # #"
"# # # # "
" # # # #"
"# # # # "

Time complexity: O(m * n).
Space complexity: O(1).

Time and Space complexity

  • We are print the pattern for each row and all columns, so Time complexity is O(m * n) where m is the no of rows and n is the no of columns.
  • We are using constant space, so Space complexity is O(1).