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,926 questions

51,859 answers

573 users

How to sum all the duplicate numbers in an array only once with C#

1 Answer

0 votes
using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main(string[] args)
    {
        int[] arr = { 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));
    }

    public static int SumUniqueNumbers(int[] arr) {
        int result = 0;
        HashSet<int> uniqueNumbers = new HashSet<int>();

        foreach (int num in arr) {
            if (!uniqueNumbers.Contains(num)) {
                if (arr.Count(x => x == num) > 1) {
                    result += num;
                    uniqueNumbers.Add(num);
                }
            }
        }

        return result;
    }
}


 
/*
run:
   
21
   
*/

 



answered Jun 1, 2024 by avibootz

Related questions

1 answer 77 views
1 answer 134 views
1 answer 110 views
1 answer 91 views
1 answer 133 views
...