Thread: How do I remove duplicate entries in an array?

  1. #1
    Unregistered
    Guest

    Unhappy How do I remove duplicate entries in an array?

    I am new to programming and to C programming itself....I was wondering how do I go about removing duplicate entries in an array, in most simplest code?
    for example:
    a[7] = {1,2,5,1,2,3,3}

    and I want to remove duplicates and store new entries in a anew array, say b[] that would have unique 1,2,5,3 entries only.... Please help me out I am lost here....
    :-(

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    The simplest way is to copy the first occurance of each number into a second array. Every time you want to move another element, loop through the second array and check that the element doesn't already exist there. If it does then skip it and move on. Here's one way this could be implemented:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    typedef int bool_t;
    
    int main ( void )
    {
      int a[7] = {1,2,5,1,2,3,3};
      /* The value -1 was used here as a placeholder.
      ** It means that no valid value is here. Just
      ** make sure that the placeholder isn't in the
      ** first array. ;)
      */
      int b[7] = {-1,-1,-1,-1,-1,-1,-1};
      int aIndex, bIndex = 0, check;
      bool_t moved;
    
      for ( aIndex = 0; aIndex < 7; aIndex++ ) {
        moved = 0;
        for ( check = 0; check < aIndex; check++ ) {
          if ( a[aIndex] == b[check] )
            moved = 1;
        }
        if ( !moved )
          b[bIndex++] = a[aIndex];
      }
    
      for ( check = 0; check < 7; check++ ) {
        printf ( "%d\t", a[check] );
        if ( b[check] != -1 )
          printf ( "%d\n", b[check] );
        else
          printf ( "\n" );
      }
      return EXIT_SUCCESS;
    }
    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. [question]Analyzing data in a two-dimensional array
    By burbose in forum C Programming
    Replies: 2
    Last Post: 06-13-2005, 07:31 AM
  2. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  3. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  4. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM
  5. Array Program
    By emmx in forum C Programming
    Replies: 3
    Last Post: 08-31-2003, 12:44 AM