Monday, 11 February 2013

find least repeated number in an array VB.NET


find least repeated number in an array VB.NET using LINQ


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



Private Shared Sub FindLeastRepeatedNumbers()
    Dim a As Integer() = New Integer() {10, 20, 100, 100, 100, 10, _
        30, 20, 40, 50, 12, 14}

    Dim query =


    Dim min As Integer = query.[Select](Function(ab, bc) ab.Count()).Min()

    Console.WriteLine(min)
    For Each i As var In query.[Select](Function(ab, bc) ab).Where(Function(ab, bc) ab.Count() = min)
        Console.WriteLine(i.Key)
    Next
End Sub

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:VB.NET 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