The Bear's Den

Enter at your own risk

Chess Solo

Task 1: Chessboard Squares

Submitted by: Mohammad Sajid Anwar


You are given two coordinates of a square on 8x8 chessboard.

Write a script to find the given two coordinates have the same colour.

8 W B W B W B W B
7 B W B W B W B W
6 W B W B W B W B
5 B W B W B W B W
4 W B W B W B W B
3 B W B W B W B W
2 W B W B W B W B
1 B W B W B W B W
  a b c d e f g h

Example 1

Input: $c1 = "a7", $c2 = "f4"
Output: true

Example 2

Input: $c1 = "c1", $c2 = "e8"
Output: false

Example 3

Input: $c1 = "b5", $c2 = "h2"
Output: false

Example 4

Input: $c1 = "f3", $c2 = "h1"
Output: true

Example 5

Input: $c1 = "a1", $c2 = "g8"
Output: false

Solution

The color of a square can be identified by the sum of its coordinates modulo 2. It does not matter if the coordinates are zero- or one-based as the modulo 2 operation annihilates any base. Furthermore, as we only need to know if two squares have the same color, the base for row and column coordinates may even be different. There is nothing wrong with the columns to start at index 97 and the rows at 49.

In summary it is sufficient to take the character codes for both rows and columns and check if their sum is even.

Perl

use strict;
use warnings;
use List::Util 'sum';

sub same_color {
    !(sum(map ord, map split(//), @_) % 2);
}

See the full solution to task 1.

J

Almost identical: find character indices for [x and] y, sum over all items, calculate modulo 2 and negate the result

same_color =: -. @ (2&|) @ (+/) @: , &: (a.&i.)
   'b5' same_color 'h2'
0
   'f3' same_color 'h1'
1

Used as a monad, the verb provides the color of a square:

   same_color 'a1'
1
   same_color 'a8'
0