The weekly challenge 256 - Task 1: Maximum Pairs
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-256/#TASK1 3 # 4 # Task 1: Maximum Pairs 5 # ===================== 6 # 7 # You are given an array of distinct words, @words. 8 # 9 # Write a script to find the maximum pairs in the given array. The words 10 # $words[i] and $words[j] can be a pair one is reverse of the other. 11 # 12 ## Example 1 13 ## 14 ## Input: @words = ("ab", "de", "ed", "bc") 15 ## Output: 1 16 ## 17 ## There is one pair in the given array: "de" and "ed" 18 # 19 ## Example 2 20 ## 21 ## Input: @words = ("aa", "ba", "cd", "ed") 22 ## Output: 0 23 # 24 ## Example 3 25 ## 26 ## Input: @words = ("uv", "qp", "st", "vu", "mn", "pq") 27 ## Output: 2 28 # 29 ############################################################ 30 ## 31 ## discussion 32 ## 33 ############################################################ 34 # 35 # Just check all possible pairs. 36 37 use strict; 38 use warnings; 39 40 maximum_pairs("ab", "de", "ed", "bc"); 41 maximum_pairs("aa", "ba", "cd", "ed"); 42 maximum_pairs("uv", "qp", "st", "vu", "mn", "pq"); 43 44 sub maximum_pairs { 45 my @words = @_; 46 print "Input: (\"" . join("\", \"", @words) . "\")\n"; 47 my $count = 0; 48 foreach my $i (0..$#words) { 49 foreach my $j ($i+1..$#words) { 50 if($words[$i] eq reversed($words[$j]) ) { 51 $count++; 52 last; 53 } 54 } 55 } 56 print "Output: $count\n"; 57 } 58 59 sub reversed { 60 my $word = shift; 61 return join("", reverse split //, $word); 62 }