如何精确产生不重复随机数,
比如在10范围内产生10个不重复的数字
- C/C++ code
for(i=0; i<10; ++i){ num = rand() % 10;}
上面这种情况怎么能让他产生的10 个数字不重复?
要求只允许循环10次,产生的数字必须在 0 - 10以内
正确的结果
0 5 6 2 1 3 7 4 8 9
5 2 3 7 8 9 0 6 1 4
错误的结果
0 0 6 2 1 3 2 8 9 4
[解决办法]
洗牌法.
[解决办法]
[解决办法]
- C/C++ code
#include <vector>#include <iostream>#include <algorithm>#include <ctime>using namespace std;int VecRandom(int num){ return rand() % num;}int main(){ srand ( unsigned ( time (NULL) ) ); int Array[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; vector<int> Vec( Array, Array + _countof( Array ) ); random_shuffle( Vec.begin(), Vec.end(), VecRandom); copy ( Vec.begin(), Vec.end(), ostream_iterator<int> (cout, "\n") ); return 0;}