The weekly challenge 250 - Task 1: Smallest Index
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-250/#TASK1 3 # 4 # Task 1: Smallest Index 5 # ====================== 6 # 7 # You are given an array of integers, @ints. 8 # 9 # Write a script to find the smallest index i such that i mod 10 == $ints[i] 10 # otherwise return -1. 11 # 12 ## Example 1 13 ## 14 ## Input: @ints = (0, 1, 2) 15 ## Output: 0 16 ## 17 ## i=0: 0 mod 10 = 0 == $ints[0]. 18 ## i=1: 1 mod 10 = 1 == $ints[1]. 19 ## i=2: 2 mod 10 = 2 == $ints[2]. 20 ## All indices have i mod 10 == $ints[i], so we return the smallest index 0. 21 # 22 ## Example 2 23 ## 24 ## Input: @ints = (4, 3, 2, 1) 25 ## Output: 2 26 ## 27 ## i=0: 0 mod 10 = 0 != $ints[0]. 28 ## i=1: 1 mod 10 = 1 != $ints[1]. 29 ## i=2: 2 mod 10 = 2 == $ints[2]. 30 ## i=3: 3 mod 10 = 3 != $ints[3]. 31 ## 2 is the only index which has i mod 10 == $ints[i]. 32 # 33 ## Example 3 34 ## 35 ## Input: @ints = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] 36 ## Output: -1 37 ## Explanation: No index satisfies i mod 10 == $ints[i]. 38 # 39 ############################################################ 40 ## 41 ## discussion 42 ## 43 ############################################################ 44 # 45 # Walk the array from the start to the end, return once 46 # i mod 10 == $ints[i]. In the end, return -1 if no entry 47 # satisfied the condition. 48 49 use strict; 50 use warnings; 51 52 smallest_index(0, 1, 2); 53 smallest_index(4, 3, 2, 1); 54 smallest_index(1, 2, 3, 4, 5, 6, 7, 8, 9, 0); 55 56 sub smallest_index { 57 my @ints = @_; 58 print "Input: (" . join(", ", @ints) . ")\n"; 59 foreach my $i (0..$#ints) { 60 if( $i % 10 == $ints[$i] ) { 61 print "Output: $i\n"; 62 return; 63 } 64 } 65 print "Output: -1\n"; 66 }