The weekly challenge 235 - Task 2: Duplicate Zeros

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-235/#TASK2
 3 #
 4 # Task 2: Duplicate Zeros
 5 # =======================
 6 #
 7 # You are given an array of integers.
 8 #
 9 # Write a script to duplicate each occurrence of ZERO in the given array and
10 # shift the remaining to the right but make sure the size of array remain the
11 # same.
12 #
13 ## Example 1
14 ##
15 ## Input: @ints = (1, 0, 2, 3, 0, 4, 5, 0)
16 ## Ouput: (1, 0, 0, 2, 3, 0, 0, 4)
17 #
18 ## Example 2
19 ##
20 ## Input: @ints = (1, 2, 3)
21 ## Ouput: (1, 2, 3)
22 #
23 ## Example 3
24 ##
25 ## Input: @ints = (0, 3, 0, 4, 5)
26 ## Ouput: (0, 0, 3, 0, 0)
27 #
28 ############################################################
29 ##
30 ## discussion
31 ##
32 ############################################################
33 #
34 # Let's start by noting that there might be a situation where the last element
35 # in the array is a 0 which can no longer be duplicated without changing the size
36 # of the array, so we won't duplicate in that case.
37 
38 use strict;
39 use warnings;
40 
41 duplicate_zeros(1, 0, 2, 3, 0, 4, 5, 0);
42 duplicate_zeros(1, 2, 3);
43 duplicate_zeros(0, 3, 0, 4, 5);
44 duplicate_zeros(0, 3, 0, 4);
45 
46 sub duplicate_zeros {
47    my @ints = @_;
48    my @result = ();
49    print "Input: (" . join(", ", @ints) . ")\n";
50    while(@ints) {
51       my $first = shift @ints;
52       if(@ints) { # there are more elements in the array
53          if($first == 0) {
54             # duplicate the zero, remove last element from remainder
55             # this will effectively "shift right" the remainder of the
56             # array while keeping size
57             pop(@ints);
58             push @result, $first, 0;
59          } else {
60             # just move the non-zero value to the result
61             push @result, $first;
62          }
63       } else { # no more elements in the array
64          # this was the last element, so duplicating makes no sense any more
65          # just add the element to the result in either case
66          push @result, $first;
67       }
68    }
69    print "Output: (" . join(", ", @result) . ")\n";
70 }