Camel
Peter
Peter Campbell Smith

Find answers

Weekly challenge 315 — 31 March 2025

Week 315: 31 Mar 2025

Task 1

Task — Find words

You are given a list of words and a character. Write a script to return the indexes of the words in the list which contain the given character.

Examples


Example 1
Input: @list = ("the", "weekly", "challenge")
       $char = "e"
Output: (0, 1, 2)


Example 2
Input: @list = ("perl", "raku", "python")
       $char = "p"
Output: (0, 2)


Example 3
Input: @list = ("abc", "def", "bbb", "bcd")
       $char = "b"
Output: (0, 2, 3)

Analysis

Another challenge where I think a one-liner is reasonably easy to understand. In English it says:

For every word in @list, append its index to $found if the word contains $char.

The rest is just about formatting the output to match the examples.

Try it 

Try running the script with any input:



example: this one is quite easy



example: q

Script


#!/usr/bin/perl

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

use v5.26;    # The Weekly Challenge - 2025-03-31
use utf8;     # Week 315 - task 1 - Find words
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

find_words([qw[the weekly challenge]], 'e');
find_words([qw[all cows eat grass]], 'a');
find_words([qw[some letters never occur]], 'z');
find_words([qw[all alligators are adept]], 'a');
find_words([qw[count best last attempt]], 't');
find_words([qw[if you cannot find it check the index]], 'x');

sub find_words {
    
    my (@list, $char, $found);
    @list = @{$_[0]};
    $char = $_[1];
    
    # find the elements of @list containg $char
    $found .= ($list[$_] =~ m|$char| ? qq[$_, ] : '') for 0 .. $#list;
    
    printf(qq[\nInput:  \@list = ('%s'), \$char = '%s'\n], join(qq[', '], @list), $char);
    say qq[Output: ] . ($found ? ('(' . substr($found, 0, -2) . ')') : 'none');
}

Output


Input:  @list = ('the', 'weekly', 'challenge'), 
   $char = 'e'
Output: (0, 1, 2)

Input:  @list = ('all', 'cows', 'eat', 'grass'), 
   $char = 'a'
Output: (0, 2, 3)

Input:  @list = ('some', 'letters', 'never', 'occur'), 
   $char = 'z'
Output: none

Input:  @list = ('all', 'alligators', 'are', 'adept'), 
   $char = 'a'
Output: (0, 1, 2, 3)

Input:  @list = ('count', 'best', 'last', 'attempt'), 
   $char = 't'
Output: (0, 1, 2, 3)

Input:  @list = ('if', 'you', 'cannot', 'find', 'it', 
   'check', 'the', 'index'), $char = 'x'
Output: (7)

 

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