The weekly challenge 376 - Task 1: Chessboard Squares
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-376/#TASK1 3 # 4 # Task 1: Chessboard Squares 5 # ========================== 6 # 7 # You are given two coordinates of a square on 8x8 chessboard. 8 # 9 # Write a script to find the given two coordinates have the same colour. 10 # 11 # 8 W B W B W B W B 12 # 7 B W B W B W B W 13 # 6 W B W B W B W B 14 # 5 B W B W B W B W 15 # 4 W B W B W B W B 16 # 3 B W B W B W B W 17 # 2 W B W B W B W B 18 # 1 B W B W B W B W 19 # a b c d e f g h 20 # 21 ## Example 1 22 ## 23 ## Input: $c1 = "a7", $c2 = "f4" 24 ## Output: true 25 # 26 ## Example 2 27 ## 28 ## Input: $c1 = "c1", $c2 = "e8" 29 ## Output: false 30 # 31 ## Example 3 32 ## 33 ## Input: $c1 = "b5", $c2 = "h2" 34 ## Output: false 35 # 36 ## Example 4 37 ## 38 ## Input: $c1 = "f3", $c2 = "h1" 39 ## Output: true 40 # 41 ## Example 5 42 ## 43 ## Input: $c1 = "a1", $c2 = "g8" 44 ## Output: false 45 # 46 ############################################################ 47 ## 48 ## discussion 49 ## 50 ############################################################ 51 # 52 # We translate a through h to numbers in the range 1 through 8. 53 # Then two coordinates have the same color if the sum of their 54 # coordinates share the same parity. 55 56 use v5.36; 57 58 chessboard_squares("a7", "f4"); 59 chessboard_squares("c1", "e8"); 60 chessboard_squares("b5", "h2"); 61 chessboard_squares("f3", "h1"); 62 chessboard_squares("a1", "g8"); 63 64 sub chessboard_squares($c1, $c2) { 65 say "Input: c1 = $c1, c2 = $c2"; 66 my ($column1, $row1) = split //, $c1; 67 my ($column2, $row2) = split //, $c2; 68 my $column_to_number = { 69 "a" => 1, "b" => 2, "c" => 3, "d" => 4, 70 "e" => 5, "f" => 6, "g" => 7, "h" => 8 71 }; 72 if ( ($column_to_number->{$column1} + $row1) % 2 73 == ($column_to_number->{$column2} + $row2) % 2) { 74 say "Output: true"; 75 } else { 76 say "Output: false"; 77 } 78 }