The weekly challenge 235 - Task 1: Remove One
1 #!/usr/bin/perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-235/#TASK1 3 # 4 # Task 1: Remove One 5 # ================== 6 # 7 # You are given an array of integers. 8 # 9 # Write a script to find out if removing ONLY one integer makes it strictly 10 # increasing order. 11 # 12 ## Example 1 13 ## 14 ## Input: @ints = (0, 2, 9, 4, 6) 15 ## Output: true 16 ## 17 ## Removing ONLY 9 in the given array makes it strictly increasing order. 18 # 19 ## Example 2 20 ## 21 ## Input: @ints = (5, 1, 3, 2) 22 ## Output: false 23 # 24 ## Example 3 25 ## 26 ## Input: @ints = (2, 2, 3) 27 ## Output: true 28 # 29 ############################################################ 30 ## 31 ## discussion 32 ## 33 ############################################################ 34 # 35 # Let's just remember that strictly increasing order means 36 # each element is bigger than the previous one and can't even 37 # be equal. So let's try to remove each element in turn and 38 # check if the remaining array is strictly increasing. 39 40 use strict; 41 use warnings; 42 43 remove_one(0, 2, 9, 4, 6); 44 remove_one(5, 1, 3, 2); 45 remove_one(2, 2, 3); 46 47 sub remove_one { 48 my @ints = @_; 49 print "Input: (" . join(", ", @ints) . ")\n"; 50 foreach my $index (0..$#ints) { 51 # if the remaining array with the element at the current index removed 52 # is strictly increasing then we found a solution that works 53 if(is_strictly_increasing(@ints[0..$index-1], @ints[$index+1..$#ints])) { 54 print "Output: True\n"; 55 return; 56 } 57 } 58 print "Output: False\n"; 59 } 60 61 sub is_strictly_increasing { 62 my @ints = @_; 63 my $previous = shift @ints; 64 # if any element is smaller or equal than the previous one, this 65 # array is not strictly increasing 66 foreach my $elem (@ints) { 67 return 0 if $elem <= $previous; 68 $previous = $elem; 69 } 70 return 1; 71 }