3

I want to generate different random numbers . I used srand and rand , but in my output some numbers are identical .

This is my output : enter image description here

How to do with srand to generate different numbers ?

#include<iostream>
#include<time.h>
#include <windows.h>

int main(){
    time_t t;
std::vector<int> myVector;
srand((unsigned)time(NULL));

for (int i = 0; i < 40; i++){

    int b = rand() % 100;
    myVector.push_back(b);
    std::cout << myVector[i] << std::endl;
}
Sleep(50000);

}
9
  • 1
    Do you mean it generates the same random sequence every time it's executed? Apr 28, 2016 at 18:13
  • 4
    Random numbers still include identical numbers, there's no guarantee the random generator engine generates unique numbers. Apr 28, 2016 at 18:13
  • You could push the results to an array, then remove duplicates Apr 28, 2016 at 18:13
  • And how can I do to generate unique numbers?
    – Michelle
    Apr 28, 2016 at 18:14
  • If you want unique random numbers you'll need to either remove duplicates after generation as @Timothy Kanski suggested or use something like std::find to check if the container already contains the generated number during the loop; or use a different container such as std::set to avoid equivalent values occurring. Apr 28, 2016 at 18:16

7 Answers 7

7

One easy way is to add all numbers from 0-99 to a vector and shuffle it, then you can get as many (up to 100) non repeating random numbers as you require.

#include <algorithm>
#include <chrono>
#include <iostream>
#include <random>
#include <vector>

int main(void) {

    std::vector<int> numbers;

    for(int i=0; i<100; i++)       // add 0-99 to the vector
        numbers.push_back(i);

    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    std::shuffle(numbers.begin(), numbers.end(), std::default_random_engine(seed));

    for(int i=0; i<40; i++)        // print the first 40 randomly sorted numbers
        std::cout << numbers[i] << std::endl;

}
2
  • 4
    Instead of the loop adding the numbers to the vector, one could set its size correctly to begin with, and then use std::iota. Aug 14, 2020 at 17:22
  • An explanation to your answer? How does this guarantee non-identical numbers?
    – Mecanik
    Oct 8, 2022 at 5:14
3

You could use a set:

std::set<int> numbers;
while (numbers.size() < 40)
{
    numbers.add(rand() % 100);
}

and then copy it into a vector if necessary.

2
  • 1
    + Shuffle the values after copying them to vector, or they'll be sorted.
    – user5726937
    Apr 28, 2016 at 18:20
  • 1
    @Roux or use an std::unordered_set if c++ 11 is available Apr 28, 2016 at 18:20
1

As for me, the idea of using set is not so good, because the generating time of every new value increases. If you have enough memory it seems that usage of an array can be preferable.

In the next code, I don't use shuffle, instead, I use a random function just size times to choose one value. I add it to the destination vector, then in the source array, swap the value with the last element and decrease arr_size.

/*
 * Return random unsigned int value using intrinsic
 * */
unsigned getRandom() {
    unsigned val;
    _rdrand32_step(&val);
    return val;
}

/*
 * Return a vector<int> of uniq numbers in a range of [min ... max).
 *
 * @param min - min value.
 * @param max - max value.
 * @param size - amount of uniq numbers (size <= max-min).
 * */
vector<int> getUniqNumbers(int min, int max, unsigned size) {
    int arr_size = max - min;
    int *a = new int[arr_size];
    for (int i = 0; i < arr_size; i++) {
        a[i] = min + i;
    }

    vector<int> numbers(size);
    for (int i = 0; i < size; i++) {
        unsigned u_rand = getRandom() % arr_size;
        numbers[i] = a[u_rand];
        a[u_rand] = a[--arr_size];
    }
    delete[] a;
    return numbers;

}
0

srand number generator can give identical numbers.

You could implement a solution which deletes duplicates not adding them to the vector. For example:

#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    std::vector<int> myVector;
    srand((unsigned)time(NULL));

    while(myVector.size() < 40)
    {
        int b = rand() % 100;
        if ( !(std::find(myVector.begin(), myVector.end(), b) != myVector.end()))
        {
           myVector.push_back(b);
           std::cout << myVector.at(myVector.size()-1) << std::endl;
        }

    }
    Sleep(50000);

    return 0;
}
0

An easy way of getting rid of duplicates is using std::unique in <algorithm>.

Here is an example of that in use:

#include <vector>
#include <iostream>
#include <algorithm>
#include <random>

int ran(int min, int max)
{
    std::random_device r;
    std::mt19937 gen(r());
    std::uniform_int_distribution<> dis(min, max);
    return dis(gen);
}

int main()
{
    const int fill_size = 10; 
    const int min = 1;        // min random number
    const int max = 100;      // max random number

    std::vector<int> vec;
    while (vec.size() != fill_size) {
        vec.emplace_back(ran(min, max)); // create new random number
        std::sort(begin(vec), end(vec)); // sort before call to unique
        auto last = std::unique(begin(vec), end(vec));
        vec.erase(last, end(vec));       // erase duplicates
    }

    std::random_shuffle(begin(vec), end(vec)); // mix up the sequence
    for (const auto& i : vec)                  // and display elements
        std::cout << i << " ";
}
-1

You can easily achieve a unique set of random numbers writing:

#include<iostream>
#include<vector>

int main(){
    std::vector<int> myVector;
    srand((unsigned)time(NULL));

    for (int i = 0; i < 40; i++) {
        int b = rand() % 100;
        if(!std::find(std::begin(myvector),std::end(myvector),b)) {
            myVector.push_back(b);
            std::cout << myVector[i] << std::endl;
        }
    }
}
-1

This is a statistical (mathematical) issue. Random numbers may be identical to eachother. If you need unique numbers, you must check to see if they are used before. For example like this:

for (int i = 0; i < 40; i++){

    int b = rand() % 100;
    for (int j = 0; j < i; j++){
        if(myVector[j]==b)i--;
        else{
            myVector.push_back(b);
            std::cout << myVector[i] << std::endl;
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.