How to get array elements that appear more than once in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Public Module Module1
    Private Function getMoreThanOnce(ByVal arr As Integer()) As Dictionary(Of Integer, Integer)
        Dim map As Dictionary(Of Integer, Integer) = New Dictionary(Of Integer, Integer)()
        Dim len As Integer = arr.Length

        For i As Integer = 0 To len - 1

            If map.ContainsKey(arr(i)) Then
                Dim count = map(arr(i))
                map.Remove(arr(i))
                map.Add(arr(i), count + 1)
            Else
                map.Add(arr(i), 1)
            End If
        Next

        Return map
    End Function
	Public Sub Main()
		Dim arr As Integer() = {1, 6, 3, 1, 8, 9, 9, 1, 3, 4}
        Dim map As Dictionary(Of Integer, Integer) = New Dictionary(Of Integer, Integer)()
        map = getMoreThanOnce(arr)

        For Each e As KeyValuePair(Of Integer, Integer) In map
            If e.Value > 1 Then
                Console.Write(e.Key & " ")
            End If
        Next
	End Sub
End Module



' run:
'
' 1 3 9
'

 



answered Jul 19, 2020 by avibootz

Related questions

1 answer 148 views
1 answer 144 views
1 answer 168 views
1 answer 172 views
1 answer 227 views
...