The weekly challenge 345 - Task 1: Peak Positions
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-345/#TASK1 3 # 4 # Task 1: Peak Positions 5 # ====================== 6 # 7 # You are given an array of integers, @ints. 8 # 9 # Find all the peaks in the array, a peak is an element that is strictly 10 # greater than its left and right neighbours. Return the indices of all such 11 # peak positions. 12 # 13 ## Example 1 14 ## 15 ## Input: @ints = (1, 3, 2) 16 ## Output: (1) 17 # 18 # 19 ## Example 2 20 ## 21 ## Input: @ints = (2, 4, 6, 5, 3) 22 ## Output: (2) 23 # 24 # 25 ## Example 3 26 ## 27 ## Input: @ints = (1, 2, 3, 2, 4, 1) 28 ## Output: (2, 4) 29 # 30 # 31 ## Example 4 32 ## 33 ## Input: @ints = (5, 3, 1) 34 ## Output: (0) 35 # 36 # 37 ## Example 5 38 ## 39 ## Input: @ints = (1, 5, 1, 5, 1, 5, 1) 40 ## Output: (1, 3, 5) 41 # 42 ############################################################ 43 ## 44 ## discussion 45 ## 46 ############################################################ 47 # 48 # We walk from the beginning of the array to the end and check 49 # if the current element is greater than its neighbors. If so, 50 # we keep its index around to add it to the result. 51 52 use v5.36; 53 54 peak_positions(1, 3, 2); 55 peak_positions(2, 4, 6, 5, 3); 56 peak_positions(1, 2, 3, 2, 4, 1); 57 peak_positions(5, 3, 1); 58 peak_positions(1, 5, 1, 5, 1, 5, 1); 59 60 sub peak_positions(@ints) { 61 say "Input: (" . join(", ", @ints) . ")"; 62 my @result = (); 63 foreach my $i (0..$#ints) { 64 my $keep = 1; 65 if($i > 0) { 66 $keep = 0 if $ints[$i] <= $ints[$i-1]; 67 } 68 if($i < $#ints) { 69 $keep = 0 if $ints[$i] <= $ints[$i+1]; 70 } 71 push @result, $i if $keep; 72 } 73 say "Output: (" . join(", ", @result) . ")"; 74 }