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 Jul 13, 2006, at 9:39 AM, Michael Ash wrote:

On 7/13/06, Bobby B <email@hidden> wrote:
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.)

Just generate the random playlist directly, don't bother with indexes. Put the tracks into an array, then use the canonical shuffle algorithm which, in pseudocode, is:

for i from 0 to array_length - 2
  random_index = random in [i, array_length - 1]
  swap array[i] with array[random_index]


I did a lot of research on this at one time, long ago...

Your method is *almost* the best way of doing this :)

You can find papers someplace if you search online that show to maximize "randomness" it is sufficient (and necessary) to only loop over the first half of the array.

Statistically speaking, the shuffle is "more" random if you only loop

for i from 0 to array_length / 2

than if you loop over the entire array, and it takes half the time of the full loop as well.


Rob Ross, Lead Software Engineer
E! Networks
email@hidden
---------------------------------------------------
"Beware of he who would deny you access to information, for in his heart he dreams himself your master." -- Commissioner Pravin Lal




_______________________________________________
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
References: 
 >Array of random, non-repeating numbers (From: "Bobby B" <email@hidden>)
 >Re: Array of random, non-repeating numbers (From: "Michael Ash" <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.