Wednesday, June 12, 2013

Given an array of integers,write a function that retrieves unique instances of any duplicates, returning them in a new array. (C#)

Question


Given an array of integers, write a function that retrieves unique instances of any duplicates, returning them in a new array -
[2,1,2,4,3,1,5,1]  should return= [2,1] 
[1,1,1,1,1,1,1,1,1] should return =[1]

Solution


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
namespace Excercises
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] Arr = new int[] { 2, 1, 2, 4, 3, 1, 5, 1 };
            int[] DupArr = findDups(Arr);
            foreach (var i in DupArr)
            {
                if (i != 0)
                {
                    Console.WriteLine(i + ",");
                }
            }
            Console.ReadKey();
        }
        public static int[] findDups(int[] arr)
        {
            Dictionary Dic = new Dictionary();
//Giving an arbitrary array with arbitrary length 10         

  int[] newArr = new int[10];
            foreach (int i in arr)
            {
                if (Dic.ContainsKey(i))
                {
                    Dic[i]++;
                }
                else
                {
                    Dic.Add(i, 1);
                }
            }
            foreach (var v in Dic)
            {
                if (v.Value > 1)
                {
                    newArr[v.Key] = v.Key;
                }
            }
            return newArr;
        }
      
        }
    }


 

No comments: