Php ranking system and get the average of all duplicate rank

Viewed 26

I have this application that will automatically rank the candidates based on their score.

[
    {"candidate":"12","rank":1},
    {"candidate":"11","rank":2},
    {"candidate":"10","rank":3},
    {"candidate":"9","rank":4},
    {"candidate":"8","rank":4},
    {"candidate":"7","rank":6},
    {"candidate":"6","rank":7},
    {"candidate":"5","rank":8},
    {"candidate":"4","rank":9},
    {"candidate":"3","rank":9},
    {"candidate":"2","rank":11},
    {"candidate":"1","rank":12}
]

Now, as you can see, candidates 4 and 9 got the same rank:

{"candidate":"9","rank":4}, // this supposed to rank 4
{"candidate":"8","rank":4}, // this supposed to rank 5
{"candidate":"4","rank":9}, // this supposed to rank 9
{"candidate":"3","rank":9}, // this supposed to rank 10

Calculation: (first duplicate)

4 + 5 = 9
9 / 2 (number of duplicate rank) = 4.5

(second duplicate)

9 + 9 = 18
18 / 2(number of duplicate rank) = 9

EDIT - shouldn't this be

9 + 10 = 19
19 / 2(number of duplicate rank) = 9.5

Expected Output:

  [
        {"candidate":"12","rank":1},
        {"candidate":"11","rank":2},
        {"candidate":"10","rank":3},
        {"candidate":"9","rank":4.5},
        {"candidate":"8","rank":4.5},
        {"candidate":"7","rank":6},
        {"candidate":"6","rank":7},
        {"candidate":"5","rank":8},
        {"candidate":"4","rank":9.5},
        {"candidate":"3","rank":9.5},
        {"candidate":"2","rank":11},
        {"candidate":"1","rank":12}
    ]
 

Note: This is just a simple scenario and ranking will change anytime.

0 Answers
Related