Determine Color of a Chessboard Square
published
last modified
3kb
Today I solved another problem in both python and c++.
You are given coordinates, a string that represents the coordinates of a square of the chessboard.
Return true if the square is white, and false if the square is black.
The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second.
Inital Stab
This one wasn't very hard when you have a picture of a chessboard in front of you. You just had to determine the pattern in terms of whether the combination of letter and number are in even/odd positions.
I decided to try solve this one in c++. I wanted to use a vector to store all the numbers and then try find the position of the coordinate in the vector to determine if the letter was odd.
This simple task proved to cumbersone which was, in fact, a good thing because it led me to think of characters as integers (i.e their ascii representation).
Overcomplicating
I then just had a series of if/else statements to determine whether the position was black or white. It looked something ugly like this:
The Better Solution
After checking the other solutions it became obvious that I could just add both integers together and then simply check if they were odd/even. That's it.
The obvious fact here is that if you add an odd number to an odd number you get an even number, which in this case meant white chess board colour
The much more pretty python solution:
Another one in the books.
Contact
If you have any comments or thoughts you can reach me at any of the places below.