random numbers

hello, I want to write simple implementation of genetic algorithm but I have a problem even at the beginning :d when i initialize my "random" cromosomes they are the same in whole generation even if i use ctime please tell me what i am doing wrong.

#include<iostream>
#include<ctime>
#include<random>
using namespace std;
const int maxgeneration = 1000;
const int popsize = 50;
const int mutation = 0.15;
const int crossover = 0.8;
const int gensize = 6;


struct bacetria{
int m[6]={1,0,0,1,0,1};

};

struct phage{
int m[6]={0,0,0,0,0,0};
phage init (){
default_random_engine dre(time(0));
uniform_int_distribution<int> di (0,1);
int k =di(dre);
for(int i=0; i<6; i++)
m[i]=di(dre);
}
void show (){{
for (int i=0; i<6; i++)
cout<<m[i]<< " ";
}
cout<<endl<<endl;
}
};



int main (){
phage population [maxgeneration];
for (int i=0; i<maxgeneration; i++)
population[i].init();


for (int i=0; i<maxgeneration; i++)
population[i].show();

phage p;
p.init();
for (int i=0; i<6; i++)
cout<<p.m[i]<<endl;


}
Last edited on
The time function usually returns the time in seconds, and all phage objects are very likely to be created within the same second, so that would mean all phage object will seed the random engine with the same value which results in them the all getting the same random numbers.

To fix this problem you could create just one random engine that you seed once and use throughout your whole program.
thank you very much i thought that was the problem but for same reason i did not consider making it global thank you again!
Topic archived. No new replies allowed.