I notice each time that I run my program the random number, represented by percentage, is always climbing. As in, the previous random number is always smaller than the next random number. What can I do to keep this from happening?
#include <iostream>
#include "Simulation.h"
void runOneGame();
int main(void){
Simulation playGame;
playGame.runOneGame();
return 0;
}
#ifndef SIMULATION_H
#define SIMULATION_H
class Simulation{
private:
int harePosition, turtlePosition;
public:
Simulation() {};
void moveTortoise(unsigned int *ptrTurtle);
void moveHare(unsigned int *ptrHare);
void runOneGame();
};
#endif
#include "Simulation.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <unistd.h>
void Simulation::moveTortoise(unsigned int *ptrTurtle){
unsigned seed = time(0);
srand(seed);
int percentage = rand() % 100 + 1;
std::cout << percentage << "%" << std::endl;
if(percentage >= 50){ *ptrTurtle += 3; } //fast pace 50% 3 squares forward
else if(percentage < 50 && percentage >= 25){ *ptrTurtle += 1; } //slow pace 25% 1 square forward
else if(*ptrTurtle > 6 && percentage < 25){ *ptrTurtle -= 6; } //slip 25% 6 squares backward
else{ *ptrTurtle = 1; } // set block position to 1 when block position is less than 6
std::cout << "T " << *ptrTurtle << std::endl;
}
void Simulation::moveHare(unsigned int *ptrHare) {
unsigned seed = time(0);
srand(seed);
int percentage = rand() % 100 + 1;
if(percentage >= 70){ *ptrHare += 1;} //small hop 30% 1 square forward
else if(percentage >= 45 && percentage < 70){ *ptrHare = *ptrHare; } //sleep 25% No move
else if(percentage >= 25 && percentage < 45) { *ptrHare += 9; } //big hop 2O% 9 squares forward
else if(*ptrHare > 2 && percentage >= 5 && percentage < 25){ *ptrHare -= 2; } //small slip 20% 2 squares backwards
else if(*ptrHare > 12 && percentage >= 1 && percentage < 5) { *ptrHare -= 12; } //big slip 5% 12 squares backward
else {*ptrHare = 1; } // set block position to 1 when block position is less than squares backwards
std::cout << "H " << *ptrHare << std::endl;
}
void Simulation::runOneGame(){
unsigned int turtlePosition, harePosition = 1; //starting position
unsigned int *ptrTurtle = &turtlePosition;
unsigned int *ptrHare = &harePosition;
bool iterate = true;
int loop = 1;
//std::cout << "OUCH!" << std::endl;
while(usleep(1000000) == 0 && iterate){
std::cout << loop << std::endl;
if(*ptrTurtle == *ptrHare){std::cout << "OUCH!" << std::endl;}
moveTortoise(ptrTurtle);
moveHare(ptrHare);
if(*ptrHare >= 70){iterate = false; std::cout << "HARE WINS!" << std::endl;}
if(*ptrTurtle >= 70) {iterate = false; std::cout << "TORTOISE WINS!" << std::endl;}
std::cout << std::endl;
loop++;
}
}
OUTPUT:
1 OUCH! 35% T 2 H 10
2 42% T 3 H 19
3 49% T 4 H 19
4 56% T 7 H 19
5 63% T 10 H 19
6 70% T 13 H 20
7 77% T 16 H 21
8 84% T 19 H 22
9 91% T 22 H 23
10 98% T 25 H 24
11 5% T 19 H 22
12 12% T 13 H 20
13 19% T 7 H 18
14 26% T 8 H 27
15 33% T 9 H 36