Reputation: 24481
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.
- (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]]];
}
}
Upvotes: 1
Views: 256
Reputation: 3859
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).
Upvotes: 5