Peter’s blog ✴ Week 376 ✴ 1 June 2026

THE WEEKLY CHALLENGE
Squares and pairs

The Perl Camel

Task 1

Chessboard squares

You are given two pairs of coordinates of a square on an 8x8 chessboard. Write a script to find whether the given two squares are the same colour.

empty chessboard

Examples


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

Analysis

If the coordinates of a square are ($x, $y) then the colour is black if $x + $y is even or white if it is odd. We are give $x as a lower case letter, but ord('a') has the same parity (even or odd) as $x so ord('a') + $y obeys the same rule as $x + $y.

The sum of two numbers with the same parity is even, and that of two different parities is odd, so if we add them and logically 'and' the sum with 1, we get 0 for 'the same' and 0 for 'different'.

That could easily be done in a single line of code, but I think it is easier to follow the logic if it's split out as I have done.

Try it 

Your input:



eg: a3, e7

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2026-06-01
use utf8;     # Week 376 - task 1 - Chessboard squares
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

chessboard_squares('a7', 'f4'); # true
chessboard_squares('c1', 'e8'); # false
chessboard_squares('b5', 'h2'); # false
chessboard_squares('f3', 'h1'); # true
chessboard_squares('a1', 'g8'); # false
chessboard_squares('a8', 'h1'); # true
chessboard_squares('a1', 'h8'); # true

sub chessboard_squares {
    
    my ($c1, $c2, $a1, $a2);
    
    # initialise
    ($c1, $c2) = @_;
    
    # if row + col is even then black (0), else white (1)
    $a1 = ord(substr($c1, 0, 1)) + substr($c1, 1, 1);
    $a2 = ord(substr($c2, 0, 1)) + substr($c2, 1, 1);

    # if $a1 + $a2 is even then colours are different else the same
    say qq[\nInput:  \$c1 = '$c1', \$c2 = '$c2'];
    say qq[Output: ] . ((($a1 + $a2) & 1) ? 'false' : 'true');
}


7 lines of code
Completed after the closing date and not submitted to GitHub

Output from script


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

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

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

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

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

Input:  $c1 = 'a8', $c2 = 'h1'
Output: true

Input:  $c1 = 'a1', $c2 = 'h8'
Output: true

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain