1

I am programming using c++11. The program is better compatible on mac, linux and windows, if possible. If not, the program should be work well on linux at least, and I would not consider mac and windows platform. I want to return random number sequence from [a, b]. The count might equal to b-a or less than b-a. Numbers in the sequence should be different with each other, e.g. 9 8 6 1 3 0 7 for [0, 10]. There should not be, like two 8 or three 1, duplicate numbers in it. Which random generator should I use? uniform_int_distribution? or uniform_real_distribution? Does uniform_real_distribution better than uniform_int_distribution? Or Is there any other possible ways? Do I have to create my own random number list like this Unique (non-repeating) random numbers in O(1). Thanks for your time.

Community
  • 1
  • 1
Nick Dong
  • 3,638
  • 8
  • 47
  • 84
  • A number generator that produces no repeated values is not as random as one that does. Yes, you should use the Fisher-Yates shuffle or similar as referenced in the link you provided. Alternatively, you could use a cyclical step through your numeric range which is relatively prime to the size of the range, but that would not be considered "random" at all. It depends what you want to do with this sequence though. – paddy Feb 23 '16 at 03:50
  • uniform_real_distribution with double type argument seems hardly to return repeat number in finite range [a, b], right? – Nick Dong Feb 23 '16 at 06:12
  • 1
    Sure, but "hardly" is very different from "never". Also in your case "same number" refers to integers. If you were to use a `double` generator for this problem, you still need to clamp the result to some integer, and then you have the same problem again. The point is that statistical distributions do not guarantee 100% coverage of N values for only N numbers. In fact, the chance of it happening in a uniform distribution is `1 / N!`, which is almost guaranteed to never happen. That is why you need to generate your numbers and randomly shuffle or select them to meet your requirements. – paddy Feb 23 '16 at 06:18

1 Answers1

3

Well, the comments are right, you need a shuffling strategy. Take a look at the following example in C++11:

std::vector<int> myNums(b-a);
std::iota(myNums.begin(), myNums.end(), a);
std::random_shuffle(myNums.begin(), myNums.end());

Of course, you can implement your own approaches, but C++ STL has some really cool algos implemented by default.

asalic
  • 664
  • 3
  • 6