Re: Best way to get a non-repeating random number?
Re: Best way to get a non-repeating random number?
- Subject: Re: Best way to get a non-repeating random number?
- From: Michael Ash <email@hidden>
- Date: Mon, 13 Apr 2009 20:36:27 -0400
On Mon, Apr 13, 2009 at 7:57 PM, Uli Kusterer
<email@hidden> wrote:
> On 14.04.2009, at 01:44, Luca C. wrote:
>>
>> You can put every (unsigned) value you want in there, though in
>> general it's used passing (unsigned)time(NULL) as parameter. This way
>> you'll always get a different int.
>
> No you won't. It's a *random* number generator. The seed simply means you
> get a different sequence of random numbers. However, random really means
> RANDOM. I.e. it's perfectly possible to get the same number three times in a
> row during a sequence. That would still be random.
Technically, I'm pretty sure you will always get a different int.
rand() is a crappy, crappy random number generator, and I would guess
that its algorithm can never return the same number twice in a row.
(If anyone is wondering what the alternatives are, use random() instead.)
> I think it would be best if Eric told us what he's trying to do. For
> example, in some cases, (e.g. sorting) you actually want to build a new list
> and shuffle that by returning random numbers from your sort function. In
> that case, since your list only contains each item once, and your random
> numbers only affect their order, it's perfectly OK to just return a random
> number. You'll still get a shuffled list with each item only once.
I agree that we need to know what the need is. Note that writing a
proper shuffling algorithm is harder than it sounds. More properly,
it's easy, but figuring out whether you got the correct one or one of
the zillions of ones that look correct but aren't is difficult. So
look it up rather than trying to just wing it. The proper algorithm
definitely has no requirement that the random number generator not
return the previously used number.
Mike
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden