开发者

create random integers for quiz using plist

I would like to have user click on a button to generate a ten-question quiz in the form of "a +/- b = c" where the values for a and b are from +10 to -10 and are randomly assigned for the ten questions. Also, the questions should randomly switch between addition and subtraction. How do I populate the plist file correctly? How do I use arc4random to create ten questions with random integers?

I thought it would be neat to have questions display in a one-column picker where user can scroll through the questions or just have text at a certain CGPoint on screen.

Instead, I have created a plist with 84 different possible questions and I want to randomly choose 10 from plist to cr开发者_开发知识库eate the quiz each time a user clicks on button. I have this so far:

NSString *plistFile = [[NSBundle mainBundle] pathForResource:@"global" ofType:@"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsofFile:plistFile];
NSLog(@"%@",[dict objectForKey:@"1"]);
NSLog(@"%@",[dict objectForKey:@"2"]);
NSLog(@"%@",[dict objectForKey:@"3"]);

global is the name of plist, @"1", @"2", @"3" etc are the names of the 84 diff Q's I put in plist. How do I randomly choose 10 of the 84 NSLogs?


Instead of using a NSDictionary, use NSArray if your keys are just numbers. You could then do

NSString *randomString = [array objectAtIndex:(arc4random() % [array count])]; 

to pick a random element.

However, I would really advice against looking it up in a plist if it's just different combinations of random numbers. Writing out all those combinations by hand is just a waste of time. That's what computers are for!

Old, but still relevant answer:

To generate a random number between -10and 10:

int a = (arc4random() % 21) - 10;

You could also make a function like this:

int randomIntegerInRange(int min, int max)
{
    int range = max - min + 1;
    return min + arc4random() % range;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜