Write some C++ code that simulates an 8-car race. In the code each car will advance, in each step, a distance determined by a random probability between 0 and 1.
• If the probability is greater than 0.8, the runway is free and will advance 83 meters
• if it is between 0.6 and 0.8, there is competition and it will advance 50 meters
• if it is between 0.4 and 0.6, you will have to slow down a bit and you will only go 30 meters
• if it is between 0.2 and 0.4, it needs a pit stop and will stop three steps
• if it is less than 0.2, they block his way and he will go back 10 meters
Each advance or retreat will be counted as a step, with the exception of the pit-stop, which is 3 steps. The one who travels 300 km in the fewest steps will win.
Generate a code that simulates car racing and prints the list of the top three finishers and the number of steps required to win. Each car must have a name.
For example, a result of the code could be:
Ganador: Mercedes, cantidad de pasos: 11852
2do puesto: McLaren, cantidad de pasos: 11984
3er puesto: Ferrari, cantidad de pasos: 12041
I tried to do it with a void function and this is what I got:
#include <iostream>
using namespace std;
void autos(int nombre);
void autos(int nombre, string _auto) {
int m = 0;
float v;
do {
v = (rand() % 9 + 1) / 10.0;
if (v > 0.8) {
m += 80;
nombre += 1;
}
else if (v > 0.6 && v < 0.8) {
m += 50;
nombre += 1;
}
else if (v > 0.4 && v < 0.6) {
m += 30;
nombre += 1;
}
else if (v > 0.2 && v < 0.4) {
nombre += 3;
}
else {
m -= 10;
nombre += 1;
}
} while (m < 300000);
cout << _auto << ", cantidad de pasos: " << nombre << "\n";
}
int main(){
srand((unsigned int)time(NULL));
int mercedes = 0, ford = 0, ferrari = 0, lamborghini = 0, audi = 0, porsche = 0, lexus = 0, toyota = 0;
string auto1 ="Mercedes", auto2 ="Ford", auto3 ="Ferrari", auto4 ="Lamborghini", auto5 ="Audi", auto6 ="Porsche", auto7 ="Lexus", auto8 ="Toyota";
autos(mercedes,auto1);
autos(ford,auto2);
autos(ferrari,auto3);
autos(lamborghini,auto4);
autos(audi,auto5);
autos(porsche,auto6);
autos(lexus,auto7);
autos(toyota,auto8);
}
However, in the output I have to order the number of steps. So what would be a method to sort random values? should I save them in a vector?