• 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: Mac First <email@hidden>
  • Date: Thu, 6 Aug 2009 09:21:28 -0700

Not strictly Cocoa, but a trick I recently incorporated to remove the mod-bias is (email code):

float frand = (random() * 1.0) / (RAND_MAX * 1.0); // gives 0.0-0.99999...
int myRand = frand * 15; // to get a number from 0-14, inclusive.



On Aug 6, 2009, at 9:12 AM, Jeremy Pereira wrote:
That's a bit convoluted.  How about:

srandom(time(NULL));
array = [[NSMutableArray alloc] init];
while ([array count] < 15)
{
	int randomNo = random() % 15 + 1;	// Gives biased results, by the way
	NSNumber numberToAdd = [NSNumber numberWithInt: randomNo];
	if (![array containsObject: numberToAdd])
	{
		[array addObject: numberToAdd];
	}
}


--
Carpe DM -- Seize the Dungeon Master


_______________________________________________

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


  • Follow-Ups:
    • [OT] Re: Generating random numbers
      • From: Alastair Houghton <email@hidden>
References: 
 >Re: Generating random numbers (From: Mahaboob <email@hidden>)
 >Re: Generating random numbers (From: Jeremy Pereira <email@hidden>)

  • Prev by Date: Re: Generating random numbers
  • Next by Date: Re: [iPhone] Webview stringByEvaluatingJavaScriptFromString
  • Previous by thread: Re: Generating random numbers
  • Next by thread: [OT] Re: Generating random numbers
  • Index(es):
    • Date
    • Thread