Generates 6 random numbers in 1-33, no duplicates
------------------------------------------------------------------------
Method 1. Each random number is generated to facilitate the comparison of all previous random numbers, and if there are duplicates, do not, re-select.
However, this method is time-consuming and can cause huge problems when the volume of data is huge and there are some limitations.
For example, to generate 10,000 random numbers, with a range of 0-9999 and no repetition, the last few random numbers can take a long time to filter out.
Method 2. Here we think from another angle,
Let's say we've got an array with an array length of 10000, which stores data 0-9999, and I'm now trying to figure out how to make a 10,000-number random arrangement.
Then I get a random number, and if I just want 100 of them, I'll take 100 out of the front. Here, we use a function random_shuffleinside the algorithm.h to do simple processing.
1234567891011121314151617181920212223 |
#include <algorithm>
#include <iostream>
#include <vector>
using namespace
std;
void
randperm(
int
Num)
{
vector<
int
> temp;
for
(
int
i = 0; i < Num; ++i)
{
temp.push_back(i + 1);
}
random_shuffle(temp.begin(), temp.end());
//for (int i = 0; i < temp.size(); i++)
for
(
int
i = 0; i < 6; i++)
{
cout << temp[i] <<
" "
;
}
}
int
main()
{
randperm(33);
return
0;
}
|
Method 3. use a linked list (sort in the unique can go to weight) or set
12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
#include<iostream>
using
namespace std;
#include <stdlib.h>
#include <time.h>
#include <list>
#include <set>
int
act_rand(
int
a,
int
b)
{
int m =
rand
()%(b-a+1)+a;
cout <<
"m = "
<< m << endl;
return
m;
}
void
genRandomList()
{
list<
int
> l;
while
( l.size() < 6)
{
int
randnum=act_rand(1,6);
l.push_back(randnum);
l.sort();
l.unique();
}
list<
int
>::iterator it;
//迭代器
for
(it = l.begin(); it != l.end(); it++)
{
cout << *it <<
‘ ‘
;
}
}
void
genRandomSet()
{
set<
int
> s;
while
( s.size() < 6)
{
int
randnum=act_rand(1,33);
s.insert(randnum);
}
set<
int
>::iterator it;
//迭代器
for
(it = s.begin(); it != s.end(); it++)
{
cout << *it <<
‘ ‘
;
}
}
|
Reference:
C + + generates non-repeating random integers-~ ~ (V_V) ~ ~-CSDN Blog
http://blog.csdn.net/pythontojava/article/details/45132059
Random numbers and non-repeating random numbers in C + +-Pilgrimage Suns-Blog Park
Http://www.cnblogs.com/salan668/p/3652532.html
(1) C + + produces non-repeating random number _ Jin Tingpo _ Sina Blog
Http://blog.sina.com.cn/s/blog_4522f0b8010008r5.html
Use C + + to generate 6 random numbers in 1-33, no duplicates