Sequence numbers
and split arrays
Weekly challenge 184 — 26 September 2022
Week 184: 26 Sep 2022
You are given list of strings in the format aa9999
ie first 2 characters can be anything
'a-z'
followed by 4 digits '0-9'
.
Write a script to replace the first two characters with sequence starting with
'00'
, '01'
, '02'
etc.
Example 1 Input: @list = ( 'ab1234', 'cd5678', 'ef1342') Output: ('001234', '015678', '021342') Example 2 Input: @list = ( 'pq1122', 'rs3334') Output: ('001122', '013334')
As with many of these tasks, formatting the input to match Mohammad's examples is part - and sometimes most - of the challenge.
The task itself is simply a case of iterating over the supplied list with $j
as the index, and replacing each term with:
sprintf('%02d%s', $j, substr($list[$j], 2))
which is the index, left padded with zeroes to make 2 digits, followed by characters 2 (zero-based) to the end of the original string.
#!/usr/bin/perl # Peter Campbell Smith - 2022-09-28 # PWC 184 task 1 use v5.28; use utf8; use warnings; my (@lists, $list_ref, @list, $old_show, $new_show, $j); # inputs @lists = (['ab1234', 'cd5678', 'ef1342'], ['pq1122', 'rs3334']); # loop over inputs while ($list_ref = shift @lists) { @list = @$list_ref; $old_show = $new_show = ''; # loop over list elements for $j (0 .. scalar @list - 1) { $old_show .= qq['$list[$j]', ]; $new_show .= qq['] . sprintf('%02d%s', $j, substr($list[$j], 2)) . qq[', ]; } # show the answer say qq[\nInput: (] . substr($old_show, 0, -2) . qq[)] . qq[\nOutput: (] . substr($new_show, 0, -2) . qq[)]; }
Input: ('ab1234', 'cd5678', 'ef1342') Output: ('001234', '015678', '021342') Input: ('pq1122', 'rs3334') Output: ('001122', '013334')
Any content of this website which has been created by Peter Campbell Smith is in the public domain