The weekly challenge 326 - Task 2: Decompressed List
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-326/#TASK2 3 # 4 # Task 2: Decompressed List 5 # ========================= 6 # 7 # You are given an array of positive integers having even elements. 8 # 9 # Write a script to to return the decompress list. To decompress, pick adjacent 10 # pair (i, j) and replace it with j, i times. 11 # 12 ## Example 1 13 ## 14 ## Input: @ints = (1, 3, 2, 4) 15 ## Output: (3, 4, 4) 16 ## 17 ## Pair 1: (1, 3) => 3 one time => (3) 18 ## Pair 2: (2, 4) => 4 two times => (4, 4) 19 # 20 # 21 ## Example 2 22 ## 23 ## Input: @ints = (1, 1, 2, 2) 24 ## Output: (1, 2, 2) 25 ## 26 ## Pair 1: (1, 1) => 1 one time => (1) 27 ## Pair 2: (2, 2) => 2 two times => (2, 2) 28 # 29 # 30 ## Example 3 31 ## 32 ## Input: @ints = (3, 1, 3, 2) 33 ## Output: (1, 1, 1, 2, 2, 2) 34 ## 35 ## Pair 1: (3, 1) => 1 three times => (1, 1, 1) 36 ## Pair 2: (3, 2) => 2 three times => (2, 2, 2) 37 # 38 ############################################################ 39 ## 40 ## discussion 41 ## 42 ############################################################ 43 # 44 # Since perl v5.36 has the possibility to run foreach with two elements 45 # of a list at once, we use that neat feature to walk all pairs of 46 # $i and $j. Then we put $j into the result $i times. 47 48 use v5.36; 49 decompressed_list(1, 3, 2, 4); 50 decompressed_list(1, 1, 2, 2); 51 decompressed_list(3, 1, 3, 2); 52 53 sub decompressed_list( @ints ) { 54 say "Input: (" . join(", ", @ints) . ")"; 55 my @output = (); 56 foreach my ($i, $j) (@ints) { 57 foreach my $k (1..$i) { 58 push @output, $j; 59 } 60 } 61 say "Output: (" . join(", ", @output) . ")"; 62 }