-
Notifications
You must be signed in to change notification settings - Fork 320
/
ch-2.pl
executable file
·78 lines (62 loc) · 2.15 KB
/
ch-2.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/perl
use strict;
use warnings;
use English;
################################################################################
# Begin main execution
################################################################################
my @integer_lists = (
[ 1, 1, 2, 2, 2, 3 ],
[ 2, 3, 1, 3, 2 ],
[ -1, 1, -6, 4, 5, -6, 1, 4, 1 ]
);
print("\n");
foreach my $integer_list (@integer_lists){
printf(
"Input: \@ints = (%s)\nOuput: (%s)\n\n",
join(", ", @{$integer_list}),
join(", ", frequency_sort(@{$integer_list}))
);
}
exit(0);
################################################################################
# End main execution; subroutines follow
################################################################################
################################################################################
# Sort a given array of integers in ascending order based on the frequency with
# which each appears in the array. If multiple integer values have the same
# frequency, those values will be sorted amongst each other in descending
# order.
# Takes one argument:
# * The list of integers to examine (e.g. (-1, 1, -6, 4, 5, -6, 1, 4, 1) )
# Returns:
# * A list of the provided integers, sorted in the manner described above (e.g.
# (5, -1, 4, 4, -6, -6, 1, 1, 1) )
################################################################################
sub frequency_sort{
my %buckets;
while(@ARG){
my $int = shift();
# Remove each int from the arg list and add it
# to its bucket; this will autovivify if the
# int hasn't been seen before
push(@{$buckets{$int}}, $int);
}
return(
# Make one list out of the contents of the
# buckets once they're sorted in the specified
# order
map(
@{$buckets{$_}},
sort(
{
scalar(@{$buckets{$a}}) == scalar(@{$buckets{$b}}) ?
($b <=> $a)
:
(scalar(@{$buckets{$a}}) <=> scalar(@{$buckets{$b}}));
}
keys(%buckets)
)
)
);
}