C# find maximum repeated number in an array
Suppose array has series of numbers, if user wants to find maximum repeated number in an array.
static void FindMaximumRepeatedNumbers()
{
int[] a = new int[] { 10, 20, 100, 100, 100, 10, 30, 20, 40, 50, 12, 14 };
var query = from d in a
group d by d into da
select da;
int max = query.Select((ab, bc) => ab.Count()).Max();
Console.WriteLine(max);
foreach (var i in query.Select((ab, bc) => ab).Where((ab, bc) => ab.Count() == max))
Console.WriteLine(i.Key);
}
Note : 1.Group each number by that number, so that duplicates will be under same group.
2.Get Which group has maximum elements
int max = query.Select((ab, bc) => ab.Count()).Max();
3. Then filter the groups which has max count got in step 2.
i.e this process may result more than one element.
Input : int[] a = new int[] { 10, 20, 100, 100, 100, 10, 30, 20, 40, 50, 12, 14 };
Output: 3-100 (i.e 100 repeated 3 times)
Input: int[] a = new int[] { 10, 20, 10, 30, 20, 40, 50, 12, 14 };
Output: 2
10
20
i.e 10 and 20 numbers repeated 2 times in an array.
Tags:C# find maximum repeated number in an array, Find repeated numbers in an array,Find duplicate numbers in an array, ,find least repeated number in an array
No comments:
Post a Comment