tags:

views:

243

answers:

3

hi all, i am new to iPhone Programing i have 10 number say (1,2,3,4,5,6,7,8,9,10) i want to choose randomly 1 number from above 10 number.so how can i choose random number from a set of numbers

A: 

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).

Ali Bozorgkhan
The seed function for random() is srandom(). So either use random() and srandom() or rand() and srand(), but do not mix the two. Generally, random() is recommended because the random algorithm is a little better.
Ole Begemann
A: 

something like this

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

}

PurplePilot
whether you want to say if i want to choose random number from 10 numbers , then use (random()%10) +1. if yes then if there are only four number, then i use following formula (random()%4) +1. Please suggest
Rupesh
+2  A: 

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];
Tom
If you want the possibility of a number to be picked the same for each number, don't use `%`!
Joey
As RAND_MAX is normally pretty huge, there's only likely to be a tiny tiny variation in the probabilities.
Tom
*"Show me how to get a random number"* — "Here" — *"Nice, thanks, anything to watch out for?"* — "Yes, the distribution isn't uniform, but it won't matter" — *"It won't matter? Hey, I'm generating a billion billion values here, and you say it wouldn't matter?"* ... it's not that hard to get right and as long as you don't know much about the OP's requirements don't give them an inferior answer.
Joey