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

Interface 2, Advanced iOS
Mockup & Code Gen
($9.99)

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

Pic Frame Dynamo: Photo Editing
($0.99)

Abiliator
($1.99)

Want your application or service advertised on iPhone Dev SDK?

Go Back   iPhone Dev SDK Forum > iPhone SDK Development Forums > iPhone SDK Development

Reply
 
LinkBack Thread Tools Display Modes
Old 08-25-2008, 05:23 PM   #1 (permalink)
Registered Member
 
Join Date: Aug 2008
Location: Ireland
Age: 21
Posts: 472
kieran12 is on a distinguished road
Unhappy Random Number Generator

I'm new to objective c and iPhone development. I'm creating an app that uses the random() function. It works but the problem I'm having is that the sequences it generates are the same every time. Here is my code:

Code:
        randomNumber1 =  1 + random() % 6;
	label1.text = [NSString stringWithFormat: @"%d",randomNumber1];
	randomNumber2 =  1 + random() % 6;
	label2.text = [NSString stringWithFormat: @"%d",randomNumber2];
	randomNumber3 =  1 + random() % 6;
	label3.text = [NSString stringWithFormat: @"%d",randomNumber3];
	randomNumber4 =  1 + random() % 6;
	label4.text = [NSString stringWithFormat: @"%d",randomNumber4];
	randomNumber5 =  1 + random() % 6;
	label5.text = [NSString stringWithFormat: @"%d",randomNumber5];
The number generated needs to be between 1 and 6. It works but it generates the same sequence every time I run the app. The sequences are:

2,5,4,2,6
2,5,1,4,2
3,2,3,2,6

and so on.

When I restart the app the same sequences are gernerated so it shows:

2,5,4,2,6
2,5,1,4,2
3,2,3,2,6

and so on again.

How can I use the random() function so that it generates completely different sequences every time I run the app.


Thanks
kieran12 is offline   Reply With Quote
Old 08-25-2008, 05:24 PM   #2 (permalink)
MDM
 
MDMstudios's Avatar
 
Join Date: Apr 2008
Location: MT
Posts: 128
MDMstudios is an unknown quantity at this point
Default

Quote:
Originally Posted by kieran12 View Post
I'm new to objective c and iPhone development. I'm creating an app that uses the random() function. It works but the problem I'm having is that the sequences it generates are the same every time. Here is my code:

Code:
        randomNumber1 =  1 + random() % 6;
	label1.text = [NSString stringWithFormat: @"%d",randomNumber1];
	randomNumber2 =  1 + random() % 6;
	label2.text = [NSString stringWithFormat: @"%d",randomNumber2];
	randomNumber3 =  1 + random() % 6;
	label3.text = [NSString stringWithFormat: @"%d",randomNumber3];
	randomNumber4 =  1 + random() % 6;
	label4.text = [NSString stringWithFormat: @"%d",randomNumber4];
	randomNumber5 =  1 + random() % 6;
	label5.text = [NSString stringWithFormat: @"%d",randomNumber5];
The number generated needs to be between 1 and 6. It works but it generates the same sequence every time I run the app. The sequences are:

2,5,4,2,6
2,5,1,4,2
3,2,3,2,6

and so on.

When I restart the app the same sequences are gernerated so it shows:

2,5,4,2,6
2,5,1,4,2
3,2,3,2,6

and so on again.

How can I use the random() function so that it generates completely different sequences every time I run the app.


Thanks
Yea, I had that same bit of trouble for a while, use arc4random instead.
__________________
iphone.MDMstudios@gmail.com


MDMstudios is offline   Reply With Quote
Old 08-25-2008, 05:44 PM   #3 (permalink)
Registered Member
 
Join Date: Aug 2008
Location: Ireland
Age: 21
Posts: 472
kieran12 is on a distinguished road
Default

Thanks for your quick reply. As I said I'm new to objective c. Could you please explain what you mean. Do I just change

Code:
random()
to

Code:
arc4random()

thanks
kieran12 is offline   Reply With Quote
Old 08-25-2008, 05:46 PM   #4 (permalink)
Registered Member
 
Join Date: Aug 2008
Location: Ireland
Age: 21
Posts: 472
kieran12 is on a distinguished road
Talking

Sorry I just tried replacing random() with arc4random() and it worked great. Thanks for your help!
kieran12 is offline   Reply With Quote
Old 08-25-2008, 05:58 PM   #5 (permalink)
Tutorial Author
 
Join Date: May 2008
Posts: 315
myersn024 is an unknown quantity at this point
Default

What a lot of people don't realize at first is that the random number generating function random() isn't a true random number generator. In order for random() to generate a different set of numbers every time you run a program, you have to seed it with a number that's never going to be the same. To accomplish this, most people will seed it with time like this:

Code:
srand(time(NULL));
That way, it's seeded with a different number (the number of seconds that have elapsed since some time in the 1970's) and it will generate a new set of numbers every time it's launched.

As a side note, seeding the random number generator with a constant integer value makes debugging programs that use random numbers easier since the random set is the same every time. Then once your done debugging, seed random with time and you're good to go.
myersn024 is offline   Reply With Quote
Old 08-25-2008, 06:04 PM   #6 (permalink)
Registered Member
 
Join Date: Aug 2008
Location: Ireland
Age: 21
Posts: 472
kieran12 is on a distinguished road
Default

Thanks for your help guys.
kieran12 is offline   Reply With Quote
Old 08-25-2008, 11:13 PM   #7 (permalink)
New Member
 
Join Date: Apr 2008
Posts: 420
jeff_lamarche is an unknown quantity at this point
Send a message via AIM to jeff_lamarche Send a message via Yahoo to jeff_lamarche
Default

I wouldn't use random() or srand() if I were you - they are notoriously poor PRNGs. They're fine for very simple games, but for anything more involved, you should consider using a different. There are several available on the iPhone, including arc4random() which is easy to use and respectably random.

If you're looking for something fast, there's a good, fast PRNG in the Touch Fighter game source code that you can get if went to WWDC this year - it's on the attendee site, and should still be available.
__________________
Check out my iPhone Dev Blog
You can send me e-mail at my forum username at mac dot com.
jeff_lamarche is offline   Reply With Quote
Old 08-26-2008, 03:26 AM   #8 (permalink)
Registered Member
 
Join Date: Aug 2008
Location: Ireland
Age: 21
Posts: 472
kieran12 is on a distinguished road
Default

I decided to use the arc4random() and it seems to work very well. I am only developing a very simple game/puzzle to help me learn so I don't thing I will need to look at PRNG just yet although I will check it out. Thanks for the advice.
kieran12 is offline   Reply With Quote
Old 06-11-2009, 05:30 AM   #9 (permalink)
Registered Member
 
Join Date: Jun 2009
Posts: 68
canit210 is on a distinguished road
Default

I'm a little late on this thread but I had a question similar to this, except when I implement this code. I get 3 error messages that all say "initializer element is not constant"

How can i fix this?

Thanks in advance. New programmer here so be easy.

Code: .m file

Quote:
#import "AddTapViewController.h"

@implementation AddTapViewController
@synthesize mathQuestion;
@synthesize randomA;
@synthesize randomB;

randomA = 1 + arc4random() % 6;
randomB = arc4random() % 6;

mathQuestion = [NSString stringWithFormat: @"%d + %d", randomA, randomB];


// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientationUIIn terfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}


- (void)dealloc {
[super dealloc];
[mathQuestion release];
}

@end
Code: .h file

Quote:
#import <UIKit/UIKit.h>

@interface AddTapViewController : UIViewController {
NSString *mathQuestion;
NSString *randomA;
NSString *randomB;
}
@property (nonatomic, retain) NSString *mathQuestion;
@property (nonatomic, retain) NSString *randomA;
@property (nonatomic, retain) NSString *randomB;

@end
canit210 is offline   Reply With Quote
Old 06-11-2009, 09:25 AM   #10 (permalink)
Pro. Game Developer
iPhone Dev SDK Supporter
 
Join Date: Feb 2009
Location: żLa Islas Hermosas?
Posts: 2,176
Kalimba is on a distinguished road
Default

Quote:
Originally Posted by canit210 View Post
I'm a little late on this thread but I had a question similar to this, except when I implement this code. I get 3 error messages that all say "initializer element is not constant"

How can i fix this?

Thanks in advance. New programmer here so be easy.

Code: .m file

Code:
#import "AddTapViewController.h"

@implementation AddTapViewController
@synthesize mathQuestion;
@synthesize randomA;
@synthesize randomB;

// the following three lines don't belong here
randomA = 1 + arc4random() % 6;
randomB = arc4random() % 6;
mathQuestion = [NSString stringWithFormat: @"%d + %d", randomA, randomB];


// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc {
    [super dealloc];
	[mathQuestion release];
}

@end
Code: .h file

Code:
#import <UIKit/UIKit.h>

@interface AddTapViewController : UIViewController {
	NSString		*mathQuestion;
	NSString		*randomA;
	NSString		*randomB;
}
@property (nonatomic, retain)	NSString	*mathQuestion;
@property (nonatomic, retain)	NSString	*randomA;
@property (nonatomic, retain)	NSString	*randomB;

@end
Couple things. First, don't use QUOTE tags around your code, because it doesn't get automatically included in any replies. Use the CODE tags instead.

Next, see my notes in RED in your code above. Basically, those lines are hanging out in no-man's-land in your class implementation, so the compiler thinks they're being initialized, hence the "initialization" error you're getting. This code needs to be moved into a function somewhere, either into an init function or a function that prepares to display the data to the user.
__________________
~~ Word Flurry ~~ App Store / Website / Facebook
Kalimba is offline   Reply With Quote
Old 06-11-2009, 09:59 AM   #11 (permalink)
Registered Member
 
Join Date: Jun 2009
Posts: 68
canit210 is on a distinguished road
Default

Could you show me (within the code) how I could implement this into a function that prepares to display the data to the user.

Thank you
canit210 is offline   Reply With Quote
Old 06-11-2009, 10:52 AM   #12 (permalink)
Registered Member
 
Join Date: Jun 2009
Posts: 11
avalore is on a distinguished road
Default

Code:
- (void)viewDidLoad
{
    randomA = 1 + arc4random() % 6;
    randomB = arc4random() % 6;
    mathQuestion = [NSString stringWithFormat: @"%d + %d", randomA, randomB];
}
This will run your code as soon as the view has been loaded...
avalore is offline   Reply With Quote
Old 06-11-2009, 06:44 PM   #13 (permalink)
Registered Member
 
Join Date: Jun 2009
Posts: 68
canit210 is on a distinguished road
Default

OK... This is really starting to frustrate me. I implemented what you told me but nothing is actually showing up when I run it on the Simulator. Could you please tell me what exactly I need to add (and how) to Interface Builder so it will display the equation. I've tried label but when I Control-Drag from File's Owner to the label to connect the code to the label, nothing happens when I run it. I must be missing something.

Below is my .h file:

Code:
#import <UIKit/UIKit.h>

@interface AddTapViewController : UIViewController {
	NSString		*mathQuestion;
	NSString		*randomA;
	NSString		*randomB;
	IBOutlet		UILabel		*label;
}
@property (nonatomic, retain)	NSString	*mathQuestion;
@property (nonatomic, retain)	NSString	*randomA;
@property (nonatomic, retain)	NSString	*randomB;
@property (nonatomic, retain) UILabel *label;
- (void)randomEquation;

@end
Below is my .m file:


Code:
#import "AddTapViewController.h"

@implementation AddTapViewController
@synthesize mathQuestion;
@synthesize randomA;
@synthesize randomB;
@synthesize label;

- (void)randomEquation
{
    randomA = arc4random() % 6;
    randomB = arc4random() % 6;
    mathQuestion = [NSString stringWithFormat: @"%d + %d", randomA, randomB];
}


// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc {
    [super dealloc];
	[mathQuestion release];
}

@end
I could really use some help. Thank you to everybody that has helped so far.
canit210 is offline   Reply With Quote
Old 06-11-2009, 07:04 PM   #14 (permalink)
Former NeXTStep Developer
 
Join Date: Mar 2009
Posts: 997
FlyingDiver will become famous soon enough
Default

Have you read the application tutorial in the Apple docs? It's in the guides section. This is basic Interface Builder, and the professional docs are going to do a better job explaining the basics than anyone can in a quick post here.

joe
FlyingDiver is offline   Reply With Quote
Old 06-11-2009, 11:58 PM   #15 (permalink)
Registered Member
 
Join Date: Jun 2009
Location: Fort Lauderdale, Florida
Posts: 67
Ins3rtNam3H3r3 is an unknown quantity at this point
Default

randomEquation is never being called. You either need to change the name to viewDidLoad, or add viewDidLoad and call randomEquation from it. Also, the label's text is never being set, you have to add label.text = mathQuestion; You also need to make randomA and randomB ints not strings.
Ins3rtNam3H3r3 is offline   Reply With Quote
Old 06-12-2009, 09:58 AM   #16 (permalink)
Registered Member
 
Join Date: Jun 2009
Posts: 68
canit210 is on a distinguished road
Default

Thank you
canit210 is offline   Reply With Quote
Old 06-12-2009, 10:34 AM   #17 (permalink)
Pro. Game Developer
iPhone Dev SDK Supporter
 
Join Date: Feb 2009
Location: żLa Islas Hermosas?
Posts: 2,176
Kalimba is on a distinguished road
Default

Quote:
Originally Posted by FlyingDiver View Post
Have you read the application tutorial in the Apple docs? It's in the guides section. This is basic Interface Builder, and the professional docs are going to do a better job explaining the basics than anyone can in a quick post here.

joe
Meh... but who has the time or desire to actually learn something? We all want to get stuff done! Reading documentation that explains how things work is soooo overrated.
__________________
~~ Word Flurry ~~ App Store / Website / Facebook
Kalimba is offline   Reply With Quote
Old 06-12-2009, 02:33 PM   #18 (permalink)
Registered Member
 
Join Date: Jun 2009
Posts: 68
canit210 is on a distinguished road
Default

Don't worry. I'll read all the documentation right after I get this working.
canit210 is offline   Reply With Quote
Old 06-16-2010, 06:37 PM   #19 (permalink)
Registered Member
 
Join Date: Jan 2010
Posts: 11
Cesar is on a distinguished road
Default

Thanks !

Last edited by Cesar; 06-16-2010 at 06:42 PM.
Cesar is offline   Reply With Quote
Reply

Bookmarks

Tags
newbie, number generator, random(), sequences

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



» Advertisements
» Online Users: 346
10 members and 336 guests
givensur, glenn_sayers, guusleijsten, ipodphone, jbro, mediaspree, mtl_tech_guy, Punkjumper, whitey99, yys
Most users ever online was 1,387, 04-10-2012 at 04:21 AM.
» Stats
Members: 175,649
Threads: 94,114
Posts: 402,883
Top Poster: BrianSlick (7,990)
Welcome to our newest member, Anwerbl
Powered by vBadvanced CMPS v3.1.0

All times are GMT -5. The time now is 09:34 PM.
Powered by vBulletin® Version 3.8.0
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0