C + + write generation of _c random number code language

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.