Chess Board

Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a “#” character. The characters should form a chess board.

Passing this string to console.log should show something like this:

 # # # #
# # # #
 # # # #
# # # #
 # # # #
# # # #
 # # # #
# # # #

When you have a program that generates this pattern, define a variable size = 8 and change the program so that it works for any size, outputting a grid of the given width and height.

Solution:

screen-shot-2016-11-17-at-3-36-41-pm

To know whether to put a space or a hash sign at a given position (or coordinate), check if the sum of x + y is even or odd.  (all the locations with space are even, and hash are odd).

Example:

location where (x, y) are (1, 1):

1 + 1 = 2 % 2 == 0 => true aka it’s even, you add a space there.

location at (2, 1):

2 + 1 = 3 % 2 == 0 => false aka it’s odd.  So you add a hash.

Advertisements
Chess Board

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s