【问题标题】:Generate random index which is not generated again [duplicate]生成不再生成的随机索引[重复]
【发布时间】:2014-01-11 00:09:04
【问题描述】:

我有一个名字数组和一个数字数组。

我的 Person 类具有 namenumber 的属性。我想将随机值分配给随机的人。

假设我有一个包含 strings @"mary" , @"Jack" and @"ABhraham" 的数组 和另一个带有 numbers 122, 378, 987 的数组,我想随机分配这些值。我使用了arc4random() 方法,但它有时会再次返回相同的值。

【问题讨论】:

  • @Reformer 不,这不是 methi1999 正在寻找的那个(尽管标题表明他正在寻找)。他实际上是在寻找 FY-shuffle。
  • 您的阵列大小是 10 秒、100 秒还是 1000 秒?然后您可以使用更粗暴的方法,例如循环,尝试分配,除非它已经分配。好处是您不必阅读 FY 并且可以继续您的项目。缺点是你错过了学习很酷的东西。

标签: objective-c arrays random


【解决方案1】:

使用Fisher–Yates shuffle。创建一个从零到N-1(含)的数组,其中N 是数组中的元素数;这将是索引数组。然后将 Fisher-Yates shuffle 应用于索引数组。现在您可以为每个name[i] 使用number[index[i]]

这是link to an answer that provides a Fisher-Yates Shuffle implementation in Objective-C

【讨论】:

    【解决方案2】:

    1:使用字典,为每个人设置关键字。

    2:对两者都使用可变数组,在分配时删除每个对象。

    while(arrayOfNumberTags.count>0){
        float randomIndex = arc4random() % arrayOfNumberTags.count;
        int tagForPerson = [arrayOfNumberTags objectAtIndex:randomIndex];
        //Create the Person object with the tag and any person
        [arrayOfNumberTags removeObjectAtIndex:randomIndex];
    
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多