Objective-C, "Shuffling" an NSMutuable Array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Sisyphus
    New Member
    • Jul 2010
    • 1

    #1

    Objective-C, "Shuffling" an NSMutuable Array

    I'm not sure, if this is best placed here or in the math/algorithms section.

    I'm trying to sort an array so it is as low discrepancy as possible.

    Code:
    int main()
    {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
        NSMutableArray *myColors;
    
        myColors = [NSMutableArray arrayWithObjects: @"Red", @"Red",@"Red", @"Red", @"Red", @"Green", @"Green", @"Green", @"Blue", @"Blue", @"Blue", @"Yellow", nil];
    
    
        srandom(time(NULL));
        NSUInteger count = [myColors count];
        for (NSUInteger i = 0; i < count; ++i) {
            int nElements = count - i;
            int n = (random() % nElements) + i;
            [myColors exchangeObjectAtIndex:i withObjectAtIndex:n];
             NSLog (@"Element %i = %@", i, [myColors objectAtIndex: i]);
        }
    
    [pool drain]; return 0;
    }
    Which outputs something like:

    Code:
    Element 0 = Blue
         Element 1 = Green
         Element 2 = Yellow
         Element 3 = Blue
         Element 4 = Green
         Element 5 = Red
         Element 6 = Red
         Element 7 = Red
         Element 8 = Blue
         Element 9 = Green
         Element 10 = Red 
         Element 11 = Red
    Which shuffles the array, but it isn't as low discrepancy as I would like mainly due to random number seed.

    Ideally each instance should be as far away from another one of it's kind as possible like:

    Code:
    Red, Green, Red, Blue, Red, Green, Yellow, Red, Blue, Red, Green, Blue
    Any help or suggestions would be great.
Working...