问题描述
我希望用户单击一个按钮以"a +/- b = c"的形式生成一个十个问题的测验,其中a和b的值从+10到-10,并且是随机的分配了十个问题.同样,问题应在加法和减法之间随机切换.如何正确填充plist文件?如何使用arc4random
用随机整数创建十个问题?
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?
我认为将问题显示在一个单列选择器中非常方便,用户可以在其中滚动查看问题,也可以只在屏幕上的某个CGPoint
处显示文本.
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.
相反,我创建了一个plist,其中包含84个不同的可能问题,并且我希望每次用户单击按钮时从plist中随机选择10个来创建测验.到目前为止,我已经知道了:
Instead, I have created a plist with 84 different possible questions and I want to randomly choose 10 from plist to create 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是plist的名称,@"1"
,@"2"
,@"3"
等是我放入plist中的84个差异Q的名称.如何从84个NSLog中随机选择10个?
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?
推荐答案
如果键只是数字,请使用NSArray
而不是使用NSDictionary
.然后你可以做
Instead of using a NSDictionary
, use NSArray
if your keys are just numbers. You could then do
NSString *randomString = [array objectAtIndex:(arc4random() % [array count])];
选择一个随机元素.
但是,如果它只是随机数的不同组合,我会真的建议不要在plist中查找它.手工写出所有这些组合只是浪费时间.那就是计算机的用途!
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:
生成-10
和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;
}
这篇关于使用plist为测验创建随机整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!