Peter’s blog ✴ Week 235 ✴ 18 September 2023

THE WEEKLY CHALLENGE
Delete and double

The Perl Camel

Task 2

Duplicate zeroes

You are given an array of integers. Write a script to duplicate each occurrence of ZERO in the given array and shift the remaining to the right but make sure the size of array remain the same.

Examples


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

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

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

Analysis

This was quite easy. Pass along @ints. When you find a non-zero, push it onto @new, or if it is a zero, push two zeroes onto @new. And then truncate @new to be the same length as @ints.

Perl Weekly’s review

from PW issue 635

You will love the engaging discussion in the post. Too good to be missed.

Try it 

Try running the script with any input, for example:
1, 0, 2, 3, 0, 4


Script


#!/usr/bin/perl

use v5.16;    # The Weekly Challenge - 2023-09-18
use utf8;     # Week 235 task 2 - Duplicate zeroes
use strict;   # Peter Campbell Smith
use warnings; # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

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

sub duplicate_zeroes {
    
    my (@ints, $j, @new);
    
    # initialise
    @ints = @_;
    
    # push items from @ints onto @new, doubling every 0
    push @new, ($_ == 0 ? (0, 0) : $_) for @ints;
    
    # cut back @new to the length of @ints
    @new = @new[0 .. scalar @ints - 1];
    
    # show results
    say qq[\nInput:  \@ints = (] . join(qq[, ], @ints) . q[)];
    say qq[Output:         (] . join(qq[, ], @new) . q[)];;
}

7 lines of code

Output from script


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

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

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

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

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

 

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