我有一个名称和数字数组。生成不再生成的随机索引
我的人类有名称和号码的财产。我想将随机值分配给随机的人。
假设我有与串@"mary" , @"Jack" and @"ABhraham"
并与数字122, 378, 987
另一个数组的数组,我想他们随机指定这些值。我使用了arc4random()
方法,但它有时会再次返回相同的值。
我有一个名称和数字数组。生成不再生成的随机索引
我的人类有名称和号码的财产。我想将随机值分配给随机的人。
假设我有与串@"mary" , @"Jack" and @"ABhraham"
并与数字122, 378, 987
另一个数组的数组,我想他们随机指定这些值。我使用了arc4random()
方法,但它有时会再次返回相同的值。
1:使用词典,为每个人设置键。
OR
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];
}
使用Fisher–Yates shuffle。创建一个包含数字0到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。
@Reformer不,这不是methi1999正在寻找的那个(虽然标题暗示他是)。他实际上是在寻找FY-shuffle。 – dasblinkenlight
您的阵列大小为10s,100s,1000s吗?然后,您可以使用更粗暴的方法,如循环,尝试分配,除非它已被分配。好处是你不必在FY阅读,你可以继续你的项目。缺点是你想念一些很酷的东西。 – danh