Re: Generating random numbers
Re: Generating random numbers
- Subject: Re: Generating random numbers
- From: Citizen <email@hidden>
- Date: Wed, 5 Aug 2009 12:09:22 +0100
On 5 Aug 2009, at 11:44, Mahaboob wrote:
I need to produce 15 random numbers between 1 to 16 without
repeating any
number. I used the code like
int i,j;
for(i=0;i<15;i++){
j =random() % 15 +1;
NSLog(@"No: %d => %d \n",i,j);
srandom(time(NULL)+i);
}
But some numbers are repeating.
How can I do it without repeating the numbers?
This isn't really a Cocoa question.
One solution is to add each item to an array. Add an inner loop that
loops through that array each time you generate a new random number to
see if it is already been used, if not then print it - and add it to
the array.
This is probably not the most efficient solution, but should work well
for your requirements.
srandom should probably be called outside your loop. There is no point
initializing the random number generator multiple times like this.
Hope that helps.
Dave
------
David Kennedy (http://www.zenopolis.com)
_______________________________________________
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