Rupesh
Rupesh

Reputation: 7906

choose random value

I am new to iPhone programming. I have 10 number say (1,2,3,4,5,6,7,8,9,10). I want to choose randomly 1 number from the above 10 numbers. How can I choose a random number from a set of numbers?

Upvotes: 0

Views: 625

Answers (3)

PurplePilot
PurplePilot

Reputation: 6612

Something like this:

- (IBAction)generate:(id)sender
{
    // Generate a number between 1 and 10 inclusive
    int generated;
    generated = (random() % 10) + 1;

}

Upvotes: 0

Tom Jefferys
Tom Jefferys

Reputation: 13310

If you simply want a value between 1 and 10, you can use the standard C rand() method. This returns an integer between zero and RAND_MAX.

To get a value between 0 and 9 you can use the % operator. So to get a value between 1 and 10 you can use:

rand()%10 + 1

If you don't want the same series of pseudo random numbers each time, you'll need to use srand to seed the random number generator. A good value to seed it with would be the current time.

If you're asking about choosing a number from a list of arbitrary (and possibly non consecutive) numbers, you could use the following.

int numbers[] = {2,3,5,7,11,13,17,19,23,29};
int randomChoice = numbers[rand()%10];

Upvotes: 2

AliBZ
AliBZ

Reputation: 4099

To generate a random number you should use random() function. But if you call it twice it gives you two equal answers. Before calling random(), call srand(time()) to get fresh new random number. if you want to use for(int i = 0; ...) to create numbers, use srand(time() + i).

Upvotes: 0

Related Questions