The weekly challenge 281 - Task 1: Check Color
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-281/#TASK1 3 # 4 # You are given coordinates, a string that represents the coordinates of a 5 # square of the chessboard as shown below: 6 # 7 # 8 # # # # 8 # 7# # # # 9 # 6 # # # # 10 # 5# # # # 11 # 4 # # # # 12 # 3# # # # 13 # 2 # # # # 14 # 1# # # # 15 # abcdefgh 16 # 17 # Write a script to return true if the square is light, and false if the square 18 # is dark. 19 # 20 ## Example 1 21 ## 22 ## Input: $coordinates = "d3" 23 ## Output: true 24 # 25 ## Example 2 26 ## 27 ## Input: $coordinates = "g5" 28 ## Output: false 29 # 30 ## Example 3 31 ## 32 ## Input: $coordinates = "e6" 33 ## Output: true 34 # 35 ############################################################ 36 ## 37 ## discussion 38 ## 39 ############################################################ 40 # 41 # Let's map a through h to 1 through 8. That way, each square has coordinates 42 # char/digit which map to digit/digit. We can observe that the sum of those 43 # digits is even when the square is dark (this works because at the end of a 44 # line, for example h1, we can jump to the beginning of the next line, and the 45 # mapping jumps from 8:1 to 1:2 which changes evenness in both digits, keeping 46 # it overall, and indeed we keep the light/dark by jumping there as well). 47 # So if the sum of the mapped digits is even, we have a dark square. That's easy 48 # to calculate. 49 50 use strict; 51 use warnings; 52 53 check_color("d3"); 54 check_color("g5"); 55 check_color("e6"); 56 57 sub check_color { 58 my $coordinates = shift; 59 my $map = { "a" => 1, "b" => 2, "c" => 3, "d" => 4, 60 "e" => 5, "f" => 6, "g" => 7, "h" => 8 }; 61 my ($char, $digit) = split //, $coordinates; 62 print "Input: $coordinates\n"; 63 my $odd = ($map->{$char} + $digit) % 2; 64 if($odd) { 65 return print "Output: true\n"; 66 } 67 return print "Output: false\n"; 68 }