Peter
Peter Campbell Smith

Anyone for chess?

Weekly challenge 281 — 5 August 2024

Week 281: 5 Aug 2024

Task 1

Task — Check color

You are given coordinates, a string that represents the coordinates of a square of the chessboard as shown below: Write a script to return true if the square is light, and false if the square is dark.

empty chessboard

Examples


Example 1
Input: $coordinates = "d3"
Output: true

Example 2
Input: $coordinates = "g5"
Output: false

Example 3
Input: $coordinates = "e6"
Output: true

Analysis

I only recently realised that m|(x)(y)| as well as returninng x and y in $1 and $2 also returns them as a list if it's used in an array context. So I can easily split the supplied coordinates into column and row with:

my ($col, $row) = $_[0] =~ m|(.)(.)|;

If we then change the column names to 1-8 rather than a-h then it's easy to see that when the product of the row and column names of a square is odd then the square is dark, and conversely if it's even, the square is light.

We can do the letter-to-number change using

(ord($col) - ord('a')
but note this that results in values 0-7, so that now an odd product is light and even is dark. And the easy way to check for odd/even is simply a logical $n & 1.

Try it 

Try running the script with any input:



example: a1

Script


#!/usr/bin/perl

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

use v5.26;    # The Weekly Challenge - 2024-08-05
use utf8;     # Week 281 - task 1 - Check color
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

check_color('d3');
check_color('g5');
check_color('a1');
check_color('h8');

sub check_color {
    
    my ($col, $row) = $_[0] =~ m|(.)(.)|;
    
    # convert column letter to number (0-7), multiply by
    # row number and odd results are light, even ones dark  

    printf(qq[\nInput:  \$square = '%s'\n], $col . $row);
    printf(qq[Output: %s\n], ((ord($col) - ord('a')) * $row) & 1 ? 'true' : 'false');
}

Output


Input:  $square = 'd3'
Output: true

Input:  $square = 'g5'
Output: false

Input:  $square = 'a1'
Output: false

Input:  $square = 'h8'
Output: false

 

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