The weekly challenge 257 - Task 1: Smaller than Current
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-257/#TASK1 3 # 4 # Task 1: Smaller than Current 5 # ============================ 6 # 7 # You are given a array of integers, @ints. 8 # 9 # Write a script to find out how many integers are smaller than current i.e. 10 # foreach ints[i], count ints[j] < ints[i] where i != j. 11 # 12 ## Example 1 13 ## 14 ## Input: @ints = (5, 2, 1, 6) 15 ## Output: (2, 1, 0, 3) 16 ## 17 ## For $ints[0] = 5, there are two integers (2,1) smaller than 5. 18 ## For $ints[1] = 2, there is one integer (1) smaller than 2. 19 ## For $ints[2] = 1, there is none integer smaller than 1. 20 ## For $ints[3] = 6, there are three integers (5,2,1) smaller than 6. 21 # 22 ## Example 2 23 ## 24 ## Input: @ints = (1, 2, 0, 3) 25 ## Output: (1, 2, 0, 3) 26 # 27 ## Example 3 28 ## 29 ## Input: @ints = (0, 1) 30 ## Output: (0, 1) 31 # 32 ## Example 4 33 ## 34 ## Input: @ints = (9, 4, 9, 2) 35 ## Output: (2, 1, 2, 0) 36 # 37 ############################################################ 38 ## 39 ## discussion 40 ## 41 ############################################################ 42 # 43 # Walk through the array, and for each element, walk through 44 # the whole array again, counting the elements that are smaller 45 # than the one in the outer loop. Put the result of this loop run 46 # at the end of the final result. 47 # 48 use strict; 49 use warnings; 50 51 smaller_than_current(5, 2, 1, 6); 52 smaller_than_current(1, 2, 0, 3); 53 smaller_than_current(0, 1); 54 smaller_than_current(9, 4, 9, 2); 55 56 sub smaller_than_current { 57 my @ints = @_; 58 print "Input: (" . join(", ", @ints) . ")\n"; 59 my @result = (); 60 foreach my $i (0..$#ints) { 61 my $count = 0; 62 foreach my $j (0..$#ints) { 63 next if $i == $j; 64 $count++ if $ints[$i] > $ints[$j]; 65 } 66 push @result, $count; 67 } 68 print "Output: (" . join(", ", @result) . ")\n"; 69 }