c++ - 无重复数字的四位随机数

标签 c++ random

有没有什么方法可以让您拥有一个不重复的 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/

相关文章:

c++ - 如何将 mat 转换为 array2d<rgb_pixel>?

c++ - Qt:单击后开始编辑单元格

excel - 如何使用 Excel VBA 打乱多个独立数据列表

mysql - 无限滚动混洗的数据库值

c++ - 命名空间和范围可见性问题

c++ - 多重继承层次结构

c++ - 如何在类层次结构中处理 CRTP?

arrays - 如何从两个列表中快速打印

C生成最大长度的随机字符串

c++ - 闭区间均匀随机数发生器