有什么办法可以让您无重复的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的帽子提示指出这可能是个问题。

09-30 16:44
查看更多