Pages

Wednesday, May 8, 2013

C#: Find the duplicates

//function to display the duplicate values in an Array
public void DisplayArray(ArrayList ary)
        {
//loop through all the elements
            for (int i = 0; i < ary.Count; i++)
            {
                Console.Write(ary[i]+" ");
            }
            Console.WriteLine();
        }
//function to find the duplicate values in an Array
  public void FindDuplicate(ArrayList ary)
        {
//Array list to store all the duplicate values
           ArrayList dup = new ArrayList();
          
            for (int i = 0; i < ary.Count;i++)
            {
                for (int j =i+1; j < ary.Count; j++)
                {
//compare each value with following remaining values
                    if (ary[i].Equals(ary[j]))
                    {
//When duplicate value is found, check
//whether the value not contained in the dup array list
                        if(!dup.Contains(ary[i]))
                        {
//if not contains, then add the value to dup array list
                       dup.Add(ary[i]);
                        }
                    }
                }
            }
            Console.WriteLine("The numbers which duplicates are");
            DisplayArray(dup);
        }


//Input Arraylist values: 4,5,2,5,4,7
 Output: 4 5 2 5 4 7
               The number which duplicates are
                4 5

8 comments:

  1. I'm tгuly enjoying the desіgn and layout of youг blog.
    It's a veey easy οn the eyes wjich mаkes it
    much mοre enjoуablе for me to come heere and visit more often.
    Did yοu hire out a deѕigneг tο create yοur theme?
    Exceptional work!

    Also visit my ωebpaage how to make a martial arts training dummy

    ReplyDelete
    Replies
    1. Thank you so much. I didn't hire a designer for my blog. Did some design changes in blogger default templates to make this layout.

      Delete
  2. You have very helpful solutions! Thank you very much.

    ReplyDelete
  3. hi..

    my array values like this : int[] arr = { 5, 6, 8, 3, 3, 5, 6, 8, 3, 5 };
    i want show duplicate value like this : 5,5,6,8,3,3

    plz solve this

    ReplyDelete
  4. // Find duplicate number and its how many times its occured. Display Duplicate NUMBER & Numer of times its occured
    int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 7, 7, 8, 9, 7, 12, 12 };
    Dictionary duplicateNumbers = new Dictionary();
    int count=1;
    for (int i = 0; i < array.Length; i++)
    {
    count=1;
    if(!duplicateNumbers.ContainsKey(array[i]))
    {
    for (int j = i; j < array.Length-1; j++)
    {
    if (array[i] == array[j+1])
    {
    count++;
    }
    }
    if (count > 1)
    {
    duplicateNumbers.Add(array[i], count);
    }
    }
    }
    foreach (var num in duplicateNumbers)
    {
    Console.WriteLine("Duplicate numbers, NUMBER-{0}, OCCURRENCE- {1}", num.Key, num.Value);
    }
    Console.ReadLine();

    ReplyDelete