Camel
Peter
Peter Campbell Smith

Straight zeroes

Weekly challenge 333 — 4 August 2025

Week 333: 4 Aug 2025

Task 2

Task — Duplicate zeros

You are given an array of integers. Write a script to duplicate each occurrence of zero, shifting the remaining elements to the right. The elements beyond the length of the original array are not written.

Examples


Example 1
Input: @ints = (1, 0, 2, 3, 0, 4, 5, 0)
Output: (1, 0, 0, 2, 3, 0, 0, 4)
Each zero is duplicated.
Elements beyond the original length (like 5 and last 0) 
   are discarded.

Example 2
Input: @ints = (1, 2, 3)
Output: (1, 2, 3)
No zeros exist, so the array remains unchanged.

Example 3
Input: @ints = (1, 2, 3, 0)
Output: (1, 2, 3, 0)

Example 4
Input: @ints = (0, 0, 1, 2)
Output: (0, 0, 0, 0)

Example 5
Input: @ints = (1, 2, 0, 3, 4)
Output: (1, 2, 0, 0, 3)

Analysis

This one's a bit simpler.

Step 1 is to create a new array mapping each 0 to (0, 0) and just copying over any non-zero elements.

Step 2 is to output the first n elements of the new array, where n is the number of elements in the input array.

Try it 

Try running the script with any input:



example: 0, 4, 0, 8, 2, 5

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2025-08-04
use utf8;     # Week 333 - task 2 - Duplicate zeros
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

duplicate_zeros(1, 0, 2, 3, 0, 4, 5, 0);
duplicate_zeros(1, 2, 3);
duplicate_zeros(1, 2, 3, 0);
duplicate_zeros(0, 0, 1, 2);
duplicate_zeros(1, 2, 0, 3, 4);

sub duplicate_zeros {
    
    # map each 0 to 0, 0
    my @output = map($_ == 0 ? (0, 0) : $_, @_);
    
    # output as many elements in @output as in the input array
    say qq[\nInput:  (] . join(', ', @_) . ')';
    say qq[Output: (] . join(', ', @output[0 .. $#_]) . ')';
}

Output


Input:  (1, 0, 2, 3, 0, 4, 5, 0)
Output: (1, 0, 0, 2, 3, 0, 0, 4)

Input:  (1, 2, 3)
Output: (1, 2, 3)

Input:  (1, 2, 3, 0)
Output: (1, 2, 3, 0)

Input:  (0, 0, 1, 2)
Output: (0, 0, 0, 0)

Input:  (1, 2, 0, 3, 4)
Output: (1, 2, 0, 0, 3)

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain