• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Generating random numbers
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Generating random numbers


  • Subject: Re: Generating random numbers
  • From: Ken Thomases <email@hidden>
  • Date: Wed, 5 Aug 2009 05:55:25 -0500

On Aug 5, 2009, at 5:44 AM, 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?

Hmm. When using random number generators, you typically do not seed the generator repeatedly. You seed it once and then have it generate numbers repeatedly.


Next, "random() % 15 + 1" will give values from 1 to 15, not 1 to 16.

Lastly, random number sequences may repeat. That's an inherent property of randomness.

What you really want is known as a shuffle. You want the numbers from 1 to 15 (or is it 16?) shuffled into a random order. http://en.wikipedia.org/wiki/Shuffling#Shuffling_algorithms

Regards,
Ken

_______________________________________________

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


References: 
 >Generating random numbers (From: Mahaboob <email@hidden>)

  • Prev by Date: Re: Generating random numbers
  • Next by Date: Re: Generating random numbers
  • Previous by thread: Re: Generating random numbers
  • Next by thread: Re: Generating random numbers
  • Index(es):
    • Date
    • Thread