Perl Weekly Challenge 281: Check Color

These are some answers to the Week 281, Task 1, of the Perl Weekly Challenge organized by Mohammad S. Anwar.

Spoiler Alert: This weekly challenge deadline is due in a few days from now (on August 11, 2024, at 23:59). This blog post provides some solutions to this challenge. Please don’t read on if you intend to complete the challenge on your own.

Task 1: Check Color

You are given coordinates, a string that represents the coordinates of a square of the chessboard as shown below:

week_281_task_1.png

Write a script to return true if the square is light, and false if the square is dark.

Example 1

Input: $coordinates = "d3"
Output: true

Example 2

Input: $coordinates = "g5"
Output: false

Example 3

Input: $coordinates = "e6"
Output: true

Check Color in Raku

We could replace the abscissa letters with numbers from 1 to 8 (or 0 to 7), add the two values of the coordinates and check whether the sum is even or odd. But it is even simpler to assign 0 or 1 to a variable depending on whether the abscissa belong to the [aceg] or [bdfh] character class. We then add this variable to the ordinates and check whether the sum is even or odd.

sub check-color ($in) {
    my ($abscissa, $ordinate) = $in.comb;`
    my $code;
    given $abscissa {
        when /<[aceg]>/ {$code = 0}
        when /<[bdfh]>/ {$code = 1}
    }
    return True if ($code + $ordinate) %% 2;
    False;
}

for <a1 d3 g5 e6 h8> -> $coordinates { 
    printf "%-2s => ", $coordinates;
    say check-color $coordinates;
}

This program displays the following output:

$ raku ./check-color.raku
a1 => False
d3 => True
g5 => False
e6 => True
h8 => False

Check Color in Perl

This is a port to Perl of the above Raku program. Please refer to the previous section if you need explanations.

use strict;
use warnings;
use feature 'say';

sub check_color {
    my ($abscissa, $ordinate) = split //, shift;
    my $code = 1;
    $code = 0 if $abscissa =~ /[aceg]/;
    return "True" if ($code + $ordinate) % 2 == 0;
    return "False";
}

for my $coordinates (qw<a1 d3 g5 e6 h8>) { 
    printf "%-2s => ", $coordinates;
    say check_color $coordinates;
}

This program displays the following output:

$ perl ./check-color.pl
a1 => False
d3 => True
g5 => False
e6 => True
h8 => False

Wrapping up

The next week Perl Weekly Challenge will start soon. If you want to participate in this challenge, please check https://perlweeklychallenge.org/ and make sure you answer the challenge before 23:59 BST (British summer time) on August 18, 2024. And, please, also spread the word about the Perl Weekly Challenge if you can.

Leave a comment

About laurent_r

user-pic I am the author of the "Think Perl 6" book (O'Reilly, 2017) and I blog about the Perl 5 and Raku programming languages.