Hello,
I was wondering if it is possible to implement chance in C++. Can you create something that says, 1, 2, 3, and 4: they each have a 25% chance of being picked, and will be completely random each time. I looked a little at rand() and srand() but this is only going to be a few numbers at a time, and I want them to have an equal chance of being picked, Thanks,
int choices = 4;
int pickedChoice = (int)(rand() * choices)
rand() returns a long decimal that can be multiplied by how many outcomes you want. It will be a number between 0 and 4 in the above, and the (int) conversion chops off the rest and rounds it up or down.
not quite correct. almost
What youw ant to do, is modulo the rand() by 4. this will give you a number between 0 and 3. then add 1 to it and have a number between 1 and 4.
That's good, but I'm lookingfor something that will basically pick a number between 1 and 4 with a 25% chance each time of picking each, how would you do that?
I was running the program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int main()
{
int move=1000;
srand(time());
move = (rand() % 4);
cout << "My move is " << move << '\n';
return 0;
}
a bunch of times in a row and it went: 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0.
but if I waited awhile it worked, this will be fine for my program.
Would you mind explaning how srand() works and what kind of argumnts it can take? It looks like it'd be useful for probability but I don't exactly know how to use it except with NULL and using it before rand().
srand() seeds your random number generator. The number you put in decides on the sequence of "random" numbers that are drawn. If you use the same seed then the same sequence of numbers will be drawn each time.
If you execute it multiple times at a high speed then you will likely end up with the same seed and thus, the same numbers. But in theory, each time you make a rand() call you have 25% chance that it'll be 1-4