How to sum all the unique numbers in array 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}
        
        ' 4 + 7 + 8 + 9 = 28
        
        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:
'
' 28
'

 



answered Jun 1, 2024 by avibootz

Related questions

1 answer 91 views
1 answer 107 views
1 answer 112 views
1 answer 194 views
1 answer 146 views
...