Is there any function or method to randomly choose a number (or 2 numbers or more) from an array?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Depending on how many numbers you need, the size of the array, and whether the array needs to retain its order, you could use
std::random_shuffleto reorder the array and then just loop from 0..n-1 to get n random numbers. This works better when you want to get a lot of numbers relative to the length of the array.If that doesn’t seem appropriate, you can just use
srand()andrand() % nas an index into the array to get a pretty good approximation of a random selection.