The weekly challenge 333 - Task 2: Duplicate Zeros
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-333/#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, shifting the remaining 10 # elements to the right. The elements beyond the length of the original array 11 # are not written. 12 # 13 ## Example 1 14 ## 15 ## Input: @ints = (1, 0, 2, 3, 0, 4, 5, 0) 16 ## Output: (1, 0, 0, 2, 3, 0, 0, 4) 17 ## 18 ## Each zero is duplicated. 19 ## Elements beyond the original length (like 5 and last 0) are discarded. 20 # 21 # 22 ## Example 2 23 ## 24 ## Input: @ints = (1, 2, 3) 25 ## Output: (1, 2, 3) 26 ## 27 ## No zeros exist, so the array remains unchanged. 28 # 29 # 30 ## Example 3 31 ## 32 ## Input: @ints = (1, 2, 3, 0) 33 ## Output: (1, 2, 3, 0) 34 # 35 # 36 ## Example 4 37 ## 38 ## Input: @ints = (0, 0, 1, 2) 39 ## Output: (0, 0, 0, 0) 40 # 41 # 42 ## Example 5 43 ## 44 ## Input: @ints = (1, 2, 0, 3, 4) 45 ## Output: (1, 2, 0, 0, 3) 46 # 47 ############################################################ 48 ## 49 ## discussion 50 ## 51 ############################################################ 52 # 53 # We just walk from the left of the array to the right. Whenever 54 # we see a "0", we replace the rest of the array by a zero followed 55 # by the rest minus the last element. Of course then we need to skip 56 # the check for "0" in the next iteration so we keep state in a 57 # variable $skip. 58 59 use v5.36; 60 61 duplicate_zeros(1, 0, 2, 3, 0, 4, 5, 0); 62 duplicate_zeros(1, 2, 3); 63 duplicate_zeros(1, 2, 3, 0); 64 duplicate_zeros(0, 0, 1, 2); 65 duplicate_zeros(1, 2, 0, 3, 4); 66 67 sub duplicate_zeros(@ints) { 68 say "Input: (" . join(", ", @ints) . ")"; 69 my $skip = 0; 70 foreach my $i (0..$#ints-1) { 71 if($skip) { 72 $skip = 0; 73 next; 74 } 75 if($ints[$i] == 0) { 76 @ints[$i+1..$#ints] = (0, @ints[$i+1..$#ints-1]); 77 $skip = 1; 78 } 79 } 80 say "Output: (" . join(", ", @ints) . ")"; 81 }