Is there any way you can have a 4 digit number without repetition - e.g. not 1130
but 1234
? I read std::random_shuffle
could do this b
I don't see a problem with std::random_shuffle
:
#include
#include
#include
#include
#include
int main()
{
std::string s;
std::generate_n(std::back_inserter(s), 10,
[]() { static char c = '0'; return c++; });
// s is now "0123456789"
std::mt19937 gen(std::random_device{}());
// if 0 can't be the first digit
std::uniform_int_distribution dist(1, 9);
std::swap(s[0], s[dist(gen)]);
// shuffle the remaining range
std::shuffle(s.begin() + 1, s.end(), gen); // non-deprecated version
// convert only first four
auto x = std::stoul(s.substr(0, 4));
std::cout << x << std::endl;
}
Live on Coliru