Sponsored
This approach involves sorting the scores in descending order, then iteratively assigning ranks to each score while handling ties appropriately. This can be efficiently achieved using a sorting algorithm followed by a traversal to assign ranks. By maintaining an index while sorting, we can assign ranks directly to the original scores.
Time Complexity: O(n log n) due to the sorting operation.
Space Complexity: O(1), only a fixed amount of additional memory is used for sorting.
1const scores = [
2 { id: 1, score: 3.50 },
3 { id: 2, score: 3.65 },
4 { id: 3, score: 4.00 },
5 { id: 4, score: 3.85 },
6 { id: 5, score: 4.00 },
7 { id: 6, score: 3.65 }
8];
9
10scores.sort((a, b) => b.score - a.score);
11
12let rank = 1;
13for (let i = 0; i < scores.length; i++) {
14 if (i === 0 || scores[i].score !== scores[i - 1].score) {
15 rank = i + 1;
16 }
17 console.log(`Score: ${scores[i].score.toFixed(2)}, Rank: ${rank}`);
18}
JavaScript takes advantage of the sort function on arrays, providing a compare function to sort scores in descending order. Ranks are then assigned by iterating over the sorted array, with efficient handling of ties using simple conditionals.
This approach uses a bucket sort strategy, particularly efficient when scores have a limited range of decimal places. This reduces the complexity substantially in scenarios where HTTP (High Throughput Processing) is required. Counting occurrences of each score allows direct assignment of ranks in descending order of scores efficiently.
Time Complexity: O(n + k), where n is the number of scores, and k is the number of buckets (constant in this case).
Space Complexity: O(k), which is fixed and depends on BUCKET_COUNT.
1using System.Collections.Generic;
using System.Linq;
class Program {
static Dictionary<int, int> CountScores(double[] scores, double bucketSize) {
var countMap = new Dictionary<int, int>();
foreach (var score in scores) {
int index = (int)(score / bucketSize);
if (countMap.ContainsKey(index)) {
countMap[index]++;
} else {
countMap[index] = 1;
}
}
return countMap;
}
static void AssignRanks(Dictionary<int, int> countMap, double bucketSize) {
var sortedKeys = countMap.Keys.OrderByDescending(key => key).ToList();
int rank = 1;
foreach (var index in sortedKeys) {
double score = index * bucketSize;
for (int i = 0; i < countMap[index]; i++) {
Console.WriteLine($"Score: {score:F2}, Rank: {rank}");
}
rank += countMap[index];
}
}
static void Main() {
double[] scores = { 3.50, 3.65, 4.00, 3.85, 4.00, 3.65 };
double bucketSize = 0.01;
var countMap = CountScores(scores, bucketSize);
AssignRanks(countMap, bucketSize);
}
}
C# utilizes a Dictionary to count occurrences of each score rounded by bucket size. Linq is then used to sort these keys in descending order. Finally, the scores are printed with their corresponding ranks, adjusting for score duplication.