四位数随机数,无数字重复 [英] Four digit random number without digit repetition

查看:62
本文介绍了四位数随机数,无数字重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让您获得一个4位数的数字而无需重复-例如不是 1130 ,而是 1234 ?我读过 std :: random_shuffle 可以做到这一点,但它只会在两者之间交换数字.

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;
    }

推荐答案

一种可能是生成包含数字的字符串,并使用C ++ 14函数 std :: experimental :: sample()

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 << '\n';
}

已更改为防止以0开头的结果.@Bathsheba的帽子提示,这可能是一个问题.

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

这篇关于四位数随机数,无数字重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆