Yunielf Yunielf - 3 years ago 90
Javascript Question

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!

Answer Source

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));

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download