views:

83

answers:

1

Possible Duplicate:
Create Random Number Sequence with No Repeats

I'm trying to generate unique session IDs. Each session ID is a random integer. The main requirement is that each session ID is unique. I'm trying to find the most efficient algorithm to do this.

Scenario: Generate 10 random numbers from 1 to 10 inclusive.

My algorithm:

// Generate unique pseudo-random numbers between 1 and 10 inclusive

vector<int> vList;

for (int i = 1; i <= 10; i++)
{
    vList.push_back(i); 
}

// vList should have {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

for (int j = 1; j <= 10; j++)
{
    int k = (rand() % vList.size());
    cout << vList[k] << " ";
    vList.erase(vList.begin() + k);
}

// Sample output: 5 1 10 7 8 2 4 9 3 6

This algorithm has a time complexity of O(n) and a space complexity of O(n). Is there a more efficient algorithm?

+1  A: 

Choose two large primes(a,b : a < b).

For the n:th ID (n < b) the ID is a^n mod b.

This will always give n unique pseudorandom numbers.

Marcus Johansson