Developing an algorithm for tiling a floor with alternating black and white tiles

Hello:

I have this problem:

To tile a floor with alternating black and white tiles, develop an algorithm that yields the color (0 for black and 1 for white), given the row and column number. And an image shows a checked square of 4 tiles by 4 tiles by four tiles starting with black in the first corner on the left. So black, white, black, white for the first row. And starting with white in the second row, second tile there is black, etc.

So I wrote:

row odd, col odd = 0
row odd, col even = 1
col even, row odd = 1
col even row even = 0

But the book I’m using gives a different answer:

Clearly, the answer depends only on whether the row and column numbers are even or odd, so lets first take the remainder after dividing by 2. Then we can enumerate all expected answers.

Row % 2 Column % 2 Color
0 0 0
0 1 1
1 0 1
1 1 0

In the first three entries of the table, the color is simply the sum of the remainders. In the fourth entry, the sum would be 2, but we want a 0. We can achieve that by taking another remainder operation:

color = ((row % 2) + (column % 2)) % 2

Thanks in advance for your comments.

These two are the same. You shouldn’t have switched places for col and row :wink:

For the rest, your logic and the book’s logic seem the same? What exactly is your question?

1 Like

This sounds deceptively like a homework assignment.

How I personally would do it…you’re basically dealing with odds and evens here - color 1 goes to odd, color 2 goes to even. So I’d add the column and row together and divide that by two. The color that’s used depends on if there’s a remainder or not.

1 Like

luckily, no assignments at this point in my life! This is from the book Python for Everyone, that’s excellent because it teaches you to design algorithms to solve problems, not just the grammar of the programming language.

Surprised it’s not in there then. So, basically, you’ll need something like this. Note: I do NOT do python so had to look up the syntax, so there’s a 99% chance of a typo, but the idea is there…

print '#000000' if (col1 + col2) % 2 == 0 else '#ffffff'

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.