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)
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.
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().
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With