c++ - Generating small range of different random numbers? -


i trying generate short range of (about 20) different / unique random numbers.

here have now:

unique_random.h:

#ifndef unique_random_h #define unique_random_h  // generates pseudo-random number in [min, max] int random_number (unsigned int min, unsigned int max) {     static bool seed_initialized = false;      if (!seed_initialized) {         seed_initialized = true;         srand((unsigned int) time(null));     }      return rand() % (max - min + 1) + min;  }   // generates random number different generated int random_number_without_these (int min, int max, std::set<int>& generated) {     int res = random_number (min, max);      // if res 1 of previous, generate again     while (s.find(res) != s.end()) {         res = random_number (min, max);     }      return res; }  #endif 

then above functions called so:

main.cpp:

#include <iostream> #include <time.h> #include <set>  #include "unique_random.h"   int main() {      std::set<int> already_generated;      (auto = 0; < 20; ++i) {          int rand =  random_number_without_these(1,20, already_generated);         already_generated.insert(rand);     }  } 

where expected result there have been generated 20 consecutively unique values. have written needs 2 functions, random_number_without_these(), random_number() , container, set<int>, in order work, why wondering:

is there easier way generate short range of unique random numbers, possibly along lines of existing code?

using std::set , e.g. std::uniform_int_distribution it's easy:

#include <iostream> #include <set> #include <random>  std::set<int> generate_numbers(const int min, const int max, const int count) {     std::set<int> numbers;     std::random_device rd;     std::mt19937 gen(rd());     std::uniform_int_distribution<> dis(min, max);      while (numbers.size() < count)     {         numbers.insert(dis(gen));     }      return numbers; }  int main() {     auto numbers = generate_numbers(1, 20, 20);     (auto const v : numbers)     {         std::cout << v << ' ';     }     std::cout << '\n'; } 

i don't see sense in using std::set since keep values sorted, , use simple loop generate numbers, or std::iota. using std::unordered_set can see point though.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -