How can I generate truly random numbers in C++ without getting repeated values frequently?

How to generate a random number in C++ without repetition?

I’m trying to create a dice-based game and need to generate random numbers in C++ to simulate rolling a die (values between 1 and 6). Using:

#include <cstdlib> 
#include <ctime> 
#include <iostream>

using namespace std;

int main() 
{ 
    srand((unsigned)time(0)); 
    int i;
    i = (rand() % 6) + 1; 
    cout << i << "\n"; 
}

doesn’t work well because when I run the program multiple times, I get repeated values like this:

6  
1  
1  
1  
1  
1  
2  
2  
2  
2  
5  
2  

How can I generate truly random numbers in C++ without getting repeated values frequently?

Instead of generating numbers randomly each time, shuffle a list of unique values:

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

int main() {
    std::vector<int> dice = {1, 2, 3, 4, 5, 6};
    std::random_device rd;
    std::mt19937 g(rd()); 

    std::shuffle(dice.begin(), dice.end(), g); 

    for (int num : dice) {
        std::cout << num << " ";
    }
    return 0;
}

:small_blue_diamond: Ensures no repetition within a full cycle of rolls.

If you want random values while avoiding repetition, store them in a std::unordered_set:

#include <iostream>
#include <unordered_set>
#include <cstdlib>
#include <ctime>

int main() {
    std::srand(std::time(0));  
    std::unordered_set<int> used;
    
    while (used.size() < 6) {  
        int roll = (std::rand() % 6) + 1;  
        if (used.insert(roll).second) {  
            std::cout << roll << " ";
        }
    }
    return 0;
}

:small_blue_diamond: Prevents duplicates dynamically while still keeping the numbers random.

The default rand() function is not truly random—instead, use the Mersenne Twister generator:

#include <iostream>
#include <random>

int main() {
    std::random_device rd;  
    std::mt19937 gen(rd());  
    std::uniform_int_distribution<int> dist(1, 6);  

    for (int i = 0; i < 6; ++i) {
        std::cout << dist(gen) << " ";
    }
    return 0;
}

:small_blue_diamond: Provides better randomness than rand().