Reputation: 4101
A grid of size 3 should look like:
# #
#
# #
A grid of size 4 should look like:
# #
# #
# #
# #
A grid of size 5 should look like:
# # #
# #
# # #
# #
# # #
etc.
Usually, to create a "normal" grid, I'd do something like:
function makeGrid (input) {
let grid = "";
for (let i = 0; i < input; i++) {
grid += "#".repeat(input) + "\n";
}
return grid;
}
console.log(makeGrid(3));
But in this case, I'm having trouble making sure that the rows are created with the correct starting element - either #
or
.
My attempt:
function makeSpecialGrid (input) {
let specialGrid = "";
for (let i = 0; i < input; i++) {
let row = "";
for (let j = 0; j < i; j++) {
if (j % 2 === 0) {
row += "#";
}
row += " ";
}
specialGrid += row;
}
return specialGrid;
}
console.log(makeSpecialGrid(3));
Which, of course, only creates one row.
Any other ideas?
Upvotes: 0
Views: 41
Reputation: 4101
Here is another way:
function gridGenerator (size) {
let grid = "";
// i is the lines
for (let i = 0; i < size; i++) {
// j is the characters
for (let j = 0; j < size; j++) {
if ((i + j) % 2 === 0) {
grid += '#';
} else {
grid += ' ';
}
}
grid += '\n';
}
return grid;
}
Upvotes: 0
Reputation: 6981
Try this:
function grid(n) {
let result = "";
for (let i = 0; i < n; i++) {
if (i % 2 == 0)
result += " #".repeat(Math.ceil(n / 2)).slice(1);
else
result += " #".repeat(Math.floor(n / 2)) + " ";
result += "\n";
}
return result;
}
console.log(grid(5));
console.log(grid(3));
console.log(grid(11));
Upvotes: 1