Sunday, January 20, 2013

How to detect repeated or duplicate elements in an integer array? Dictionary Implementations (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DictionaryImplementation
{
class Program
{
static void Main(string[] args)
{

//How to detect repeated or duplicate elements in an integer array?

int[] Nums = { 1, 3, 6, 8, 2, 6, 13, 9, 3, 6 };

duplicates(Nums);
Console.ReadKey();


}

public static void duplicates(int[] input)
{
Dictionary Dic = new Dictionary();

for (int i =0; i if (input.Length != 0 || input.Length != 1)
{
//if there is a key present, then increase the count. Key is the input number, value is the count


if (Dic.ContainsKey(input[i]))
Dic[input[i]]++;

else
{

//if key is not present, add the key to the dictionary and the count is 1

Dic.Add(input[i], 1);
}
}

foreach (var d in Dic)
{
//iterate through the dictionary key and value.

Console.WriteLine("the number {0} occurs {1} times", d.Key, d.Value);
}

}

}
}

No comments: