Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a JavaScript grid with odd and even characters using two loops

This is my first question on StackOverflow.

I have to build gridGenerator(num). If num is 3, it would look like this:

#_#
_#_
#_#

If num is 4, it would look like this:

#_#_
_#_#
#_#_
_#_#

I was able to solve it for odd numbers, but struggle to adjust it to even numbers.

function gridGenerator(num) {
  var grid = '';
  var row = '';

  for (var i = 0; i < num; i++) {
    for (var j = 0; j < num; j++) {

      if (row.length % 2) {
        row += '_';
      } else {
        row += '#';
      }
    }
    grid += row.slice(-num) + '\n';
  }
  return grid;
}

console.log(gridGenerator(3));

Need a hint how to solve it for 2, 4, and other even numbers. Thank you!

like image 983
Yunielf Avatar asked Jul 26 '17 01:07

Yunielf


1 Answers

Try this if ((i+j) % 2)

function gridGenerator(num) {
  var grid = '';
  var row = '';

  for (var i = 0; i < num; i++) {
    for (var j = 0; j < num; j++) {
      if ((i+j) % 2) {
        row += '_';
      } else {
        row += '#';
      }
    }
    grid += row.slice(-num) + '\n';
  }
  return grid;
}

console.log(gridGenerator(4));
like image 187
Sourabh Somani Avatar answered Oct 19 '22 09:10

Sourabh Somani