Delete and double
Weekly challenge 235 — 18 September 2023
Week 235: 18 Sep 2023
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.
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)
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.
#!/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[)];; }
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