I have written code to calculate the rank of each element of a double[] array in the following code. For an example, if I have double
array {3, 1.3, 2, 3}
then I find the rank as {2, 0, 1, 2}
. It has been calculated as
- 1.3 is least so it got rank 0.
- 2 is the next, so it got rank 1.
- 3 is the next bigger number, so both 3's get rank 2.
public static void main() {
double[] x = {3, 1.3, 2, 3};
System.out.println(Arrays.toString(x) + " - original");
System.out.println("[2, 0, 1, 2] - should be");
System.out.println(Arrays.toString(findRank(x)) + " - our rank");
}
private static int[] findRank(double[] x){
List<Double> lst = new ArrayList<Double>();
int[] rank=new int[x.length]; // maximum length for already unique array
for(double d:x)
if (lst.indexOf(d) == -1) //only unique elements in list
lst.add(d);
Collections.sort(lst);
for(int i=0;i<x.length;i++) {
rank[i]=lst.indexOf(x[i]);
}
return rank;
}
This code gives the following output
[3.0, 1.3, 2.0, 3.0] - original
[2, 0, 1, 2] - should be
[2, 0, 1, 2] - our rank
What I am interested in is the better implementation of above code. How can it be done in a better way?
Edit
This question asks for duplicate elements to be ranked similarly and continuously i.e. {0,1,2,3,...}
without skipping the intermediate rank, which is different from similar but different question
How to find what is the rank of each element in an integer array. That question requires output {3,0,1,3}
if the input {3,1,2,3}
is given. i.e. it handles duplicate elements differently, or it breaks on duplicate values in input. But this is about handling duplicates too and the desired output is {2,0,1,2}
.