Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Array of random, non-repeating numbers



Hey guys,

I'm trying to write a way to generate a random array of X numbers, and
the numbers need to be between 0 and X, and not be repeating (its for
generating a random playlist.)

I've come up with the following, which works perfectly.  I'm just
curious if there is a "much better way" to do this?  (Oh, and I want
the numbers to be strings in the array)..

maxSongs = [[musicViewSongArrayController
valueForKeyPath:@"arrangedObjects.@count"] intValue];
		
		NSMutableArray *randomArray = [NSMutableArray array];
		
		int i = 0;
		while (i < maxSongs)
		{
			[randomArray addObject:@"-"];
			i = i + 1;
		}
		
		BOOL finished = NO;
		int completed = 0;
		while (finished == NO)
		{
			int randomIndex = (random() % maxSongs);
			NSLog(@"%u", randomIndex);
			if (([[randomArray objectAtIndex:completed] isEqualToString:@"-"]) &&
				(!([randomArray containsObject:[NSString stringWithFormat:@"%u",
randomIndex]])))
			{
				[randomArray replaceObjectAtIndex: completed withObject:[NSString
stringWithFormat:@"%u", randomIndex]];
				NSLog(@"%u - %u", randomIndex, completed);
				completed = completed + 1;
			}
			
			if (!([randomArray containsObject:@"-"])) finished = YES;
		}
		NSLog(@"%@", randomArray);
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/email@hidden

This email sent to email@hidden


Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.