The weekly challenge 233 - Task 2: Frequency Sort
1 #!/usr/bin/perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-233/#TASK2 3 # 4 # Task 2: Frequency Sort 5 # ====================== 6 # 7 # You are given an array of integers. 8 # 9 # Write a script to sort the given array in increasing order based on the 10 # frequency of the values. If multiple values have the same frequency then sort 11 # them in decreasing order. 12 # 13 ## Example 1 14 ## 15 ## Input: @ints = (1,1,2,2,2,3) 16 ## Ouput: (3,1,1,2,2,2) 17 ## 18 ## '3' has a frequency of 1 19 ## '1' has a frequency of 2 20 ## '2' has a frequency of 3 21 # 22 ## Example 2 23 ## 24 ## Input: @ints = (2,3,1,3,2) 25 ## Ouput: (1,3,3,2,2) 26 ## 27 ## '2' and '3' both have a frequency of 2, so they are sorted in decreasing order. 28 # 29 ## Example 3 30 ## 31 ## Input: @ints = (-1,1,-6,4,5,-6,1,4,1) 32 ## Ouput: (5,-1,4,4,-6,-6,1,1,1) 33 # 34 ############################################################ 35 ## 36 ## discussion 37 ## 38 ############################################################ 39 # 40 # Calculate the frequencies for all elements in the array 41 # Then sort by frequency first and then value second 42 43 use strict; 44 use warnings; 45 46 frequency_sort(1,1,2,2,2,3); 47 frequency_sort(2,3,1,3,2); 48 frequency_sort(-1,1,-6,4,5,-6,1,4,1); 49 50 sub frequency_sort { 51 my @ints = @_; 52 print "Input: (" . join(", ", @ints) . ")\n"; 53 my %frequencies; 54 foreach my $int (@ints) { 55 $frequencies{$int}++; 56 } 57 print "Output: (" . join(", ", sort { $frequencies{$a} <=> $frequencies{$b} || $b <=> $a } @ints) . ")\n"; 58 }