The weekly challenge 337 - Task 1: Smaller Than Current
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-337/#TASK1 3 # 4 # Task 1: Smaller Than Current 5 # ============================ 6 # 7 # You are given an array of numbers, @num1. 8 # 9 # Write a script to return an array, @num2, where $num2[i] is the count of all 10 # numbers less than or equal to $num1[i]. 11 # 12 ## Example 1 13 ## 14 ## Input: @num1 = (6, 5, 4, 8) 15 ## Output: (2, 1, 0, 3) 16 ## 17 ## index 0: numbers <= 6 are 5, 4 => 2 18 ## index 1: numbers <= 5 are 4 => 1 19 ## index 2: numbers <= 4, none => 0 20 ## index 3: numbers <= 8 are 6, 5, 4 => 3 21 # 22 # 23 ## Example 2 24 ## 25 ## Input: @num1 = (7, 7, 7, 7) 26 ## Output: (3, 3, 3, 3) 27 # 28 # 29 ## Example 3 30 ## 31 ## Input: @num1 = (5, 4, 3, 2, 1) 32 ## Output: (4, 3, 2, 1, 0) 33 # 34 # 35 ## Example 4 36 ## 37 ## Input: @num1 = (-1, 0, 3, -2, 1) 38 ## Output: (1, 2, 4, 0, 3) 39 # 40 # 41 ## Example 5 42 ## 43 ## Input: @num1 = (0, 1, 1, 2, 0) 44 ## Output: (1, 3, 3, 4, 1) 45 # 46 ############################################################ 47 ## 48 ## discussion 49 ## 50 ############################################################ 51 # 52 # First, we generate a descendingly sorted copy of @num1. Then, for 53 # each element of @num1, we search for the first element inside 54 # the sorted copy that is equal to the current number. From there we can 55 # calculate the number of elements that are less than or equal to the 56 # number by substracting the current index from the index of the last 57 # element in the sorted list. 58 59 use v5.36; 60 use Data::Dumper; 61 62 smaller_than_current(6, 5, 4, 8); 63 smaller_than_current(7, 7, 7, 7); 64 smaller_than_current(5, 4, 3, 2, 1); 65 smaller_than_current(-1, 0, 3, -2, 1); 66 smaller_than_current(0, 1, 1, 2, 0); 67 68 sub smaller_than_current( @num1 ) { 69 say "Input: (" . join(", ", @num1) . ")"; 70 my @numsorted = sort { $b <=> $a } @num1; 71 my @num2 = (); 72 foreach my $n (@num1) { 73 foreach my $i (0..$#numsorted) { 74 if($n == $numsorted[$i]) { 75 push @num2, $#numsorted-$i; 76 last; 77 } 78 } 79 } 80 81 say "Output: (" . join(", ", @num2) . ")"; 82 } 83