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 Tutorials

Reply
 
LinkBack Thread Tools Display Modes
Old 03-29-2011, 07:01 AM   #1 (permalink)
Cocoa Junkie
 
Duncan C's Avatar
 
Join Date: Dec 2008
Location: Northern Virginia
Posts: 6,005
Duncan C has a spectacular aura about
Default Generating random, non-repeating text

This question comes up on this board at least once a week. A while back I wrote some code to select random words or phrases from an array, and only select any given word/phrase once. Here is the code you need:



Code:
	NSArray* words;
	NSMutableArray* randomArray;
	NSMutableArray* array;
}
@property (nonatomic, retain)			NSArray* words;
@property (nonatomic, retain)			NSMutableArray* array;
@property (nonatomic, retain)			NSMutableArray* randomArray;
And put these methods (and one C function) into the .m file of the same class:


Code:
//This is the "sort" function that puts the items in random order.
//It uses a random number generator to decide the ordering of items in the array

NSInteger randomize(id num1, id num2, void *context)
{
	int rand = arc4random() %2;
	if (rand)
		return NSOrderedAscending;
    else 
        return NSOrderedDescending;
}

//This function populates "randomArray" with an array of indexes in random order.
//Once the getRandomWord method returns nil, call resetRandomArray to 
//repopulate the randomArray with the same list of words in a different random order.
- (void) resetRandomArray;
{
        //Copy over our starting "array" containing all our indexes in order.
	[randomArray setArray: array ];

        //Use a trick to "sort" the array into random order.
        //this trick involves using a sort function "randomize" that puts
        //the items in random order.
	[randomArray sortUsingFunction: randomize context:NULL];

}

-(NSString*) getRandomWord;
{
	if ([randomArray count] ==0)
		return nil;
	NSString* result;
	NSInteger randomIndex = [[randomArray lastObject] intValue];;
	[randomArray removeLastObject];
	result = [words objectAtIndex: randomIndex];
	return result;
}

-(void) buildRandomWordArray;
{	
	NSInteger index;
	
	NSError* theError;

	NSString *path = [[NSBundle mainBundle] pathForResource:@"words" ofType:@"txt"];
	NSString* text = [NSString stringWithContentsOfFile: path 
		encoding: NSUTF8StringEncoding 
		error: &theError];
	self.words = [text componentsSeparatedByString: @"\n"];
	
	int arraySize = [words count];
	self.array = [NSMutableArray arrayWithCapacity:arraySize];
	self.randomArray = [NSMutableArray arrayWithCapacity:arraySize];

        //This code fills "array" with index values from 0 to the number of elements in the "words" array.
	for (index = 0; index
To use it:
-Create a file called words.txt containing a list of words or phrases separated by carriage returns.
-Drag that file into the resources portion of your project, so it will be included in the bundle.
-Call [self buildRandomWordArray] to do the initial setup. That reads the file and populates an array of random indexes.
-Call [self getRandomWord] to get a new random word or phrase. That word/phrase will be deleted from the list and not used again. Once the list is exhausted, the getRandomWord will return nil;
-To start over and get the same list of words in a different order, call [self resetRandomArray]


I wrote this to use a text file delimited by carriage returns because its simple to generate a text file.

It would be trivial to change the code above to bring the array of words/phrases in from a plist instead of a text file, but that means you have to generate the plist.

All you would have to do s replace the bolded lines above with:

Code:
	NSString *path = [[NSBundle mainBundle] pathForResource:@"words" ofType:@"plist"];
	self.words = [NSArray arrayWithContentsOfFile: path];
__________________
Regards,

Duncan C
WareTo

Check out our apps in the Apple App store


Check out this password generator app that shows various techniques including using a data container singleton object to share data between objects in your project.

See this tutorial on using UIView animations and layer animations:

See this thread on generating random, non-repeating text

Check out a very cool Macintosh Kaleidoscopes app called ScopeWorks that we released to the Mac App store.
Duncan C is offline   Reply With Quote
Old 04-08-2011, 03:06 PM   #2 (permalink)
Registered Member
 
Join Date: Apr 2011
Posts: 3
eiskrelle is on a distinguished road
Default

It says that error: initializer element is not constant
is not compile-time constant
expected '=', ',', ';', 'asm' or '__attribute__' before '.' token
expected " before "

What can i do?
eiskrelle is offline   Reply With Quote
Old 04-08-2011, 03:59 PM   #3 (permalink)
Cocoa Junkie
 
Duncan C's Avatar
 
Join Date: Dec 2008
Location: Northern Virginia
Posts: 6,005
Duncan C has a spectacular aura about
Default

Quote:
Originally Posted by eiskrelle View Post
It says that error: initializer element is not constant
is not compile-time constant
expected '=', ',', ';', 'asm' or '__attribute__' before '.' token
expected " before "

What can i do?


On what line?
__________________
Regards,

Duncan C
WareTo

Check out our apps in the Apple App store


Check out this password generator app that shows various techniques including using a data container singleton object to share data between objects in your project.

See this tutorial on using UIView animations and layer animations:

See this thread on generating random, non-repeating text

Check out a very cool Macintosh Kaleidoscopes app called ScopeWorks that we released to the Mac App store.
Duncan C is offline   Reply With Quote
Old 04-08-2011, 04:47 PM   #4 (permalink)
Indie Developer
 
iSDK's Avatar
 
Join Date: Jul 2010
Posts: 1,346
iSDK is on a distinguished road
Send a message via AIM to iSDK
Default

@Duncan C he can't be getting that as someone else would have picked up on it. He posted this in another thread, and he is trying to hijack this to solve his problem.

Quote:
Originally Posted by Duncan C View Post
On what line?
iSDK is offline   Reply With Quote
Old 04-08-2011, 05:29 PM   #5 (permalink)
Registered Member
 
Join Date: Jan 2011
Posts: 154
Bobarino is on a distinguished road
Default

Hey, just posting to get this into my subscribed threads for I may want this later. It may be helpful for the future. Nice work Duncan. You can delete this or whatever, just disregard it
Bobarino is offline   Reply With Quote
Old 08-28-2011, 08:18 PM   #6 (permalink)
Registered Member
 
Join Date: Aug 2011
Posts: 6
tbeck is on a distinguished road
Default generate random non repeating text

Quote:
Originally Posted by Duncan C View Post
This question comes up on this board at least once a week. A while back I wrote some code to select random words or phrases from an array, and only select any given word/phrase once. Here is the code you need:



Code:
	NSArray* words;
	NSMutableArray* randomArray;
	NSMutableArray* array;
}
@property (nonatomic, retain)			NSArray* words;
@property (nonatomic, retain)			NSMutableArray* array;
@property (nonatomic, retain)			NSMutableArray* randomArray;
And put these methods (and one C function) into the .m file of the same class:


Code:
//This is the "sort" function that puts the items in random order.
//It uses a random number generator to decide the ordering of items in the array

NSInteger randomize(id num1, id num2, void *context)
{
	int rand = arc4random() %2;
	if (rand)
		return NSOrderedAscending;
    else 
        return NSOrderedDescending;
}

//This function populates "randomArray" with an array of indexes in random order.
//Once the getRandomWord method returns nil, call resetRandomArray to 
//repopulate the randomArray with the same list of words in a different random order.
- (void) resetRandomArray;
{
        //Copy over our starting "array" containing all our indexes in order.
	[randomArray setArray: array ];

        //Use a trick to "sort" the array into random order.
        //this trick involves using a sort function "randomize" that puts
        //the items in random order.
	[randomArray sortUsingFunction: randomize context:NULL];

}

-(NSString*) getRandomWord;
{
	if ([randomArray count] ==0)
		return nil;
	NSString* result;
	NSInteger randomIndex = [[randomArray lastObject] intValue];;
	[randomArray removeLastObject];
	result = [words objectAtIndex: randomIndex];
	return result;
}

-(void) buildRandomWordArray;
{	
	NSInteger index;
	
	NSError* theError;

	NSString *path = [[NSBundle mainBundle] pathForResource:@"words" ofType:@"txt"];
	NSString* text = [NSString stringWithContentsOfFile: path 
		encoding: NSUTF8StringEncoding 
		error: &theError];
	self.words = [text componentsSeparatedByString: @"\n"];
	
	int arraySize = [words count];
	self.array = [NSMutableArray arrayWithCapacity:arraySize];
	self.randomArray = [NSMutableArray arrayWithCapacity:arraySize];

        //This code fills "array" with index values from 0 to the number of elements in the "words" array.
	for (index = 0; index
To use it:
-Create a file called words.txt containing a list of words or phrases separated by carriage returns.
-Drag that file into the resources portion of your project, so it will be included in the bundle.
-Call [self buildRandomWordArray] to do the initial setup. That reads the file and populates an array of random indexes.
-Call [self getRandomWord] to get a new random word or phrase. That word/phrase will be deleted from the list and not used again. Once the list is exhausted, the getRandomWord will return nil;
-To start over and get the same list of words in a different order, call [self resetRandomArray]


I wrote this to use a text file delimited by carriage returns because its simple to generate a text file.

It would be trivial to change the code above to bring the array of words/phrases in from a plist instead of a text file, but that means you have to generate the plist.

All you would have to do s replace the bolded lines above with:

Code:
	NSString *path = [[NSBundle mainBundle] pathForResource:@"words" ofType:@"plist"];
	self.words = [NSArray arrayWithContentsOfFile: path];
Thank you Duncan for the purposeful responses to newbies like myself....

If I understand correctly, I can use this code to create a quiz of 10 Q's in the form of a +/- b =?, where a is id num 1 and b is id num 2? I still need to randomly assign each question to be + or -, would that be id num 3 populated from another plist where the only choices are +/-?
Finally, I need the quiz to appear at a specific point on screen so I need to tell text to appear at a certain CGPoint... where does that go???
How do I get the quiz to appear at certain CGPoint?
a will be id num1 and b will be id num 2
tbeck is offline   Reply With Quote
Old 08-31-2011, 12:09 PM   #7 (permalink)
Cocoa Junkie
 
Duncan C's Avatar
 
Join Date: Dec 2008
Location: Northern Virginia
Posts: 6,005
Duncan C has a spectacular aura about
Default

Quote:
Originally Posted by tbeck View Post
Thank you Duncan for the purposeful responses to newbies like myself....

If I understand correctly, I can use this code to create a quiz of 10 Q's in the form of a +/- b =?, where a is id num 1 and b is id num 2? I still need to randomly assign each question to be + or -, would that be id num 3 populated from another plist where the only choices are +/-?
Finally, I need the quiz to appear at a specific point on screen so I need to tell text to appear at a certain CGPoint... where does that go???
How do I get the quiz to appear at certain CGPoint?
a will be id num1 and b will be id num 2
This is a very specific question. You should start a new thread that asks for help with your specific needs.
__________________
Regards,

Duncan C
WareTo

Check out our apps in the Apple App store


Check out this password generator app that shows various techniques including using a data container singleton object to share data between objects in your project.

See this tutorial on using UIView animations and layer animations:

See this thread on generating random, non-repeating text

Check out a very cool Macintosh Kaleidoscopes app called ScopeWorks that we released to the Mac App store.
Duncan C is offline   Reply With Quote
Old 08-31-2011, 12:37 PM   #8 (permalink)
Registered Member
 
Join Date: Aug 2011
Posts: 6
tbeck is on a distinguished road
Default New Thread

Quote:
Originally Posted by Duncan C View Post
This is a very specific question. You should start a new thread that asks for help with your specific needs.
Duncan C: I don't believe I have permission to start new thread as there is a box on my screen saying I may not post new threads.
tbeck is offline   Reply With Quote
Old 08-31-2011, 03:25 PM   #9 (permalink)
Registered Member
 
Join Date: Aug 2011
Posts: 6
tbeck is on a distinguished road
Default generate random integers for quiz

Quote:
Originally Posted by Duncan C View Post
This is a very specific question. You should start a new thread that asks for help with your specific needs.
I want to generate a 10 Q quiz in the form of a +/- b = c where a and b are integers from (+10) to (-10) and are selected randomly for each question. Also each question should randomly choose from an add/sub operation.

I bellieve I need to use plist and arc4random but am not sure how to...

thank you....
tbeck is offline   Reply With Quote
Old 08-31-2011, 03:40 PM   #10 (permalink)
Cocoa Junkie
 
Duncan C's Avatar
 
Join Date: Dec 2008
Location: Northern Virginia
Posts: 6,005
Duncan C has a spectacular aura about
Default

Quote:
Originally Posted by tbeck View Post
I want to generate a 10 Q quiz in the form of a +/- b = c where a and b are integers from (+10) to (-10) and are selected randomly for each question. Also each question should randomly choose from an add/sub operation.

I bellieve I need to use plist and arc4random but am not sure how to...

thank you....
ARGGGGHHHH!

To repeat:

Quote:
This is a very specific question. You should start a new thread that asks for help with your specific needs.
As I told you in a private message, you can't (and shouldn't) create new threads to this section without specific permission. You should go to the general iPhone Dev SDK page and create a new thread there with your question.

This thread is not the place for specific help developing your app, which does not have much to do with selecting random, non-repeating text.
__________________
Regards,

Duncan C
WareTo

Check out our apps in the Apple App store


Check out this password generator app that shows various techniques including using a data container singleton object to share data between objects in your project.

See this tutorial on using UIView animations and layer animations:

See this thread on generating random, non-repeating text

Check out a very cool Macintosh Kaleidoscopes app called ScopeWorks that we released to the Mac App store.
Duncan C is offline   Reply With Quote
Reply

Bookmarks

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 On
Trackbacks are On
Pingbacks are On
Refbacks are On



» Advertisements
» Online Users: 478
15 members and 463 guests
alexeir, David-T, Dj_kades, foslock, HemiMG, iAppDeveloper, jeroenkeij, LunarMoon, Mijator, Pauluz85, pipposanta, QuantumDoja, robsmy, sacha1996, usernametaken
Most users ever online was 1,387, 04-10-2012 at 04:21 AM.
» Stats
Members: 175,679
Threads: 94,129
Posts: 402,928
Top Poster: BrianSlick (7,990)
Welcome to our newest member, xzoonxoom
Powered by vBadvanced CMPS v3.1.0

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