Click here to Skip to main content
15,892,537 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
hello,
i am a c++ beginner. i came across this question regarding rand function in c++. it wants us to program a code which generates a random number from a given set of numbers. i have herd about the rand() function but not about this feature regarding it!! i have already googled it!! but have not found a satisfying solution. please help me.
Posted

There are a couple of approaches you could use here:
The Brute-Force-And-Ignorance approach is to generate a random number using rand which is between the largest and smallest numbers in the valid set. If this number is in the set, use it. If it isn't, then generate another number and check again. This works, but...it's very slow, and may take an infinite time to generate a new number.

The best way to do it is to set up an array containing the set of valid numbers, and generate a number which is between zero and the number of items (minus one) using rand, and then use that number as an index to select a number from the array. This will take the same amount of time to select a number every time you try. And it can be extended to remove the number from the set so there are never duplicates, either - this is the way "intelligent" music players shuffle tracks for example, or the way to "shuffle" a pack of cards.
 
Share this answer
 
I assume numbers is a set of given numbers.Then have a try with..
C++
int numbers[] = { 3, 13, 22, 57, 417 };
int length = sizeof(numbers) / sizeof(int);
int randomNumber = numbers[rand() % length];
 
Share this answer
 
Comments
pasztorpisti 18-Aug-13 9:38am    
+5, Although this is often not discrete uniform distribution that really doesn't matter in most cases.
ridoy 18-Aug-13 12:13pm    
Thanks pasztorpisti,:).
I googled and this[^] was top of the list.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900