1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-207/#TASK1
 3 #
 4 # Task 1: Keyboard Word
 5 # =====================
 6 #
 7 # You are given an array of words.
 8 #
 9 # Write a script to print all the words in the given array that can be types using alphabet on only one row of the keyboard.
10 #
11 # Let us assume the keys are arranged as below:
12 #
13 # Row 1: qwertyuiop
14 # Row 2: asdfghjkl
15 # Row 3: zxcvbnm
16 #
17 ## Example 1
18 ##
19 ## Input: @words = ("Hello","Alaska","Dad","Peace")
20 ## Output: ("Alaska","Dad")
21 #
22 ## Example 2
23 ##
24 ## Input: @array = ("OMG","Bye")
25 ## Output: ()
26 #
27 ############################################################
28 ##
29 ## discussion
30 ##
31 ############################################################
32 #
33 # Basically, for all input words, we create the same word in
34 # lowercase and for each keyboard row, we check whether we can
35 # build this word with this row and add it to the output if we
36 # can
37 
38 use strict;
39 use warnings;
40 use feature 'say';
41 
42 keyboard_word("Hello","Alaska","Dad","Peace");
43 keyboard_word("OMG","Bye");
44 
45 sub keyboard_word {
46    my @words = @_;
47    my @output = ();
48    foreach my $word (@words) {
49       # if the lowercase "lc()" version of $word is a keyboard
50       # word, we can push the word onto the output
51       push @output, $word if is_keyboard_word(lc($word));
52    }
53    say "Input: (" . join(",", @words) . ")";
54    say "Output: (" . join(",", @output) . ")";
55 }
56 
57 sub is_keyboard_word {
58    my $word = shift;
59    my @rows = ( "qwertyuiop", "asdfghjkl", "zxcvbnm");
60    my @chars = split //, $word;
61    foreach my $row (@rows) {
62       # if $found_all is still 1 after all characters have been
63       # found in the current row, we found a keyboard word
64       my $found_all = 1;
65       foreach my $char (@chars) {
66          if($row !~ m/$char/) {
67             # we found a character that is not in this row
68             $found_all = 0;
69          }
70       }
71       return 1 if $found_all;
72    }
73    # we haven't found all characters in the same row for all rows
74    return 0;
75 }