从数组中获取随机对象,如果对象相同,则获取一个新对象

时间:2022-06-24 07:10:19

I have made a jokes application, where the user generates a joke and the joke will display in a UILabel. However I am trying to randomise the jokes show, but I do not want to show the same joke twice. Please could you tell me how I could do this. I am using the code below to try and do that, but it seems that it is not working.

我做了一个笑话应用程序,用户生成一个笑话,笑话将显示在UILabel中。然而,我试图随机化笑话节目,但我不想两次显示相同的笑话。请问你能告诉我怎么做到这一点。我正在使用下面的代码尝试这样做,但它似乎无法正常工作。

- (IBAction)generateNewJoke {
if (i < [jokeArray count]) {
    i++;
        [userDefaults setInteger:[userDefaults integerForKey:kNewIndex] forKey:kOldIndex];

    int oldnumber = [userDefaults integerForKey:kOldIndex];
    int newnumber = [userDefaults integerForKey:kNewIndex];

    [answerLabel setText:@""];
    [userDefaults setInteger:i forKey:kNewIndex]; 

    if (oldnumber == newnumber) {
        NSLog(@"they are the same");
        [userDefaults setInteger:arc4random()%[jokeArray count] forKey:kNewIndex]; 
    }

    [jokeLabel setText:[jokeArray objectAtIndex:[userDefaults integerForKey:kNewIndex]]];

}
}

1 个解决方案

#1


6  

You could have all your jokes in an array, shuffle the array and then just traverse the array in order. Since it was shuffled before, all the jokes will be different. When you get to the end of the array, start at the beginning (and even reshuffle).

你可以将所有的笑话放在一个数组中,对数组进行洗牌,然后按顺序遍历数组。由于它之前被洗牌,所有的笑话都会有所不同。当你到达数组的末尾时,从头开始(甚至重新洗牌)。

#1


6  

You could have all your jokes in an array, shuffle the array and then just traverse the array in order. Since it was shuffled before, all the jokes will be different. When you get to the end of the array, start at the beginning (and even reshuffle).

你可以将所有的笑话放在一个数组中,对数组进行洗牌,然后按顺序遍历数组。由于它之前被洗牌,所有的笑话都会有所不同。当你到达数组的末尾时,从头开始(甚至重新洗牌)。