Four digit random number without digit repetition

后端 未结 5 1613
日久生厌
日久生厌 2021-01-16 18:46

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 b

5条回答
  •  北海茫月
    2021-01-16 19:22

    One possibility is to generate a string containing the digits, and to use the C++14 function std::experimental::sample()

    #include 
    #include 
    #include 
    #include 
    #include 
    
    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';
    }
    

    Edit:

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

提交回复
热议问题