generate random numbers in c ++ for small intervals - c++

I'm working on a program to calculate the odds of a poker game, it's in process. I found how to generate random numbers but these random numbers depend on time and are not appropriate for generating random numbers in a small interval. I would like to know how I can generate random numbers without having to depend on computer time.
#include <cstdlib>
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
using namespace std;
int main() {
srand(time(NULL));
int N = 1000, T=100;
int j;
float tcouple = 0, ttrio = 0, tfull = 0, tpoker = 0, trien = 0;
struct Lettre{ int numero; char baton;};
Lettre lettre[5];
for(int a = 0; a < T; a++)
{
int couple = 0, trio = 0, full = 0, poker = 0;
for(int i = 0; i< N; i++){
int d = 0 ;
for(j = 0; j < 5; j++)
{
int r = 0;
lettre[j].numero = (1 + rand() % 13);
r = (1 + rand() % 4);
switch(r)
{
case 1:
lettre[j].baton = 'T';
break;
case 2:
lettre[j].baton = 'P';
break;
case 3:
lettre[j].baton = 'C';
break;
case 4:
lettre[j].baton = 'D';
break;
}
}
for(int l = 0; l < 4; l++)
{
for(int k = l + 1; k<5; k++)
{
if(lettre[l].numero == lettre[k].numero)
d = d + 1;
}
}
if (d == 1)
couple = couple + 1;
if (d == 3)
trio = trio + 1;
if(d == 4)
full = full + 1;
if(d==6)
poker = poker + 1;
}
tcouple = tcouple + couple;
ttrio = ttrio + trio;
tfull = tfull + full;
tpoker = tpoker + poker;
}
trien=(T*N)-(tcouple+ttrio+tfull+tpoker);
cout << "probabilite couple: " << tcouple/(T*N) <<endl;
cout << "probabilite trio: " << ttrio/(T*N) <<endl;
cout << "probabilite full: " << tfull/(T*N) <<endl;
cout << "probabilite poker: " << tpoker/(T*N) <<endl;
cout << "probabilite rien: " << trien/(T*N) << endl;
return 0;
}

You may want to keep a random numbers pool, which is filled at start or once a time period. It should be big enough so every time you get new random value from it it was a new one. In this case you may use uniform_int_distribution as Timo suggested or even rand.
struct RandPool
{
void Generate()
{
srand(time(nullptr));
for (int i = 0; i < 1000'000; ++i)
mNumbers.push_back(rand());
mIndex = 0;
}
int Next()
{
return mNumbers[mIndex++];
}
private:
int mIndex = 0;
std::vector<int> mNumbers;
};

Related

Strange behaviour of pointers in C++

#include <cstdlib>
#include <iostream>
#include <Math.h>
#include <algorithm>
#include <string>
#include <iterator>
#include <iostream>
#include <vector> // std::vector
using namespace std;
int stepCount, i, x, y, z, j, k, array1Size, array2Size, tester, checker;
int numstring[10] = { 0,1,2,3,4,5,6,7,8,9 };
int numstringTest[10] = { 0,1,2,3,4,5,6,7,7,9 };
int* numbers;
int* differentNumbers;
int* p;
int* otherNumbers;
void stepCounter(int a) {
// determines the step number of the number
if (a / 10 == 0)
stepCount = 1;
else if (a / 100 == 0)
stepCount = 2;
else if (a / 1000 == 0)
stepCount = 3;
else if (a / 10000 == 0)
stepCount = 4;
else if (a / 100000 == 0)
stepCount = 5;
else if (a / 1000000 == 0)
stepCount = 6;
else if (a / 10000000 == 0)
stepCount = 7;
else if (a / 100000000 == 0)
stepCount = 8;
else if (a / 1000000000 == 0)
stepCount = 9;
}
void stepIndicator(int b) {
// indicates each step of the number and pass them into array 'number'
stepCounter(b);
numbers = new int[stepCount];
for (i = stepCount; i>0; i--) {
//
/*
x = (round(pow(10,stepCount+1-i)));
y = (round(pow(10,stepCount-i)));
z = (round(pow(10,stepCount-i)));
*/
x = (int)(pow(10, stepCount + 1 - i) + 0.5);
y = (int)(pow(10, stepCount - i) + 0.5);
numbers[i - 1] = (b%x - b%y) / y;
}
}
int sameNumberCheck(int *array, int arraySize) {
//checks if the array has two or more of same integer inside return 1 if same numbers exist, 0 if not
for (i = 0; i<arraySize - 1; i++) {
//
for (j = i + 1; j<arraySize; j++) {
//
if (array[i] == array[j]) {
//
return 1;
}
}
}
return 0;
}
void getDifferentNumbers(int* array, int arraySize) {
//
k = 0;
j = 0;
checker = 0;
otherNumbers = new int[10 - arraySize]; //exact number of other numbers is 10 - numbers we have
for (i = 0; i<10; i++) {
if ((i>0)&(checker = 0)) {
k++;
otherNumbers[k - 1] = i - 1;
}
//
checker = 0;
for (j = 0; j<arraySize; j++) {
//
p = array + j;
cout << *p << endl; //ilkinde doğru sonra yanlış yapıyor?!
if (*p = i) {
checker++;
}
}
}
}
int main(int argc, char *argv[])
{
stepCounter(999999);
cout << stepCount << endl;
stepIndicator(826424563);
for (j = 0; j<9; j++) {
//
cout << numbers[j] << endl;
}
cout << sameNumberCheck(numstringTest, 10) << " must be 1" << endl;
cout << sameNumberCheck(numstring, 10) << " must be 0" << endl;
cout << endl;
getDifferentNumbers(numstringTest, 10);
cout << endl;
cout << endl << otherNumbers[0] << " is the diff number" << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
Hi, my problem is with pointers actually. You will see above, function getDifferentNumbers. It simply does a comparement if in any given array there are repeated numbers(0-9). To do that, I passed a pointer to the function. I simply do the comparement via pointer. However, there is a strange thing here. When I execute, first time it does correct, but secon time it goes completely mad! This is the function:
void getDifferentNumbers(int* array, int arraySize) {
//
k = 0;
j = 0;
checker = 0;
otherNumbers = new int[10 - arraySize]; //exact number of other numbers is 10 - numbers we have
for (i = 0; i<10; i++) {
if ((i>0)&(checker = 0)) {
k++;
otherNumbers[k - 1] = i - 1;
}
//
checker = 0;
for (j = 0; j<arraySize; j++) {
//
p = array + j;
cout << *p << endl; //ilkinde doğru sonra yanlış yapıyor?!
if (*p = i) {
checker++;
}
}
}
}
and this is the array I passed into the function:
int numstringTest[10] = {0,1,2,3,4,5,6,7,7,9};
it should give the number 7 in otherNumbers[0], however it does not. And I do not know why. I really can not see any wrong statement or operation here. When I execute, it first outputs the correct values of
numstringTest: 1,2,3,4,5,6,7,7,9
but on next 9 iteration of for loop it outputs:
000000000011111111112222222222333333333344444444445555555555666666666677777777778888888888
You have some basic problems in your code.
There are multiple comparisons that are not really comparisons, they're assignments. See the following:
if((i>0) & (checker=0)){
and
if(*p = i){
In both cases you're assigning values to the variables, not comparing them. An equality comparison should use ==, not a single =. Example:
if (checker == 0) {
Besides that, you're using & (bitwise AND) instead of && (logical AND), which are completely different things. You most likely want && in your if statement.
I've just noticed this:
getDifferentNumbers(numstringTest, 10);
and in that function:
otherNumbers = new int[10 - arraySize];
which doesn't seem right.

Undesired output of series of numbers and letters for Dice Roll (Text based rpg) C++

I'm trying to make a small text rpg based on a dice roll system. However I keep getting a weird output of letter and numbers instead of the intended integer when I call the rollDice function.
PlayerCreation.cpp
#include "header.h"
#include "Player.h"
void ChooseBuild();
void GenerateStats();
Player player;
int stats[5];
void PlayerCreation() {
cout << "What is my name?" << endl;
cin >> sOpt;
player.setName(sOpt);
cout << "Ah, yes my name is " << player.getName() << "! I don't remember this body though it's so..." << endl;
ChooseBuild();
GenerateStats();
for (int i = 1; i <= 5; i++)
cout << stats << endl;
}
void ChooseBuild() {
//There is stuff here.
}
void GenerateStats() {
for (int i = 1; i <= 5; i++)
stats[i] = rollDice(12, 2) / 2;
}
rollDice.cpp
#include "header.h"
//Creates a random number which is then used to roll different dice.
default_random_engine random;
uniform_int_distribution<int> d4(1, 4);
uniform_int_distribution<int> d6(1, 6);
uniform_int_distribution<int> d8(1, 8);
uniform_int_distribution<int> d10(1, 10);
uniform_int_distribution<int> d12(1, 12);
uniform_int_distribution<int> d100(1, 100);
auto D4 = bind(d4, random);
auto D6 = bind(d6, random);
auto D8 = bind(d8, random);
auto D10 = bind(d10, random);
auto D12 = bind(d12, random);
auto D100 = bind(d100, random);
int rollDice(int die, int num) {
int diceTotal = 0;
if (die == 4) {
for (int i = 1; i <= num; i++) {
diceTotal += D4();
}
}
if (die == 6) {
for (int i = 1; i <= num; i++) {
diceTotal += D6();
}
}
if (die == 8) {
for (int i = 1; i <= num; i++) {
diceTotal += D8();
}
}
if (die == 10) {
for (int i = 1; i <= num; i++) {
diceTotal += D10();
}
}
if (die == 12) {
for (int i = 1; i <= num; i++) {
diceTotal += D12();
}
}
if (die == 100) {
for (int i = 1; i <= num; i++) {
diceTotal += D100();
}
}
return diceTotal;
}
It displays something like this:
000E63B0
000E63B0
000E63B0
000E63B0
000E63B0
Stats is an array. So cout << stats prints address of the first element. You need a separate loop to iterate over stats elements and print each of them.
Edit: actually you have a loop already, just add index: cout << stats[i-1] << endl;
Edit2: also you have some errors w.r.t. array indexing: array int stats[5]; has elements stats[0], stats[1], stats[2], stats[3] and stats[4]; so to iterate other them use loop which starts at 0 and is strictly less than 5:
for (int i = 0; i < 5; i++)
cout << stats[i] << endl;

C++ generating a pascal triangle, wrong output

I have a problem with generating a pascal triangle in c++, same algorithm works good in java and in c++ it only works for the first two numbers of every line of the triangle in any other it generates way to big numbers. For example in java it generates:
1 5 10 10 5 1 and in C++: 1 5 1233124 1241241585 32523523500 etc
Here is code:
#include <cstdlib>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class Pascal {
private:
int* tab;
int prev1;
int prev2;
public:
Pascal(int n) {
tab = new int[n+1];
prev1=0;
prev2=0;
for(int i = 0; i <= n; i++) {
for(int k = 0; k <= i; k++) {
if (k == 0) {
tab[k] = 1;
prev2 = 1;
} else {
prev1 = tab[k-1] + tab[k];
tab[k-1] = prev2;
prev2 = prev1;
}
}
}
}
int wspolczynnik(int m) {
return tab[m];
}
};
int main (int argc, char* argv[]) {
int n = 0, m = 0;
n = atoi(argv[1]); // konwersja string na int
if (n >= 0)
for (int i = 2; i < argc; i++) {
Pascal *wiersz = new Pascal(n);
m = atoi(argv[i]);
int result = wiersz->wspolczynnik(m);
if (m < 0 || m > n)
cout << m << " - element poza zakresem" << endl;
else
cout << m << " : " << result << endl;
delete[] wiersz;
}
return 0;
}
See if initializing the tab array helps:
tab = new int[n+1]();

My variables black1 and black2 giving me the wrong answers in c++?

My professor is forcing me to use a program called RAPTOR, which preety much creates and executes flow charts and psuedocode. And I'm stuck converting my flowchart, insted of writing in the actual language. I finally got my program to compile, but now it wont give me the same results as in the RAPTOR program, and my black1 variable keeps returning 0, where as black2 keeps spitting out a number like 1,000. Anyways any help would be greatly appreciated thank you!
Here's the code:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main()
{
int trials;
int first;
string bag;
int j;
float percent;
string temp;
int black2;
int runs;
int l;
int black1;
int firstdraw;
int c;
string possible;
int seconddraw;
srand(time(NULL));
l = bag.length();
int r = rand() % 4;
possible ="bw";
runs =0;
while (!(runs>9))
{
black1 =0;
black2 =0;
runs =runs+1;
trials =0;
while (!(trials==1000))
{
trials =trials+1;
bag ="bbwww";
l = bag.length();
c =1;
temp =" ";
while (!(c==5))
{
j = r ;
temp[1] = bag[c];
bag[c] = bag[j];
bag[j] = temp[1];
c =c+1;
}
c =1;
j = r;
firstdraw =bag[j];
if (firstdraw==possible[1])
{
black1 = black1+1;
first = 1;
}
else
{
first = 0;
}
while (!(j>l-1))
{
bag[j] = bag[j + 1];
j =j+1;
}
l =l-1;
j = r;
seconddraw = bag[j];
if (seconddraw==possible[1] && first==1)
{
black2 =black2+1;
}
else
{
}
}
percent = 100.0 * black2/black1;
cout << black2 << " " << black1 << endl;
cout << "Percentage for run #" << runs << " and " << trials << " trials: %" << percent << endl; }
return 0;
}
I'm sorry but I won't fix your whole code, I made it more readable, removed that ugly using namespace std; and left some comments for you. Check this out, fix your code, and take a look into some tutorials if needed. I've gotten a debug assertion over and over again with this code. Guessing you never runned any debugger and just had Release mode on.
Also don't forget to initialize the variables. You risk undefined behaviour.
These two strings walk into a bar and sit down. The bartender says, "So what'll it be?"
The first string says, "I think I'll have a beer quag fulk boorg jdk^CjfdLk jk3s d#f67howe%^U r89nvy~~owmc63^Dz x.xvcu"
"Please excuse my friend," the second string says, "He isn't null-terminated."
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <time.h>
#include <stdlib.h>
int main()
{
int trials = 0;
int first = 0;
int c = 0;
int j = 0;
int l = 0;
int black2 = 0;
int runs = 0;
int black1 = 0;
int firstdraw = 0;
int seconddraw = 0;
float percent = 0.0f;
std::string temp = "\0";
std::string bag = "\0";
std::string possible = "\0";
srand (time(NULL));
l = bag.length();
fflush(stdin); // You may want to do this to get random numbers from rand() otherwise it may use the same number over and over again
int r = 0;
r = rand() % 4;
possible = "bw";
runs = 0;
while (!(runs > 9))
{
black1 = 0;
black2 = 0;
runs = runs + 1; //Why no for loop ?
trials = 0;
while (!(trials == 1000))
{
trials = trials + 1; //Why no for loop ?
bag ="bbwww";
l = bag.length();
c = 1;
temp =" ";
while (!(c == 5))
{
j = r;
temp[1] = bag[c]; // temp[1] <- debug assertion, can't work
bag[c] = bag[j];
bag[j] = temp[1]; // temp[1] <- debug assertion, can't work either
c = c + 1;
}
c = 1;
j = r;
firstdraw = bag[j];
if (firstdraw == possible[1])
{
black1 = black1 + 1;
first = 1;
}
else
{
first = 0;
}
while (!(j > l - 1))
{
bag[j] = bag[j + 1]; //Will most likely cause a debug assertion too...
j = j + 1;
}
l = l - 1;
j = r;
seconddraw = bag[j];
if (seconddraw == possible[1] && first==1)
{
black2 = black2 + 1;
}
else
{
//Not needed !?!
}
}
percent = 100.0 * black2 / black1;
std::cout << black2 << " " << black1 << std::endl;
std::cout << "Percentage for run #" << runs << " and " << trials << " trials: %" << percent << std::endl;
}
return 0;
}

Problem with fibonacci function. C++

Should return the n place of the array. But instead of the value I'm only getting 0.
int fibonacci(int n)
{
int f[100];
f[0] = 0;
f[1] = 1;
for (int i=2; i<n; i++)
{
f[i] = f[i-2] + f[i-1];
}
return f[n];
}
int main()
{
cout << fibonacci(3);
return 0;
}
New CODE:
New problem its returning one number further then it should. For example if 'n==7' its returning '13' not '8' like it should.
int fibonacci(int n)
{
int f[100] = { 0, 1 };
for (int i=2; i<=n; i++)
{
f[i] = f[i-2] + f[i-1];
}
return f[n-1];
}
int main()
{
cout << fibonacci(7);
return 0;
}
well, you never set f[n], you only go up to i < n, that is, i == n-1.
try returning f[n-1]
EDIT: as Chris Lutz pointed out my answer is no good as it would give an invalid result if you called fibonacci(0)
Like many have answered already, the best solution is to loop until i <= n
Unless, of course, you want fibonacci(3) to return the 3rd element in the fibonacci sequence and not the 4th, in which case fibonacci(0) wouldn't really make sense, and the right return value would be f[n-1]... still the n==0 case should be handled somehow, as should the n<0and the n>100 cases.
you can return f[n-1] as long as you check for the right boundaries:
int fibonacci(int n)
{
int f[100] = { 0, 1 };
if ((n <= 0) || (n > 100))
return -1;//return some invalid number to tell the caller that he used bad input
for (int i=2; i < n; i++) // you can use i < n here
{
f[i] = f[i-2] + f[i-1];
}
return f[n-1];
}
Your loop termination condition is wrong. Since this is homework perhaps you can work out why.
You forgot to initialize the n-th value of the array. You return f[n] but only initialize up to n-1.
n is the index that is never reached in your version. You just need to replace the < with <= in your for loop conditional. (You never assigned f[n] because n was never reached by the loop and so you got back a default value.)
int fibonacci(int n)
{
int f[100];
f[0] = 0;
f[1] = 1;
for (int i=2; i<=n; i++)
{
f[i] = f[i-2] + f[i-1];
}
return f[n];
}
int main()
{
cout << fibonacci(3);
return 0;
}
And you don't need an array to perform the fib sequence by the way. Just use two variables and reassign them in the loop. Something like this:
int a = 0;
int b = 1;
for (int i=2; i<=n; i++)
{
b = a + b;
a = b;
}
return b;
The trouble is that you test for i < n (where n == 3 in your example call), but you return f[3] which has not been set to anything. You are 'lucky' that you're getting zeroes rather than random garbage.
Change the '<' to '<='.
Working Code #1
Retaining the full size array.
#include <iostream>
using namespace std;
static int fibonacci(int n)
{
int f[100] = { 0, 1 };
if (n < 0 || n > 100)
return -1;
else if (n < 2)
return f[n];
for (int i = 2; i <= n; i++)
{
f[i] = f[i-2] + f[i-1];
//cout << "f[" << i << "] = " << f[i] << endl;
}
return f[n];
}
int main()
{
for (int i = 0; i < 8; i++)
cout << "fib(" << i << ") = " << fibonacci(i) << endl;
return 0;
}
Sample Output #1
fib(0) = 0
fib(1) = 1
fib(2) = 1
fib(3) = 2
fib(4) = 3
fib(5) = 5
fib(6) = 8
fib(7) = 13
Working Code #2
This uses an array of size 3, at the cost of a lot of modulo operations:
#include <iostream>
using namespace std;
static int fibonacci(int n)
{
int f[3] = { 0, 1, 0 };
if (n < 0 || n > 100)
return -1;
else if (n < 2)
return f[n];
for (int i = 2; i <= n; i++)
{
f[i%3] = f[(i-2)%3] + f[(i-1)%3];
//cout << "f[" << i << "] = " << f[i%3] << endl;
}
return f[n%3];
}
int main()
{
for (int i = 0; i < 8; i++)
cout << "fib(" << i << ") = " << fibonacci(i) << endl;
return 0;
}
It produces the same output - so there is no point in repeating it.
Working Code #3
Avoiding arrays and modulo operations:
#include <iostream>
using namespace std;
static int fibonacci(int n)
{
int f0 = 0;
int f1 = 1;
if (n < 0 || n > 46)
return -1;
else if (n == 0)
return f0;
else if (n == 1)
return f1;
int fn;
for (int i = 2; i <= n; i++)
{
int fn = f0 + f1;
f0 = f1;
f1 = fn;
//cout << "f[" << i << "] = " << fn << endl;
}
return f1;
}
int main()
{
for (int i = -2; i < 50; i++)
cout << "fib(" << i << ") = " << fibonacci(i) << endl;
return 0;
}
The limit 46 is empirically determined as correct for 32-bit signed integers.
Example Output #3
fib(-2) = -1
fib(-1) = -1
fib(0) = 0
fib(1) = 1
fib(2) = 1
fib(3) = 2
fib(4) = 3
fib(5) = 5
fib(6) = 8
fib(7) = 13
fib(8) = 21
fib(9) = 34
fib(10) = 55
fib(11) = 89
fib(12) = 144
fib(13) = 233
fib(14) = 377
fib(15) = 610
fib(16) = 987
fib(17) = 1597
fib(18) = 2584
fib(19) = 4181
fib(20) = 6765
fib(21) = 10946
fib(22) = 17711
fib(23) = 28657
fib(24) = 46368
fib(25) = 75025
fib(26) = 121393
fib(27) = 196418
fib(28) = 317811
fib(29) = 514229
fib(30) = 832040
fib(31) = 1346269
fib(32) = 2178309
fib(33) = 3524578
fib(34) = 5702887
fib(35) = 9227465
fib(36) = 14930352
fib(37) = 24157817
fib(38) = 39088169
fib(39) = 63245986
fib(40) = 102334155
fib(41) = 165580141
fib(42) = 267914296
fib(43) = 433494437
fib(44) = 701408733
fib(45) = 1134903170
fib(46) = 1836311903
fib(47) = -1
fib(48) = -1
fib(49) = -1
With the call fibonacci(3), your for loop (inside the fibonacci function) goes until i < 3...
It means that the last assigment is f[2]. Not f[3] as expected (which is the value you return).
Don't you mean
return f[n-1];
I guess your compiler has set the array f[100] to 0?
Looks like the other guy has the right answer....