Skip to main content

Find the frequency of each element in an array in vb.net

Vb program for Find the frequency of each element in an array. Here more information.

' Include namespace system
Imports System
Imports System.Collections.Generic
Imports System.Collections
'  Vb.net program
'  Count frequency of each element in array 

public Class Occurrence 

    '  Function which is display list elements
    Public Shared Sub display(ByVal arr As Integer())
        Dim i As Integer = 0
        While i < arr.Length
            Console.Write("   " + arr(i).ToString())
        i += 1
        End While
        Console.Write(""& vbLf &"")
    
    End Sub
    '  Count occurrence of given list
    
    Public Shared Sub frequency(ByVal arr As Integer())
        '  Display given list
        display(arr)
        '  Create a empty map
        Dim map As Dictionary(Of Integer, Integer) = 
          New Dictionary(Of Integer, Integer)()
        Dim i As Integer = 0
        While i < arr.Length

            if (map.ContainsKey(arr(i))) Then 
                '  When key exists then update value
                map(arr(i)) = map(arr(i)) + 1
            Else 
                '  Add new element
                map(arr(i)) = 1
            End IF

        i += 1
        End While
        Console.WriteLine("  Occurrence ")
        '   Display calculated result
        For Each entry As KeyValuePair(Of Integer,Integer) In map
            Console.WriteLine("  " + 
                              entry.Key.ToString() + "  :  " + 
                              entry.Value.ToString())
        Next
    
    End Sub
    
    Public Shared Sub Main(ByVal args As String())
        '  Array element
        Dim arr As Integer() = 
        {1, 3, 2, 1, 4, 2, 7, 9, 1, 3, 3, 4, 7}
        frequency(arr)
    
    End Sub

End Class

Output

   1   3   2   1   4   2   7   9   1   3   3   4   7
  Occurrence
  1  :  3
  3  :  3
  2  :  2
  4  :  2
  7  :  2
  9  :  1




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment