Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map a ranking over an array of positive scores

Tags:

ruby

haskell

I have a list of positive scores:

[98.5, 85, 50, 50, 23, 0, 0, 0]

I would like to assign ranks to these scores:

[1, 2, 3, 3, 4, 5, 5, 5]

When two consecutive scores have the same value, they get the same rank. Any idea how to solve this in a functional fashion?

(posted in Haskell and Ruby because I think both solutions would be feasible and can be ported)

like image 826
Guarana Joe Avatar asked Oct 07 '13 20:10

Guarana Joe


People also ask

How do you rank an array of numbers?

Given an array of N integers with duplicates allowed. All elements are ranked from 1 to N in ascending order if they are distinct. If there are say x repeated elements of a particular value then each element should be assigned a rank equal to the arithmetic mean of x consecutive ranks.

How do you rank in JavaScript?

To rank array elements with JavaScript, we can use the sort method. For instance, we write: const arr = [79, 5, 18, 5, 32, 1, 16, 1, 82, 13]; const sorted = arr. slice().

What is rank of an element?

The rank of an element is defined as the distance between the element with the first element of the array when the array is arranged in ascending order. If two or more are same in the array then their rank is also the same as the rank of the first occurrence of the element.


1 Answers

In Ruby:

a = [98.5, 85, 50, 50, 23, 0, 0, 0]
sorted = a.sort.uniq.reverse
a.map{|e| sorted.index(e) + 1}
# => [1, 2, 3, 3, 4, 5, 5, 5]
like image 196
sawa Avatar answered Nov 08 '22 12:11

sawa