Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,919 questions

51,852 answers

573 users

How to sum all the duplicate numbers in an 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, 10, 10}
          
        ' 2 + 2 + 3 + 3 + 1 + 1 + 5 + 5 + 10 + 10 = 42
          
        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 * kvp.Value)
            End If
        Next
  
        Return result
    End Function
End Class
  
  
  
  
' run:
'
' 42
'

 



answered Jun 2, 2024 by avibootz
...