Wednesday 12 October 2016

C++ Seed generation

This is a quick tutorial on how to generate pseudo-random seeds in C++. It is important to understand that, this is a two-step process: first - setting a range with ran()%10- this will produce numbers from 0 to 9 (); and second - generating a seed for the program to work with, using srand(123)- this will generate a seed based on those numbers. In this tutorial I will go over 3 examples to demonstrate different outcomes.

The code below will output the same 10 numbers every time the program is ran.

#include "stdafx.h" // - Visual Studio only
#include <stdlib.h>
#include <iostream>

using namespace std;

void genRanNum() {
 int num = 10;
 do {
  cout << rand() % 10 << endl;
  num--;
 } while (num>0);
} 

 

int main()
{

 genRanNum();//--produce 10 random numbers
 cin.get();//-- pause
 
    return 0;

}

To generate a seed that will be different to the default output but same every time it is used, use srand(23232) - with numbers of your choice.

#include "stdafx.h" // - Visual Studio only
#include <stdlib.h>
#include <iostream>

using namespace std;

void genRanNum() {
 int num = 10;
 do {
  cout << rand() % 10 << endl;
  num--;
 } while (num>0);
}

void seedGen(int seed=0) {
 srand(seed);
}
int main()
{
 seedGen(3245);//--generate a seed based on numbers

 genRanNum();//--produce 10 random numbers
 cin.get();//-- pause
 
    return 0;

}

And finally to produce a pseudo-random seed every time the program is used, parse current time value into the srand(time(0)) function as a parameter. Include <time.h> header to work with time.
 
#include "stdafx.h" // - Visual Studio only
#include <stdlib.h>
#include <iostream>
#include <time.h>

using namespace std;

void genRanNum() {
 int num = 10;
 do {
  cout << rand() % 10 << endl;
  num--;
 } while (num>0);
}


void randSeedGen() {
 srand(time(0));
}

int main()
{
 randSeedGen();//--generate a random seed based on time
 
 genRanNum();//--produce random 10 number
 cin.get();//-- pause
 
    return 0;

}

No comments:

Post a Comment