in reply to Sorting and ranking
Use a HoA keyed by the value and sort that in descending order, incrementing rank for each key. Uncomment the Data::Dumper lines to see the structure of the HoA. The code
use strict; use warnings; use 5.022; # use Data::Dumper; my %data = ( car => 180, motorcycle => 150, skate => 150, bird => 120, ); my %byValue; push @{ $byValue{ $data{ $_ } } }, $_ for keys %data; # print Data::Dumper->Dumpxs( [ \ %byValue ], [ qw{ *byValue } ] ); my $rank; for my $descVal ( sort { $b <=> $a } keys %byValue ) { $rank ++; say qq{$rank - $_} for sort @{ $byValue{ $descVal } }; }
The output.
1 - car 2 - motorcycle 2 - skate 3 - bird
I hope this is helpful.
Update: An updated script to show the difference between "rank" and "place" as in "Fred and Mary were placed 3rd equal."
use strict; use warnings; use 5.022; my %data = ( car => 180, tortoise => 90, concorde => 300, motorcycle => 150, bird => 120, skate => 150, pedestrian => 100, rocket => 300, aeroplane => 210, unicycle => 175, sheep => 100, frog => 120, cow => 110, bus => 150, ); my %byValue; push @{ $byValue{ $data{ $_ } } }, $_ for keys %data; say q{Rank Place Item}; my $rank = 0; my $place = 1; for my $descVal ( sort { $b <=> $a } keys %byValue ) { $rank ++; my $count = scalar @{ $byValue{ $descVal } }; my $eq = $count > 1 ? q{=} : q{ }; printf qq{%3d%5d%1s %s\n}, $rank, $place, $eq, $_ for sort @{ $byValue{ $descVal } }; $place += $count; }
The output.
Rank Place Item 1 1= concorde 1 1= rocket 2 3 aeroplane 3 4 car 4 5 unicycle 5 6= bus 5 6= motorcycle 5 6= skate 6 9= bird 6 9= frog 7 11 cow 8 12= pedestrian 8 12= sheep 9 14 tortoise
Cheers,
JohnGG
|
|---|