The Weekly Challenge 376

Chessboard Squares and Doubled Words

Task 1: Chessboard Squares

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

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

Example 1

Input: $coord1 = "a7", $coord2 = "f4" Output: 1

Example 2

Input: $coord1 = "c1", $coord2 = "e8" Output: 0

Example 3

Input: $coord1 = "b5", $coord2 = "h2" Output: 0

Logic

On an 8x8 chessboard, the columns can be mapped to 1-8 (a=1, b=2, etc.). The color parity of any square is determined by the sum of its column and row index: (col + row) % 2. If both squares have the same parity, they share the same color.

Perl Solution

ch-1.pl

sub square_color_parity ($coord) { die "Invalid coordinate format" unless $coord =~ /^([a-h])([1-8])$/; my ($col, $row) = ($1, $2); my $col_num = ord($col) - ord('a') + 1; return ($col_num + $row) % 2; } sub same_color ($c1, $c2) { return square_color_parity($c1) == square_color_parity($c2) ? 1 : 0; }

Python Solution

ch-1.py

def square_color_parity(coord: str) -> int: if len(coord) != 2 or coord[0] not in "abcdefgh" or coord[1] not in "12345678": raise ValueError("Invalid coordinate format") col_num = ord(coord[0]) - ord("a") + 1 row_num = int(coord[1]) return (col_num + row_num) % 2 def same_color(c1: str, c2: str) -> bool: return square_color_parity(c1) == square_color_parity(c2)

Task 2: Doubled Words

Write a script to find case-insensitive doubled words (separated by whitespace or HTML tags) in a block of text, wrap each matching word in brackets [word], and output only the lines containing these matches.

Example 1

Input: "you're given the job of checking the pages on a\nweb server for doubled words (such as 'this this'), a common problem" Output: "web server for doubled words (such as '[this] [this]'), a common problem"

Logic

A regex backreference \b(\w+)\b(\s*(?:<[^>]*>\s*)*)\b(\1)\b is used to locate doubled words. We wrap matched items in brackets while keeping their original separator. The lines are then filtered to output only those containing brackets.

Perl Solution

ch-2.pl

sub highlight_doubled_words ($str) { my $modified = $str; $modified =~ s/\b(\w+)\b(\s*(?:<[^>]*>\s*)*)\b(\1)\b/"[$1]" . $2 . "[$3]"/gie; my @lines = split /\n/, $modified; my @kept_lines = grep { /\[\w+\]/ } @lines; return join("\n", @kept_lines); }

Python Solution

ch-2.py

def highlight_doubled_words(text: str) -> str: pattern = re.compile(r"\b(\w+)\b(\s*(?:<[^>]*>\s*)*)\b(\1)\b", re.IGNORECASE) modified = pattern.sub(r"[\1]\2[\3]", text) lines = modified.split("\n") kept_lines = [line for line in lines if re.search(r"\[\w+\]", line)] return "\n".join(kept_lines)