有没有什么方法可以让您拥有一个不重复的 4 位数字 - 例如不是 1130
而是 1234
?我读到 std::random_shuffle
可以做到这一点,但它只会交换两者之间的数字。
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <random>
unsigned seed = static_cast<size_t>(std::chrono::system_clock::now().time_since_epoch().count());
using namespace std;
class Player {
private:
string playername;
public:
void setName(string b) {
cout << "Please enter your name:" << endl;
getline(cin, b);
playername = b;
}
string getName () {
return playername;
}
};
class PasswordGuessingGame {
private:
std::mt19937 random_engine;
std::uniform_int_distribution<size_t> random_generator;
public:
PasswordGuessingGame():
random_engine(seed),
random_generator(1000,9999)
{
}
int getNumber () {
return random_generator(random_engine);
}
};
int main () {
Player newgame;
PasswordGuessingGame b;
newgame.setName("");
cout << newgame.getName() << " " << "password " << b.getNumber() << endl;
}
最佳答案
一种可能性是生成包含数字的字符串,并使用 C++14 函数 std::experimental::sample()
#include <iostream>
#include <random>
#include <string>
#include <iterator>
#include <experimental/algorithm>
int main() {
std::string in = "0123456789", out;
do {
out="";
std::experimental::sample(in.begin(), in.end(), std::back_inserter(out), 4, std::mt19937{std::random_device{}()});
std::shuffle(out.begin(), out.end(), std::mt19937{std::random_device{}()});
} while (out[0]=='0');
std::cout << "random four-digit number with unique digits:" << out << '\n';
}
编辑:
已更改以防止出现以 0 开头的结果。向指出这可能是个问题的@Bathsheba 致敬。
关于c++ - 无重复数字的四位随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35479416/