How to sum all the duplicate numbers in an array only once with VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic
 
Public Class Program
    Public Shared Sub Main(ByVal args As String())
        Dim arr As Integer() = {2, 3, 4, 2, 1, 1, 7, 5, 8, 9, 5, 3, 10, 10}
         
        ' 2 + 2 + 3 + 3 + 1 + 1 + 5 + 5 + 10 + 10 = 42 / 2 = 21
         
        Console.WriteLine(SumUniqueNumbers(arr))
    End Sub
 
    Public Shared Function SumUniqueNumbers(ByVal arr As Integer()) As Integer
        Dim result As Integer = 0
        Dim countAppearances As New Dictionary(Of Integer, Integer)
  
        For Each num As Integer In arr
            If countAppearances.ContainsKey(num) Then
                countAppearances(num) += 1
            Else
                countAppearances(num) = 1
            End If
        Next
 
        For Each kvp As KeyValuePair(Of Integer, Integer) In countAppearances
            If kvp.Value > 1 Then
                result += kvp.Key
            End If
        Next
 
        Return result
    End Function
End Class
 
 
 
 
' run:
'
' 21
'



 



answered Jun 1, 2024 by avibootz
...