The Java implementation gives the score array a method to get the corresponding rank array

  • 2020-04-01 04:04:16
  • OfStack

This article illustrates an example of how a Java implementation can give an array of scores to an array of corresponding rankings. Share with you for your reference. The specific implementation method is as follows:


package test01;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ScoreRank {
  //The output array
  public static void show(int[] s){
    for(int x:s) System.out.print(x);
    System.out.println();
  }
  //place
  public static int[] scoreRank(int[] score) {
    int[] temp = new int[score.length];
    List lis = new ArrayList();
    for(int x:score)   //Add elements (not repeated)
      if(!lis.contains(x)) lis.add(x);
    Collections.sort(lis);    //Sort from small to large
    Collections.reverse(lis);  //Sort from large to small
    for(int i=0;i<score.length;i++) //The index starts at 0
      temp[i] = lis.indexOf(score[i])+1;
      //So: normal ranking = to obtain subscript + 1
    return temp;
  }
  public static void main(String[] args){
    int[] score = {4,2,5,4};  //Ranking,3,1,2 {2}
    int[] rank = scoreRank(score);  //place
    System.out.print(" Original score: ");show(score);
    System.out.print(" Corresponding ranking: ");show(rank);
  }
}

The operation results are as follows:

Original score: 4254
Corresponding ranking: 2312

I hope this article has been helpful to your Java programming.


Related articles: