DEV Community

loading...

Discussion on: Daily Challenge #26 - Ranking Position

Collapse
choroba profile image
E. Choroba • Edited

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;
Forem Open with the Forem app