Robbie Hatley's Solutions To The Weekly Challenge #230

For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle, usually with two parts, cycling every Sunday. You can find it here:

The Weekly Challenge

This week (2023-08-13 through 2023-08-19) is weekly challenge #230.

Task 1 is as follows:

Task 1: Separate Digits
Submitted by: Mohammad S Anwar
You are given an array of positive integers. Write a script
to separate the given array into single digits.

Example 1:
Input: @ints = (1, 34, 5, 6)
Output: (1, 3, 4, 5, 6)

Example 2:
Input: @ints = (1, 24, 51, 60)
Output: (1, 2, 4, 5, 1, 6, 0)

In Perl, any integer scalar can be treated like a string, so this task can be done by using "split" to chop the integers into arrays of digits, then dump them into a new array:

my @new = map {split //, $_} @old;

The script I came up with is this:

Robbie Hatley's Solution to The Weekly Challenge 230-1

Task 2 is as follows:

Task 2: Count Words
Submitted by: Mohammad S Anwar
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
starts with the given prefix.

Example 1:
Input:
   @words  = ("pay", "attention", "practice", "attend")
   $prefix = "at"
Ouput: 2
(The two words "attention" and "attend" start with "at".)

Example 2:
Input: 
   @words  = ("janet", "julia", "java", "javascript")
   $prefix = "ja"
Ouput: 3
(The three words "janet", "java" and "javascript" start with "ja".

This calls for the use of a regular expression:

$word =~ m/^$prefix/ and ++$count;

Here's the script I wrote:

Robbie Hatley's Solution to The Weekly Challenge 230-2

That's it for 230; see you on 231!

Comments

Popular posts from this blog

Robbie Hatley's Solutions To The Weekly Challenge #262

Robbie Hatley's Solutions To The Weekly Challenge #266

Robbie Hatley's Solutions To The Weekly Challenge #273