0

I have 4 UIbuttons and one UILabel.I want to do 4 words (from plist file )random shown on 4 buttons(one button has one word) and one word shown on label(that have the same name of the word on the button). How can I do that?

nmzik
  • 141
  • 1
  • 1
  • 9

2 Answers2

3

Assuming that your plist is called words.plist and that you have an array of 4 UIButtons

NSString * path = [[NSBundle mainBundle] pathForResource:@"words" ofType:@"plist"];
NSMutableArray * words = [NSMutableArray arrayWithContentsOfFile:path];

Now you have all the possible words in the words array. At this point we need 4 unique random indices, which basically means to take the starting 4 elements of the array after randomly shuffling it. We'll use the Fisher-Yates shuffle algorithm as suggested in this answer.

for (int i = words.count - 1; i > 0; --i) {
    int r = arc4random_uniform(i);
    [words exchangeObjectAtIndex:i withObjectAtIndex:r];
}

Now that we have a randomly shuffled array of words, we just take the first 4 elements and assign them to the buttons. It would look something like:

for (int j = 0; j < buttons.count; j++) {
    UIButton * button = [buttons objectAtIndex:j];
    button.titleLabel.text = [words objectAtIndex:j];
}

Finally we assign a word to the label, randomly choosing an index between the one we used for the buttons:

yourLabel.text = [words objectAtIndex:arc4random_uniform(buttons.count)];

This solution works with an arbitrary number of buttons, it's guaranteed to be efficient due to the shuffling algorithm (which is definitely better than checking for already generated indices) and the random generation is not biased thanks to the use of arc4random_uniform

Community
  • 1
  • 1
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
  • Thanks but I have crash in iphone simulator:Terminating app due to uncaught exception 'NsRangeException', reason NSMutableArray exchangeObjectAtIndex:withObjectAtIndex:]: index 6 beyond bounds [0 .. 5]' – nmzik Dec 16 '12 at 08:41
  • You are right, I got the indexes wrong. The loop for shuffling the words has to go from words.count - 1 to 0. I updated my answer – Gabriele Petronella Dec 16 '12 at 17:47
2

Move the contents of the PLIST file into an array.

NSArray *words = [[NSArray alloc] initWithContentsOfFile:filePath];

Randomly find a number.

int randInt = arc4random() % 10;

Change 10 to the total number of words in the PLIST.

You can now select the random word out of the array.

NSString *random = [words objectAtIndex:randInt];

You have one random word. Find another random number (check to make sure it is not the same as the previous one) and then choose the next word out of the words array.

Jack Humphries
  • 13,056
  • 14
  • 84
  • 125