【问题标题】:Using arc4random function to produce unique values [duplicate]使用 arc4random 函数产生唯一值
【发布时间】:2014-04-08 13:43:20
【问题描述】:

我正在为 iPhone 创建一个测验应用程序。目前我的问题是使用arc4random 函数随机选择的。

问题是我希望每个问题只显示一次。有没有办法让arc4random 函数生成唯一的数字,然后在它生成所有可能的数字后停止?

这是我目前用来生成我的随机数的:

QuestionSelected = arc4random() %4;

任何帮助都会很棒。

【问题讨论】:

  • 一个解决方案:创建一个由 k 个元素组成的数组(带有您的问题的 id)。然后: int index = arc4Randcom()%[theArray count];你会得到 [theArray objectAtIndex:index] 的问题。然后,删除问题:[theArray removeObjectAtIndex:index];
  • 您要查找的内容称为“随机排列”或“随机洗牌”。
  • Y 前段时间使用过 Larme 方法
  • 使用@Larme和arc4random_uniform([theArray count])提到的方法。 arc4random_uniform的原因可以在这里找到:stackoverflow.com/questions/160890/…
  • 我的回答有用吗?

标签: ios objective-c arc4random


【解决方案1】:
NSMutableArray *questions=[NSMutableArray new];
//creating an array to save questions
// Place in viewDidLoad
for(;;) {
    //randomly select question
    QuestionSelected = arc4random() % 4;
    //check if question contains this number
    //if it does - continue looping
    if(![questions containsObject:@(QuestionSelected)]){
        //so it doesn't - we add this number to array
        [questions addObject:@(QuestionSelected)];
        break;
        //and exit loop
    }

 }

就是这样

【讨论】:

  • 你喜欢解释你的代码吗???
  • 取决于有多少问题,这可能会降低随机尝试查找未使用的数字的速度
  • 我试过这个,但我收到错误“ARC不允许将'int'隐式转换为'Id'
【解决方案2】:

您可以在问题中使用NSMutableArray,并在选择问题时将其从数组中删除。在这种情况下,您将生成介于 0 和 array.count - 1

之间的随机数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    相关资源
    最近更新 更多