Skip to content

Instantly share code, notes, and snippets.

@codedjinn
Created March 10, 2021 16:47
Show Gist options
  • Select an option

  • Save codedjinn/5a1842314a463242257707dfcd48bbdc to your computer and use it in GitHub Desktop.

Select an option

Save codedjinn/5a1842314a463242257707dfcd48bbdc to your computer and use it in GitHub Desktop.
static int[] GetRanks_Sort(int[] input)
{
int[] sorted = new int[input.Length];
Array.Copy(input, sorted, input.Length);
Array.Sort(sorted);
var ranked = new Dictionary<int, int>();
int rank = 1;
int number = sorted[0];
ranked.Add(sorted[0], rank);
for (int i = 1; i < sorted.Length; i++)
{
if (sorted[i] != number)
{
number = sorted[i];
ranked.Add(number, i + 1);
}
}
int[] result = new int[input.Length];
for (int i = 0; i < input.Length; i++)
{
result[i] = ranked[input[i]];
}
return result;
}
static int[] GetRanks_Hash(int[] input)
{
var frequencies = new Dictionary<int, int>();
for (int i = 0; i < input.Length; i++)
{
if (frequencies.ContainsKey(input[i]))
{
frequencies[input[i]]++;
}
else
{
frequencies.Add(input[i], 1);
}
}
int[] sorted = new int[frequencies.Count];
frequencies.Keys.CopyTo(sorted, 0);
Array.Sort(sorted);
var ranks = new Dictionary<int, int>();
var rank = 1;
ranks.Add(sorted[0], 1);
for (int i = 1; i < sorted.Length; i++)
{
int newRank = rank + frequencies[sorted[i - 1]];
ranks.Add(sorted[i], newRank);
rank = newRank;
}
int[] result = new int[input.Length];
for (int i = 0; i < input.Length; i++)
{
result[i] = ranks[input[i]];
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment