I was wondering if anyone knows an easy way to generat random numbers, but in a sequence so that no random number is used more than once? I only need to generate under 50 random numbers or so. i.e. with a set = {1,2,3,4,5} I want to generate a random sequence like {3,5,1,4,2} where no numbers show up more than once. Thanks
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int main()
{
srand(time(NULL)); // Set seed for random numbers
vector<int> initialNumbers (50);
vector<int> randomNumbers (50);
int randomNumber;
for (int i = 0;i<50;i++) // Set vector with the numbers 1-50
{
initialNumbers[i]=i+1;
}
for (int i = 0;i<50;i++) // Take a random member of initialNumbers and put it in randomNumbers, then erase that member from initialNumbers
{
randomNumber = rand() % (50-i);
randomNumbers[i] = initialNumbers[randomNumber];
initialNumbers.erase(initialNumbers.begin()+randomNumber);
}
}
Also if you replace all places where 50 shows up with a variable you should be able to adjust how many numbers are generated.
You should definitely use that algorithm if it works for you. I just wanted to give shank8 an idea of how to do it manually, because learning the underlying concept can teach you things useful for when there isn't a STL library for you to use.
It uses two arrays. random_shuffle only needs the array you give it.
It calls erase many times. Erase itself has linear time complexity, so in the end, your algorithm will have a complexity somewhere between n2/2 and n. random_shuffle always has linear complexity.