Camel
Peter
Peter Campbell Smith

Hip, hip, array!

Weekly challenge 344 — 20 October 2025

Week 344: 20 Oct 2025

Task 1

Task — Array form compute

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.

Examples


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)

Analysis

My one-line solution is:

  • use join to convert @ints to a number
  • add $x
  • use 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:

@input = (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.

Try it 

Try running the script with any input:



example: 1, 2, 3, 4, 5



example: 54321

Script


#!/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]))
        . ')';
}

Output


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