Jeff Johnson Jeff Johnson - 5 months ago 23
C++ Question

How to generate a 4-digit numbers with digits from 1 to 6 only?

I'm looking for a way to generate a 4 digit number with digits from 1 to 6 like 1234, 1251, 3243 ... and so on.

I want it for my

makeDigitsToGuess()
method in my
MastermindDigits
class. Every time a user starts the game, this function should be called and generate a 4 digit number containing only digits from 1 to 6.

This is what I've tried so far:

srand(time(0));
cout << "RANDOM NUMBER: " << (rand() % 6 + 1)
<< (rand() % 6 + 1)
<< (rand() % 6 + 1)
<< (rand() % 6 + 1) << endl;


this is how far I got on my own. The next step I was thinking about, was to create a
vector
in my method where I could
push_back
those 4x generated random numbers.

Does this make sense? Is there an easier way to code it?

Answer Source

I suggest this solution using the C++11's std::uniform_int_distribution.

#include <iostream>
#include <random>

int generateFour()
{
    int result=0;
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(1, 6);
    for (int n=0; n<4; ++n)
    {
        result=result*10+dis(gen);
    }
    return result;
}

int main() 
{

    std::cout << generateFour() << std::endl;
    return 0;
}