【问题标题】:Random with selected number in xcode在xcode中随机选择数字
【发布时间】:2012-08-24 12:32:39
【问题描述】:

我有整数,即 0、17、23、44、57、60、66、83、89、91、100,但我想从该数字中随机取 6 个数字,该怎么做?我只能显示 0-100 之间的一个随机数,但我不知道如何从选定的数字中显示 6 个数字。请教。

【问题讨论】:

  • 那些整数值是否插入到数组中?

标签: iphone ios5 xcode4.3


【解决方案1】:

如果您想从数组中挑选六个不重复的数字,请使用Knuth-Fisher–Yates shuffle 打乱数组,然后取前六个数字:

int data[] = {0, 17, 23, 44, 57, 60, 66, 83, 89, 91, 100};
// Knuth-Fisher-Yates
for (int i = 10 ; i > 0 ; i--) {
    int n = rand() % (i+1);
    int tmp = data[i];
    data[i] = data[n];
    data[n] = tmp;
}

data 数组的前六个元素包含从原始 11 元素数组中的随机选择。

【讨论】:

  • +1 :在这种特殊情况下,他确实需要一种随机行为而不是随机行为!
【解决方案2】:

将数字放入数组中。使用随机数生成器获取小于数组长度 0 到 1 之间的随机数,然后获取该索引处的数字。

这只是一种方法。

【讨论】:

    【解决方案3】:

    对于将随机数提取到数组中,以下代码可能对您有用

    [array objectAtIndex: (random() % [array count])]
    

    这是一个例子

    NSUInteger firstObject = 0;
    
    for (int i = 0; i<[myNSMutableArray count];i++) {
        NSUInteger randomIndex = random() % [myNSMutableArray count];
        [myNSMutableArray exchangeObjectAtIndex:firstObject withObjectAtIndex:randomIndex];
        firstObject +=1;
    
    }
    

    【讨论】:

    【解决方案4】:

    看到这个帖子:Generating random numbers in Objective-C

    有很多方法可以做到这一点。这种特殊的方法有很好的反应。要获得 6 个随机数,只需运行该函数 6 次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-21
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多