0
Hi, I’m writing a simulation in C++ and I have to generate some random numbers. To do this, initialize ( srand(time(NULL)) once and I have a method as follows:
void Supermercado::geraTempoProximoCliente() {
int intervaloProximoCliente = rand()%(2*tempoMedioChegada-1) +1;
printf("Intervalo para chegar outro cliente %d\n",intervaloProximoCliente);
tempoChegadaProximoCliente = getRelogio() + intervaloProximoCliente;
}
Would anyone like to tell me why every time my program generates a new interval, it is always the same throughout the entire execution of the program? Builder where seed is generated:
Supermercado::Supermercado(string nome_,int tempoSimulacao_,inttempoMedioChegada_,
int numeroDeCaixas_, int tamanhoMaximoDasFilas, Caixa caixas[]) {
listaDeCaixas = new CircularList<Caixa>();
tempoMedioChegada = tempoMedioChegada_;
relogio = 0;
clientesDesistentes = 0;
valorDesistentes = 0;
numeroDeCaixas = numeroDeCaixas_;
tempoSimulacao = tempoSimulacao_;
tempoChegadaProximoCliente = 0;
srand(time(NULL));
for(int i = 0; i < numeroDeCaixas; i++)
listaDeCaixas -> push_back(caixas[i]);
}
I urge the supermarket once only on Main and call the method run from it.
The method perform:
void Supermercado::executa() {
bool continua = true;
Caixa caixa;
geraTempoProximoCliente();
while(relogio != tempoSimulacao*3600) {
if(relogio == tempoChegadaProximoCliente)
geraTempoProximoCliente();
}
relogio++;
}
Where are you generating the seed? His problem is where it is.
– Maniero
I am generating in the Supermarket class builder, in the main I instate a Supermarket and call the method run from it. Where would be the mistake in that? I’m cracking my head on this
– Antonio Gomes
Unless srand should be initialized in the method that Rand will be called, but then it would still be stuck because it would need to generate different random numbers at each call of the method.
– Antonio Gomes
Enter the code for us to see. But it seems that the problem is to have put in the constructor.
– Maniero
I edited the question with the builder of the Supermarket.
– Antonio Gomes
I can’t reproduce your problem. http://ideone.com/ao2qah
– Maniero
Yes, seeing your link I realize that my method should work properly.
– Antonio Gomes
Maybe if you try to make a [mcve] or find the mistake on your own or at least give better subsidies for us to help.
– Maniero
Why not use the Mersenne Twist library to generate the numbers? for me the best algorithm of random numbers. https://www.cs.hmc.edu/~Geoff/mtwist.html Only download to include in project folder
– Andrey França
Thanks for the tip, Andrey. It was solved, I found a srand lost in the builder of another class that is instantiated all the time, this was causing the repetition of the number.
– Antonio Gomes