Reputation: 111
So I wrote a code to simulate a gambling machine from a game. Basically, you press a button, and you have a chance to double your the credits you earn. On the other hand, if you this fails, you have to start over. An example run might be:
Start of run 1:
0
1
2
Start of run 2:
0
1
Start of run 3:
0
Start of run 4:
0
1
2
It works fine. I have the code do a certain amount of runs (determined by user input into 'n') and outputs the maximum combo that was reached in all of those runs. It also tells when the highest combo was surpassed.
The problem is that after a certain amount of runs, the highest combo cannot surpass 15 for whatever reason. Literally every time I input 10 million or more (, it gives 15. It just doesn't seem right given the fact that it doesn't match the probability at all.
Is there something wrong with the way I seeded it?
#include <iostream>
#include <stdlib.h>
//#include "stdafx.h"
#include<ctime>
using namespace std;
int main() {
int n = 1;
srand(time(0));
while (n > 0) {
cin >> n;
int highestCombo = 0;
for (int i = 0; i < n; i++) {
int combo = 0;
while (true) {
int r = (rand() % 2) + 1;
if (r == 1) {
combo++;
}
else if (r == 2) {
if (combo > highestCombo) {
highestCombo = combo;
cout << combo << " at #" << i << endl;
}
combo = 0;
break;
}
}
}
cout << "Highest Combo: " << highestCombo << endl;
}
}
EDIT: So it seems that it might just be my IDE. Weird. I'm using Dev-C++ since I just wanted to quickly write it. However, cpp.sh goes above 15 and into the 20s.
Upvotes: 0
Views: 103
Reputation: 337
The correct answer seams to come from tobi303. I tested his solution for you and using "< random >" instead works much better.
#include <iostream>
#include <stdlib.h>
//#include "stdafx.h"
#include<ctime>
using namespace std;
int main() {
int n = 1;
//srand(time(NULL));
std::mt19937 rng;
rng.seed(std::random_device()());
std::uniform_int_distribution<std::mt19937::result_type> rand(1,2);
while (n > 0) {
cin >> n;
int highestCombo = 0;
for (int i = 0; i < n; i++) {
int combo = 0;
while (true) {
//int r = (rand() % 2);
int r = rand(rng);
if (r == 1) {
combo++;
}
else if (r == 2) {
if (combo > highestCombo) {
highestCombo = combo;
cout << combo << " at #" << i << endl;
}
combo = 0;
break;
}
}
if(i == n - 1)
{
cout << " i " << i << endl;
}
}
cout << "Highest Combo: " << highestCombo << endl;
}
}
Upvotes: 1