Monday, 11 February 2013

find least repeated number in an array C#


find least repeated number in an array C#


Suppose array has series of numbers, if user wants to find maximum repeated number in an array.



 static void FindLeastRepeatedNumbers()
        {
            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 min = query.Select((ab, bc) => ab.Count()).Min();

            Console.WriteLine(min);
            foreach (var i in query.Select((ab, bc) => ab).Where((ab, bc) => ab.Count() == min))
                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()).Min();
            3. Then filter the groups which has min 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:  1
30
40
50
12
14

i.e one time repeated numbers in array a

Input:  int[] a = new int[] { 10, 20,  10,30, 30, 20, 40, 40, 12, 14,12,14 };
Output: 2
10
20
30
40
12
14
 i.e 10 ,20,30,40,12,14 numbers repeated 2 times in an array.






Tags:C# find least repeated number in an array, Find repeated numbers in an array,Find duplicate numbers in an array, ,find least repeated number in an array