I want to understand how it is better to get random numbers, for example, for some kind of game. On this occasion, I ask for your help. So that I can imagine myself well, please explain to me with a simple example what is better and why.

class Random_numbers { int m, s; public: Random_numbers(int max, int start = 0) : m(max + 1), s(start) {} int operator ()() { return rand() % m + s; } }; int main() { const int N = 20, r = 100; std::vector<int> v(2 * r); auto f = v.begin(), end = v.end(); std::generate(f, end, []() { static int n = -100; return ++n;}); std::random_shuffle(f,end); std::copy_n(f, N, ostream_iterator<int>(std::cout, " ")); std::cout << std::endl << std::endl; // второй способ Random_numbers Rn(2 * r, -100); int number = 0; srand(time(0)); for (int i = 0; i < N; ++i) { number = Rn(); std:: cout << number <<' '; } return 0; } 

What is the difference between these 2 ways and which way will give the result preferable and why? If there are a lot of questions, I’ll be satisfied with the answer only to the first question.

  • one
    It is preferable to use the library <random> ... - Harry
  • that is, there are certain classes for random numbers, or what? - AR Hovsepyan
  • 2
    There are generators and distributions that come together to produce random numbers that are needed — let's say, much richer and more reliable than rand() . - Harry
  • @Harry, this is just what you need, but the topic is not very pleasant for me, and I did not know about it: we will use what we have - AR Hovsepyan
  • This is a big topic ... In short - en.cppreference.com/w/cpp/numeric/random - Harry

1 answer 1

These methods have a fundamental difference. In the first, you generate an array of non-repeating numbers, mix it up and consistently output the first N elements of this array. Those. derived items are guaranteed not to be repeated.

In the second case, you output N randomly generated numbers lying in a range. Whether these numbers will be all pairwise distinct or whether they will be repeated - no one knows. The probability of repetition is directly proportional to the number of generated numbers and inversely proportional to the number of possible numbers (in fact, the width of the range)

  • and the distribution quality of the rand () function, except that numbers can be repeated? ... - AR Hovsepyan
  • @ARHovsepyan It makes no sense to talk about the quality of distribution on 20 elements. Generate 5000 elements, calculate the frequency of each drop and evaluate the quality of the distribution - Anton Shchyrov
  • and I will, thank you - AR Hovsepyan
  • I probably didn’t formulate the question, because I didn’t read everything I needed in your answer, but since he helped me figure it out, I’ll accept it - AR Hovsepyan