Link to home
Start Free TrialLog in
Avatar of barnwillyb
barnwillyb

asked on

How do I remove duplicates in NSMutableArray

I am not sure how to remove duplicate numbers in a NSMutableArray and whether to remove them before sorting or not.  And is there an easy way to remove duplicate numbers before they are even added to the array?  This is not homework.
#import <Foundation/Foundation.h>
 
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc]init];
    
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
    [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [numberFormatter setFormat:@"00"];
    NSString *myNumberString;
    NSMutableArray *array;
    int i;
    NSNumber *newNumber;
    NSNumber *numbersToPrint;
 
    printf ("\n");
    array = [[NSMutableArray alloc]init];
    // Initialize the random number generator.
    srandom(time(NULL));
    for (i = 0; i < 6; i++) {
        newNumber = [[NSNumber alloc]initWithInt:random() % 55 + 1];
        myNumberString = [numberFormatter stringFromNumber:newNumber];
        [array addObject:myNumberString];
        [array sortUsingSelector:@selector(compare:)];
        [newNumber release];
    }
 
    // Using NSLog
    for (i = 0; i < 6; i++) {
        numbersToPrint = [array objectAtIndex:i];
        NSLog(@"The number at index %d is %@.", i, numbersToPrint);
    }
 
    [array release];
    [pool drain];
 
    return 0;
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of AJVienna
AJVienna

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of romanm
romanm

Use insertion sort, find the location to insert using a binary search,

insertion loop would look like this:

start = 0
end = array count
if array empty
  add item, go to next item.
1. search position = start + ((end - start) / 2), round down
2. if insert item equals item at search position, exit search and go to next item to insert
3. else if insert item is greater than the item at search position,
    if search position equals end
       insert at end
    else
       start = search position + 1
4. else
    if search position equals start
       insert before start
    else
       end = search position
5. if start equals end
    insert item after start.
6. else
    go to 1

so you get the insertion of a NSMutableSet, unique values and sorted, and save the need to copy.
@romanm, the binary search is only useful if there are more elements. With only 6 random numbers it will cause more overhead than benefit.
how will it cause more overhead then using a set?
a set uses a binary search too, a set has a red-black tree balancing each time you insert, (I am talking windows but I think same applies).

proposed algorithm is a shortcut over using a set, count of elements is irrelevent.