How to rank elements of an array in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;
using System.Linq;

/*
    This program demonstrates how to compute "competition ranking"
    for an array of integers in C#.

    Competition Ranking Rules:
    --------------------------
    - Highest value gets rank 1
    - Equal values share the same rank
    - Next rank increases by the number of equal values

    Example:
        Values: 88, 4, 19, 4, 1, 31, 14, 1, 93, 17
        Ranks:   2, 7,  4, 7, 9,  3,  6, 9,  1,  5
*/

class Program
{
    /*
        FUNCTION: GetRanks
        -------------------
        Computes competition-style ranks for a list of integers.

        Steps:
        1. Make a sorted copy of the list (descending)
        2. Assign ranks to each unique value
        3. Build a rank list matching the original order
    */
    static List<int> GetRanks(List<int> arr)
    {
        // Step 1: Create a sorted copy (descending)
        List<int> sorted = arr.OrderByDescending(x => x).ToList();

        // Step 2: Map each unique value to its rank
        Dictionary<int, int> rankMap = new Dictionary<int, int>();
        int rank = 1;

        foreach (int value in sorted) {
            // Assign rank only once per unique value
            if (!rankMap.ContainsKey(value)) {
                rankMap[value] = rank;
            }

            rank++; // next rank position
        }

        // Step 3: Build ranking list in original order
        List<int> result = new List<int>();
        foreach (int value in arr) {
            result.Add(rankMap[value]);
        }

        return result;
    }

    /*
        FUNCTION: PrintRanking
        -----------------------
        Prints the original list and its ranking.
    */
    static void PrintRanking(List<int> arr, List<int> ranks)
    {
        Console.Write("Original array: [ ");
        foreach (int v in arr)
            Console.Write(v + " ");
        Console.WriteLine("]");

        Console.Write("Ranking array : [ ");
        foreach (int r in ranks)
            Console.Write(r + " ");
        Console.WriteLine("]");
    }

    // MAIN PROGRAM
    // ---------------------------------------------
    static void Main()
    {
        List<int> array = new List<int> { 88, 4, 19, 4, 1, 31, 14, 1, 93, 17 };

        // Compute ranks
        List<int> rankingArray = GetRanks(array);

        PrintRanking(array, rankingArray);
    }
}


/*
run:

Original array: [ 88 4 19 4 1 31 14 1 93 17 ]
Ranking array : [ 2 7 4 7 9 3 6 9 1 5 ]

*/

 



answered Jun 21 by avibootz
...