Re: Array of random, non-repeating numbers
Re: Array of random, non-repeating numbers
- Subject: Re: Array of random, non-repeating numbers
- From: Boyd Collier <email@hidden>
- Date: Thu, 13 Jul 2006 17:22:02 -0700
The code that I've pasted in below (and which I take no credit for)
implements, I believe,
the algorithm recommended by Michael Ash for an array of ints. It
should be very easy to
modify for an array of "whatevers."
If someone sees a problem with it, please let me know.
Boyd
/*
* shuffle.c
*
* This function is from http://www.stanford.edu/~blp/writings/clc/
shuffle.html
* Copyright © 2004 Ben Pfaff
*
* BDC made change to add argument to allow new seed to be used for
each call of shuffle
*/
#include <stdlib.h>
#include "shuffle.h"
/* Arrange the N elements of array in random order. Only effective if
N is much smaller than RAND_MAX;
* if this may not be the case, use a better random number generator.
*/
void shuffle(int *array, size_t n, char new_seed)
{
if (new_seed)
sranddev(); // causes a new seed to be used with each run
if (n > 1) {
size_t i;
for (i = 0; i < n - 1; i++) {
size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
int t = array[j];
array[j] = array[i];
array[i] = t;
}
}
}
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]
Transforming this into real code is left as an exercise for the
reader.
If you really do need random numbers, fill an array with the numbers
sequentially and then run the shuffle routine on it.
The other responses in this thread (no offense meant, guys) work and
are unbiased, but are more complex and slower than necessary.
Mike
_______________________________________________
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