C + + Write generates a random number code that does not duplicate
vector<int> getrandom (int total)
{
srand (int) time (NULL));
std::vector<int> input = *new std::vector<int> ();
for (int i = 0; i < total; i++) {
input.push_back (i);
}
vector<int> output = *new vector<int> ();
int end = Total;
for (int i = 0; i < total; i++) {
Vector<int>::iterator iter = Input.begin ();
int num = random ()%end;
iter = Iter+num;
Output.push_back (*iter);
Input.erase (ITER);
end--;
}
return output;
}
One more example:
void permutation (int n, int *z_array)
{
int i, j, K, Z;
int buffer[n];
/* Initialize array *
/for (i=0; i<n; i++)
buffer[i]=0;
/* Prepare to generate random numbers, seeded at current time/
Srand ((unsigned) ((long *) 0));
/* Obtain the random data for the i<n; (
i=0; i++) {//
* obtain 0~ (n-i) (*
z = rand ()% (n-i);
j=0; k=0;
while (j<=z) {
if (buffer[j+k]==0) j + +;
else k++;
}
Buffer[j+k-1]=1;
z_array[i]=j+k-1;
}
return;
}
Method Three: to a complex point
#include <stdio.h>
#include <time.h>
#include "iostream"
#include <math.h>
# Define N
using namespace std;
Print array
void display (int *a)
{for
(int i =0;i<n;i++)
{
cout<< "" <<a[i] << "";
}
}
int main (void)
{
int b[n],a[n];
for (int i =0;i<n;i++)
{
b[i] = i+1;
}
Random (a);
Srand ((unsigned) time (NULL));
int maxindex = N;
for (i= 0;i<n;i++)
{
//
int index = (int) rand ()%maxindex;//a random index of 0-52
a[i] = b[index];
//random numbers to the a[i],i from 0 to N-1
b[index] = b[maxindex-1];
maxindex--;
}
Display (a);
return 0;
All of the above 3 methods can be achieved to generate a random number of duplicates, the specific efficiency, the small partners themselves test it.