Peter
Peter Campbell Smith

All on the same line,
and am I being cited?

Weekly challenge 207 — 6 March 2023

Week 207 - 6 Mar 2023

Task 1

Task — Linear words

We are given an array of words and asked to write a script to print all the words in the array that can be typed using the letters on only one row of the keyboard.

Analysis

I toyed with the idea of a regular expression that would handle all the words at once, but concluded that it would be rather unreadable, so settled on a loop over the words and using

$word =~ m¦^([qwertyuiop]+|[asdfghjkl]+|[zxcvbnm]+)$¦i;

to identify the ones that met the requirement.

In fact, there are no words in English (or any other language that I am familiar with) that can be typed on the third row, ie that match [zxcvbnm]+, so that could probably be eliminated from the regex.

Try it 

Example: the typewriter has been made obsolete

Script


#!/usr/bin/perl

# Peter Campbell Smith - 2023-02-20

use v5.28;
use utf8;
use warnings;

# We are given an array of words and asked to write a script to print all the words in the 
# array that can be typed using the letters on only one row of the keyboard.

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge/207/1

linear_words('Hello','Alaska','Dad','Peace');
linear_words('OMG','Bye');
linear_words('typewriter', 'zmncbxvz', 'shakalshas');
linear_words(qw[We are given an array of words and asked to write a script to print all the words in the 
    array that can be typed using the letters on only one row of the keyboard]);
    
sub linear_words {

    my (@test, $word, $result);
    $result = '';
    
    # loop over words and save those that are monolinear
    for $word (@_) {
        $result .= qq['$word', ] if $word =~ ^([qwertyuiop]+|[asdfghjkl]+|[zxcvbnm]+)$¦i;
    }
    
    say qq[\nInput:  ('] . join(q[', '], @_) . qq[')];
    say qq[Output: (] . substr($result, 0, -2) . qq[)];
}   

Output


Input:  ('Hello', 'Alaska', 'Dad', 'Peace')
Output: ('Alaska', 'Dad')

Input:  ('OMG', 'Bye')
Output: ()

Input:  ('typewriter', 'zmncbxvz', 'shakalshas')
Output: ('typewriter', 'zmncbxvz', 'shakalshas')

Input:  ('We', 'are', 'given', 'an', 'array', 'of', 'words', 'and', 'asked', 'to', 'write', 'a', 'script', 'to', 'print', 'all', 'the', 'words', 'in', 'the', 'array', 'that', 'can', 'be', 'typed', 'using', 'the', 'letters', 'on', 'only', 'one', 'row', 'of', 'the', 'keyboard')
Output: ('We', 'to', 'write', 'a', 'to', 'all', 'row')