Advertise Mobile SDKs Books Events Forum News Social Networking Support Us
Follow @iphonedevsdk on Twitter

Mockup & CodeGen, iPhone & iPad
($9.99)

Make your own iPhone apps
and run them live!
(free)

Manu
($0.99)

Want your application or service advertised on iPhone Dev SDK?

Go Back   iPhone Dev SDK Forum

View Single Post
Old 01-11-2009, 02:23 AM   #5 (permalink)
smasher
Senior Member
iPhone Dev SDK Supporter
 
smasher's Avatar
 
Join Date: Jul 2008
Location: San Mateo, CA (San Fran)
Posts: 3,858
Default

It's always the same result, or sometimes you get the same result twice in a row? Getting duplicates in a row is not surprising - if you flip a coin 30 times, you'll see a lot of HeadHeadHead and TailTailTail.

If you want to get rid of dupes, you'll have to keep track of what the last item chosen was, and pick a new item if you pull a dupe. We could do this with a "do-while" loop.

Code:
- (IBAction)hello:(id)sender {
	//"static" means this variable will keeps it value between function calls.
	static int lastChosen=0;
	
	//this is the same
	NSArray *myArray= [NSArray arrayWithObjects: @"Yes",@"No",@"Maybe", nil];
	int length = [myArray count];
	
	int chosen;
	//this is a "Do" loop - it repeats as long as the "while" is true. 
	//we'll keep picking numbers until we get not-a-dupe
	do {
		chosen = (float)random() * length /RAND_MAX;	
	} while(chosen==lastChosen);
	
	//this is the same
	NSString *item = [myArray objectAtIndex: chosen];
	
	//this is how we combine the two strings
	helloLabel.text = [NSString stringWithFormat: @"The item I picked is: %@", item];

	//save the value for the next function call
	lastChosen=chosen;
}
__________________

Free Games!
smasher is offline   Reply With Quote
 

» Advertisements
» Online Users: 748
14 members and 734 guests
aaronhartigan, Bertrand21, betterlee, chiataytuday, Domele, gascertificate, kampftrinker, Macaret, meribran, phackdat, superblooddrainer, wilsonn44, wodanbrlam
Most users ever online was 1,187, 10-11-2011 at 08:09 AM.
» Stats
Members: 158,828
Threads: 89,207
Posts: 380,639
Top Poster: BrianSlick (7,129)
Welcome to our newest member, aaronhartigan
Powered by vBadvanced CMPS v3.1.0

All times are GMT -5. The time now is 02:54 AM.
Powered by vBulletin® Version 3.8.0
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.