Peter’s blog ✴ Week 344 ✴ 20 October 2025
THE WEEKLY CHALLENGE
Hip, hip, array!
You are given an array of integers, @ints
and an integer, $x.
Write a script to add $x to the integer in array form.
The array form of an integer is a digit-by-digit representation stored as an array, where the most significant digit is at the 0th index.
Example 1 Input: @ints = (1, 2, 3, 4), $x = 12 Output: (1, 2, 4, 6) Example 2 Input: @ints = (2, 7, 4), $x = 181 Output: (4, 5, 5) Example 3 Input: @ints = (9, 9, 9), $x = 1 Output: (1, 0, 0, 0) Example 4 Input: @ints = (1, 0, 0, 0, 0), $x = 9999 Output: (1, 9, 9, 9, 9) Example 5 Input: @ints = (0), $x = 1000 Output: (1, 0, 0, 0)
My one-line solution is:
join to convert @ints to a number
$x
split to convert that to an array@x is stated to be 'an integer', so we have to
allow for it being 0 or negative, which my algorithm
covers. However, we aren't told how
to represent a negative number in array form so I have
assumed that this is not allowed, ie this is invalid:
@ints = (1, 2, 3); $x = -124
There is also the possibility that @ints
or the result of the addition represent
a number larger than can be represented as a Perl
integer. My code fails in that case, but the algorithm
is still valid if translated into Math::BigInt
notation.
In the great majority of real-world use cases, this solution accurately resolves the issue and is clear, practical and effective. It creates a sophisticated one-liner by utilizing Perl's advantages in handling strings and numbers. The fundamental requirement of the problem—converting between array and numerical representations—is clearly understood by Peter.
This review may cover either or both challenges for this week.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2025-10-20 use utf8; # Week 344 - task 1 - Array form compute use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; array_form_compute([1, 2, 3, 4], 12); array_form_compute([2, 7, 4], 181); array_form_compute([9, 9, 9], 1); array_form_compute([0, 1, 2, 3, 4], -17); array_form_compute([1, 2, 3, 4], -1000); array_form_compute([1, 2, 3, 4], -1234); array_form_compute([0], 12345); sub array_form_compute { say qq[\nInput: \@ints = (] . join(', ', @{$_[0]}) . qq[), \$x = $_[1]]; # do it say qq[Output: (] . join(', ', split('', join('', @{$_[0]}) + $_[1])) . ')'; }
6 lines of code
Input: @ints = (1, 2, 3, 4), $x = 12 Output: (1, 2, 4, 6) Input: @ints = (2, 7, 4), $x = 181 Output: (4, 5, 5) Input: @ints = (9, 9, 9), $x = 1 Output: (1, 0, 0, 0) Input: @ints = (0, 1, 2, 3, 4), $x = -17 Output: (1, 2, 1, 7) Input: @ints = (1, 2, 3, 4), $x = -1000 Output: (2, 3, 4) Input: @ints = (1, 2, 3, 4), $x = -1234 Output: (0) Input: @ints = (0), $x = 12345 Output: (1, 2, 3, 4, 5)
Any content of this website which has been created by Peter Campbell Smith is in the public domain