The weekly challenge 244 - Task 1: Count Smaller

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-244/#TASK1
 3 #
 4 # Task 1: Count Smaller
 5 # =====================
 6 #
 7 # You are given an array of integers.
 8 #
 9 # Write a script to calculate the number of integers smaller than the integer
10 # at each index.
11 #
12 ## Example 1
13 ##
14 ## Input: @int = (8, 1, 2, 2, 3)
15 ## Output: (4, 0, 1, 1, 3)
16 ##
17 ## For index = 0, count of elements less 8 is 4.
18 ## For index = 1, count of elements less 1 is 0.
19 ## For index = 2, count of elements less 2 is 1.
20 ## For index = 3, count of elements less 2 is 1.
21 ## For index = 4, count of elements less 3 is 3.
22 #
23 ## Example 2
24 ##
25 ## Input: @int = (6, 5, 4, 8)
26 ## Output: (2, 1, 0, 3)
27 #
28 ## Example 3
29 ##
30 ## Input: @int = (2, 2, 2)
31 ## Output: (0, 0, 0)
32 #
33 ############################################################
34 ##
35 ## discussion
36 ##
37 ############################################################
38 #
39 # Straight forward, for each element of the array, walk the whole array,
40 # checking each element for its size compared to the current one.
41 
42 use strict;
43 use warnings;
44 
45 count_smaller(8, 1, 2, 2, 3);
46 count_smaller(6, 5, 4, 8);
47 count_smaller(2, 2, 2);
48 
49 sub count_smaller {
50    my @int = @_;
51    print "Input: (" . join(", ", @int) . ")\n";
52    my @result = ();
53    foreach my $elem (@int) {
54       my $smaller = 0;
55       foreach my $elem2 (@int) {
56          $smaller++ if $elem2 < $elem;
57       }
58       push @result, $smaller;
59    }
60    print "Output: (" . join(", ", @result) . ")\n";
61 }
62