Jack Pettersson
Jack Pettersson

Reputation: 1666

Perl: How do you sort and convert, items of an array by number of appearances

first post here (and program that i'm trying to make for that matter!).

I'm not sure if this is even possible, but what i want to do is sort my array by how many times the items inside them appear and then translate the amount of times they appear into numbers.

From this:

@array = (blue, red, blue, green, red, blue)

I want to create this:

@array1 = (blue, blue, blue, red, red, green)

and then from that i want to create this:

@array2 = (3, 2, 1)

Thanks in advance!

Upvotes: 2

Views: 105

Answers (1)

mpapec
mpapec

Reputation: 50637

my @array = qw(blue red blue green red blue);

my %seen;
$seen{$_}++ for @array;

my @array1 = sort { $seen{$b} <=> $seen{$a} } @array;
my @array2 = sort { $b <=> $a } values %seen;

%seen is hash which holds frequency/count for each color:

   blue  => 3,
   red   => 2,
   green => 1,

First sort uses hash as count look up in order to sort colors in descending order regarding number of corresponding occurrences. Second sort is plain numerical descending sort for hash values (1,2,3).

Upvotes: 2

Related Questions