Randomize words

2019-09-15 18:24发布

问题:

I'm making my first iOS app, and am in need of some help. Here is how it'll work:

User enters word in a textfield, presses a button and in the label it should be like this: [Users word] [Randomly picked word].

So I think that I should make an array with the random words and then somehow randomize them when the button is pressed to display a random word out of many after the word the user entered in the text field.

But how is it supposed to work? Here is what I was thinking:

randomizing this (don't know how though):

NSArray *words = [NSArray arrayWithObjects: @"Blue", @"Green", @"Red", nil ];

and here is the code for displaying the text from the textfield:

NSString *labeltext = [NSString stringWithFormat:@"%@", [textField text]];

if I put label.text = labeltext; then it displays the word typed by the user, but I'm stuck at the "displaying random word from array" part.

Any help appreciated!

回答1:

    NSArray *words = [NSArray arrayWithObjects: @"Blue", @"Green", @"Red", nil ];
    NSString *str=[words objectAtIndex:arc4random()%[words count]];
    // using arc4random(int) will give you a random number between 0 and int.
    // in your case, you can get a string at a random index from your words array 


回答2:

To the OP. To make the random answers non-repeating, set up your array as an instance variable in your view controller's viewDidLoad. Also create a property remainingWords:

@property (nonatomic, retain) NSMutableArray *remainingWords;

Your viewDidLoad code would look like this:

-(void) viewDidLoad;
{
  //Create your original array of words.
  self.words = [NSArray arrayWithObjects: @"Blue", @"Green", @"Red", nil ];

  //Create a mutable copy so you can remove words after choosing them.
  self.remainingWords = [self.words mutableCopy];
}

Then you can write a method like this to get a unique word from your array:

- (NSString *) randomWord;
{
  //This code will reset the array and start over fetching another set of unique words.
  if ([remainingWords count] == 0)
    self.remainingWords = [self.words MutableCopy];

  //alternately use this code:
  if ([remainingWords count] == 0)
    return @""; //No more words; return a blank.
  NSUInteger index = arc4random_uniform([[remainingWords count])
  NSString *result = [[[remainingWords index] retain] autorelease];
  [remainingWords removeObjectAtindex: index]; //remove the word from the array.
}