I want to find out the kth most common element from an array and I was able to find most common element but I don't know how to find kth common one.
I tried like:
private static int KthCommonElement(int[] a, int k)
{
var counts = new Dictionary<int, int>();
foreach (int number in a)
{
int count;
counts.TryGetValue(number, out count);
count++;
//Automatically replaces the entry if it exists;
//no need to use 'Contains'
counts[number] = count;
}
int mostCommonNumber = 0, occurrences = 0;
foreach (var pair in counts)
{
if (pair.Value > occurrences)
{
occurrences = pair.Value;
mostCommonNumber = pair.Key;
}
}
Console.WriteLine("The most common number is {0} and it appears {1} times", mostCommonNumber, occurrences);
return mostCommonNumber;
}
You can sort the elements by their occurence and take the kth element:
int[] orderedByOccurence = a.OrderByDescending(i => counts[i]).ToArray();
if (orderedByOccurence.Length > k)
Console.WriteLine($"{k}th most common element: {orderedByOccurence[k]});
But as Adam pointed out in the comments, you can shorten your code by using GroupBy
:
private static int KthCommonElement(int[] a, int k)
{
if (a == null) throw new ArgumentNullException(nameof(a));
if (a.Length == 0) throw new ArgumentException();
if (k < 0) throw new ArgumentOutOfRangeException();
var ordered = a.GroupBy(i => i, (i, o) => new { Value = i, Occurences = o.Count()})
.OrderByDescending(g => g.Occurences)
.ToArray();
int index = k;
if (ordered.Length <= index)
{
// there are less than k distinct values in the source array
// so add error handling here, either throw an exception or
// return a "magic value" that indicates an error or return the last element
index = ordered.Length - 1;
}
var result = ordered[index];
Console.WriteLine("The most common number is {0} and it appears {1} times",
result.Value, result.Occurrences);
return result.Value;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With