Mailing Lists: Apple Mailing Lists

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

Re: 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:
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.