Re: Array of random, non-repeating numbers
Re: Array of random, non-repeating numbers
- Subject: Re: Array of random, non-repeating numbers
- From: Matt Neuburg <email@hidden>
- Date: Thu, 13 Jul 2006 09:10:26 -0700
- Thread-topic: Array of random, non-repeating numbers
On Thu, 13 Jul 2006 10:46:20 -0400, "Bobby B" <email@hidden> said:
>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
Wait - if there are to be X numbers and between 0 and X and not repeating,
then you are merely saying you want to shuffle a deck consisting of the
number 0 thru X. So just start with such a deck and extract cards from it
one at a time, randomly:
NSMutableArray* tempDeck = [NSMutableArray arrayWithCapacity: [cards
count]];
int i,u;
u = [cards count] - 1; // last card will be xferred manually
for (i=0; i<u; i++) {
int k = random() % ([cards count]-1);
[tempDeck addObject: [cards objectAtIndex: k]];
[cards removeObjectAtIndex: k];
}
[tempDeck addObject: [cards objectAtIndex: 0]]; // last card
Here, "cards" is a "deck" consisting of the numbers 0 thru X. m.
--
matt neuburg, phd = email@hidden, <http://www.tidbits.com/matt/>
A fool + a tool + an autorelease pool = cool!
AppleScript: the Definitive Guide - Second Edition!
<http://www.amazon.com/gp/product/0596102119>
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden