Perl Weekly Challenge 230: Separate Digits
These are some answers to the Week 230, Task 1, of the Perl Weekly Challenge organized by Mohammad S. Anwar.
Spoiler Alert: This weekly challenge deadline is due in a few days from now (on August 20, 2023 at 23:59). This blog post offers some solutions to this challenge. Please don’t read on if you intend to complete the challenge on your own.
Task 1: Separate Digits
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
This task is very simple. We just need to split each value of the input array into individual digits and collect them into a list or an array.
Separate Digits in Raku
The separate-digits
subroutine splits each input value into individual digits using the built-in comb method together with the map routine to iterate over the input items. Note that we also need to use the flat method to obtain a single Seq
of values.
sub separate-digits (@ints) {
return (map { $_.comb }, @ints).flat;
}
for <1 34 5 6>, <1 24 51 60> -> @test {
printf "%-10s => ", "@test[]";
say separate-digits @test;
}
This program displays the following output:
$ raku ./separate-digits.raku
1 34 5 6 => 1 3 4 5 6
1 24 51 60 => 1 2 4 5 1 6 0
Separate Digits in Perl
This is essentially a port to Perl of the above Raku program. We use split
to split each input value into individual digits, and map
to iterate over the input items. Contrary to Raku, Perl automatically flattens the result into one large array or list.
use strict;
use warnings;
use feature qw /say/;
sub separate_digits {
return join " ", map { split //, $_ } @_;
}
for my $test ( [<1 34 5 6>], [<1 24 51 60>] ) {
printf "%-10s => ", "@$test";
say separate_digits @$test;
}
This program displays the following output:
$ perl separate-digits.pl
1 34 5 6 => 1 3 4 5 6
1 24 51 60 => 1 2 4 5 1 6 0
Wrapping up
The next week Perl Weekly Challenge will start soon. If you want to participate in this challenge, please check https://perlweeklychallenge.org/ and make sure you answer the challenge before 23:59 BST (British summer time) on August 27, 2023. And, please, also spread the word about the Perl Weekly Challenge if you can.
Leave a comment