28 September 2022

Sequence numbers and split arrays

Sequence numbers

Task 1 this week states that we are given a list of strings in the format aa9999 ie first 2 characters can be anything in a-z followed by 4 digits from 0-9, and we have to write a script to replace the first two characters with '00', '01', '02' etc.

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.

Split arrays

We are given a list of strings containing 0-9 and a-z, like this:

['1 2', 'p q r', 's 3', '4 5 t']

We are required to separate the digits and the letters to produce;

[[1,2], [3], [4,5]] and [['p','q','r'], ['s'], ['t']]

Interestingly the formatting of the output is rather different from the input.

After a couple of false starts I decided that the best strategy was to treat the input simply as a string of characters. The only characters that matter are the digits, letters and commas. I append digits to $first and (single-quoted) letters to $second, in both cases appending ', '. When a comma is encountered in the input I append '], [' to both $first and $second.

It's then just a case of combining '$first and $second' and eliminating trailing commas and empty occurrences of [].


No comments:

Post a Comment