Going functional in Perl:
#!/usr/bin/perl use warnings; use strict; sub rank { my ($in) = @_; my $i = 1; my $same = 0; my $last = 'INF'; [ map { if ($_->{points} == $last) { ++$same; } else { $i += $same; $last = $_->{points}; $same = 1; } +{ %$_, position => $i } } sort { $b->{points} <=> $a->{points} || $a->{name} cmp $b->{name} } @$in ] } my $input = [ { name => "John", points => 100 }, { name => "Bob", points => 130 }, { name => "Mary", points => 120 }, { name => "Kate", points => 120 }]; my $expected = [ { name => "Bob", points => 130, position => 1 }, { name => "Kate", points => 120, position => 2 }, { name => "Mary", points => 120, position => 2 }, { name => "John", points => 100, position => 4 }]; use Test::More tests => 1; is_deeply rank($input), $expected;
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Going functional in Perl: