Peter
Peter Campbell Smith

Divide and detect

Weekly challenge 230 — 14 August 2023

Week 230: 14 Aug 2023

Task 2

Task — Count words

You are given an array of words made up of alphabetic characters and a prefix. Write a script to return the count of words that start with the given prefix.

Examples


Example 1
Input: @words  = ("pay", "attention", "practice", "attend")
       $prefix = "at"
Output: 2
Two words "attention" and "attend" start with the given prefix "at".

Example 2
Input: @words  = ("janet", "julia", "java", "javascript")
       $prefix = "ja"
Output: 3
Three words "janet", "java" and "javascripr" start with the given prefix "ja".

Analysis

There's probably a one-liner for this one too if you don't want to list the matches, but I did want to, so added a couple of lines. My solution adds the word to @matches if it matches the prefix.

Try it 

Example words: ping, pong, pint, punt, pine

Example prefix: pin

Script


#!/usr/bin/perl

use v5.16;    # The Weekly Challenge - 2023-08-14
use utf8;     # Week 230 task 2 - Count words
use strict;   # Peter Campbell Smith
use warnings; # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

count_words(['pay', 'attention', 'practice', 'attend'], 'at');
count_words(['janet', 'julia', 'java', 'javascript'], 'ja');
count_words(['hello', 'hedge', 'he', 'heffalump', 'herbivore', 'lion'], 'he');
count_words(['the', 'cat', 'sat', 'on', 'the', 'mat'], 'zzz');

sub count_words {
    
    my ($w, @matches);
    
    # add any word that matches to @matches
    @matches = ();
    for $w (@{$_[0]}) {
        push(@matches, $w) if $w =~ m|^$_[1]|;
    }
    
    # spill the beans
    say qq[\nInput:  \@words = ('] . join(qq[', '], @{$_[0]}) . qq['), \$prefix = '$_[1]'];
    say qq[Output: ] . ($#matches + 1) .
        (@matches ? (qq[ - '] . join(qq[', '], @matches) . qq[']) : '');    
}

Output


Input:  @words = ('pay', 'attention', 'practice', 'attend'), $prefix = 'at'
Output: 2 - 'attention', 'attend'

Input:  @words = ('janet', 'julia', 'java', 'javascript'), $prefix = 'ja'
Output: 3 - 'janet', 'java', 'javascript'

Input:  @words = ('hello', 'hedge', 'he', 'heffalump', 'herbivore', 'lion'), $prefix = 'he'
Output: 5 - 'hello', 'hedge', 'he', 'heffalump', 'herbivore'

Input:  @words = ('the', 'cat', 'sat', 'on', 'the', 'mat'), $prefix = 'zzz'
Output: 0

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain