C++ writes random number code that generates no repetition

  • 2020-04-02 03:03:24
  • OfStack

C++ writes random number code that generates no repetition


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;
}

Another example:


void permutation(int n, int *z_array)
{
  int i, j, k, z;
  int buffer[N];

  
  for (i=0; i<n; i++)
    buffer[i]=0;

  
  srand((unsigned)time((long *)0));

  
  for (i=0; i<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 3: make it more complicated


#include<stdio.h>
#include <time.h>
#include "iostream"
#include <math.h>
#define N 53
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 minus 52
    a[i] = b[index];    //The random number is a[I], I from 0 to N minus 1
    b[index] = b[MaxIndex-1];
    MaxIndex--;

  }
    display(a);
  return 0;
} 

The above three methods can be achieved to generate non-repeating random Numbers, the specific efficiency, friends test it.


Related articles: