我有一个14个字符串的数组。我想显示这14个字符串中的每一个,但不要重复。我尝试过创建一个整数数组并随机打乱它们的值,然后使用整数数组中的一个数字作为索引从字符串数组中读取:
//appDelegate.randomRiddles is an array of integers that has integer values randomly
appDelegate.randomRiddlesCounter++;
NSNumber *index=[appDelegate.randomRiddles objectAtIndex:appDelegate.randomRiddlesCounter];
int i = [index intValue];
while(i>[appDelegate.currentRiddlesContent count]){
appDelegate.randomRiddlesCounter++;
index=[appDelegate.randomRiddles objectAtIndex:appDelegate.randomRiddlesCounter];
i = [index intValue];
}
hintText.text = [[appDelegate.currentRiddlesContent objectAtIndex:i] objectForKey:@"hint"];
questionText.text = [[appDelegate.currentRiddlesContent objectAtIndex:i] objectForKey:@"question"];
但我的方法会导致崩溃和重复。而且每次从字符串数组中读取一个值时,该字符串都会从数组中删除,使其计数减少1。这使得问题稍微有点复杂。
arc4random() % [myArray count]
吗?这样可以得到从 0 到 count-1 的数字。否则,最后一个元素将保持不变,如果 count = 1,则会执行arc4random() % 0
,这是不正确的。如果您想从数组中删除项目,可以说明或发布相应代码。 - Rudy Velthuis