Four digit random number without digit repetition

后端 未结 5 1617
日久生厌
日久生厌 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:19

    I don't see a problem with std::random_shuffle:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        std::string s;    
        std::generate_n(std::back_inserter(s), 10,
            []() { static char c = '0'; return c++; });
        // s is now "0123456789"
    
        std::mt19937 gen(std::random_device{}());
    
        // if 0 can't be the first digit
        std::uniform_int_distribution dist(1, 9);
        std::swap(s[0], s[dist(gen)]);
    
        // shuffle the remaining range
        std::shuffle(s.begin() + 1, s.end(), gen); // non-deprecated version
    
        // convert only first four
        auto x = std::stoul(s.substr(0, 4));
        std::cout << x << std::endl;
    }
    

    Live on Coliru

提交回复
热议问题