Last active
February 2, 2018 12:01
-
-
Save Liam0205/42ae9968b1e0edaada8f1e0ebbcc8158 to your computer and use it in GitHub Desktop.
generate distinct random numbers in C++.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <unordered_set> | |
| #include <random> | |
| template <typename IntType = int> | |
| class distinct_uniform_int_distribution { | |
| public: | |
| using result_type = IntType; | |
| private: | |
| using set_type = std::unordered_set<result_type>; | |
| using distr_type = std::uniform_int_distribution<result_type>; | |
| public: | |
| distinct_uniform_int_distribution(result_type inf, result_type sup) : | |
| inf_(inf), sup_(sup), range_(sup_ - inf_ + 1), distr_(inf_, sup_) {} | |
| void reset() { | |
| uset_.clear(); | |
| distr_.reset(); | |
| } | |
| template <typename Generator> | |
| result_type operator()(Generator& engine) { | |
| if (not(uset_.size() < range_)) { std::terminate(); } | |
| result_type res; | |
| do { res = distr_(engine); } while (uset_.count(res) > 0); | |
| uset_.insert(res); | |
| return res; | |
| } | |
| result_type min() const { return inf_; } | |
| result_type max() const { return sup_; } | |
| private: | |
| const result_type inf_; | |
| const result_type sup_; | |
| const size_t range_; | |
| distr_type distr_; | |
| set_type uset_; | |
| }; | |
| int main() { | |
| std::random_device rd; | |
| std::mt19937 mt(rd()); | |
| distinct_uniform_int_distribution<> dis(1, 100); | |
| for (size_t i = 0; i != 20; ++i) | |
| std::cout << dis(mt) << std::endl; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment