Advanced rand() uses

I know the basic uses of the rand() function, but I was wondering if there were more advanced uses for it. I ask this because I am making a program where a number from 0-60 is generated repetitively but I'd like it to not generate the same number twice.

So how would you exclude a number from this rand() function example:

 
rand % 60 + 1;
Last edited on
The first solution that comes in my mind is to populate a vector of int with all the number generated and for each generation check in to the vector. This solution scale very bad though.
I thought of that solution, but the problem is that if you get down to the point where there are 2 numbers left, it will keep searching over and over until it hits one of those 2 numbers and that will take up a lot of unnecessary processing and possible a crash.
Another way is to store all possible values 1-60 in an array or vector and then shuffle them so that the order becomes random. Then you can just pick the values one after another in the order they appear.
Another solution is to have a vector of int, and use the result of the rand % the length of vector as index. Then you have only to delete the item from the vector and update the length. How about this?
Great idea! Thank you both for posting the same idea at the exact moment lol
or you can use a loop to make sure that your number is not generating two equal numbers.
You guys really over looked @Peter87's solution. His is the best IMHO. Just fill an array then shuffle it and iterate through it.

http://www.cplusplus.com/reference/algorithm/
http://www.cplusplus.com/reference/algorithm/generate/
http://www.cplusplus.com/reference/algorithm/random_shuffle/ or http://www.cplusplus.com/reference/algorithm/shuffle/

Here is a very simple version:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <vector>
#include <algorithm>

int generateVector(void)
{
    static int i = 0;
    return i++;
}

int main()
{
    int const numbers = 61; //0-60
    std::vector<int> randomNumbers(numbers);
    std::generate(randomNumbers.begin(), randomNumbers.end(), generateVector);
    std::random_shuffle(randomNumbers.begin(), randomNumbers.end());

    for(int const &number : randomNumbers) std::cout << number << ' ';

    return 0;
}
(results may vary)
4 51 11 15 24 35 17 36 26 50 33 39 19 2 47 56 59 18 32 40 5 21 57 12 14 42 27 6 45 58 30 38 13 37 3 54 55 53 9 22 8 23 20 34 1 10 31 0 46 41 48 28 52 43 16 60 49 7 44 25 29  

Last edited on
Topic archived. No new replies allowed.