Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

c++ - Four digit random number without digit repetition

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 but it would only swap the numbers in between.

#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;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One possibility is to generate a string containing the digits, and to use the C++14 function 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 << '
';
}

Edit:

Changed to prevent a result that starts with a 0. Hat tip to @Bathsheba who indicated that this could be a problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...