I am trying to evaluate a statistics problem via a Monte Carlo method. In this problem I am generating a random number and comparing it to a fixed probability number stored in a vector array titled comms_reliability. Assuming there is only one variable in the vector array, I am comparing the random number and the probability and tallying the results if the random number is greater than the reliability number. However, the vector array could also have two values, in which case I am producing two random numbers and comparing them to the two reliability numbers and. If both random numbers are bigger than the reliability numbers, I am tallying the scenarios. Theoretically this could continue on and on for as many values in the vector array as I want. However, through a failure of imagination I only know how to code this where the for statement is contained in multiple if statements
for each possible scenario. In this implementation I have to copy the same lines of code multiple times, and it also limits the commms_reliability array sizes that can be evaluated based on how many times I have copied these lines of code to handle the next array point. How can I do this where I only need one if statement. An example of how I have it coded currently is shown below.
int main(int argc, const char * argv[]) {
int sample_size = 1000000;
std::vector<float> comms_reliability = {0.6,0.6};
float tally = 0.0;
// rang() = random number generator
// if statement for comms_reliability array of size 1
if (comms_reliability.size() == 1) {
for (int i = 0; i < sample_size; i++){
if (rang() > comms_reliability[0]) tally = tally + 1.0;
}
}
// if statement 2 for comms_reliability array of size 2
if (comms_reliability.size() == 2) {
for (int i = 0; i < sample_size; i++){
if (rang() > comms_reliability[0] && rang() > comms_reliability[1]) tally = tally + 1.0;
}
}
// if statement 3 for comms_reliability array of size 3
if (comms_reliability.size() == 3) {
for (int i = 0; i < sample_size; i++){
if (rang() > comms_reliability[0] && rang() > comms_reliability[1] &&
rang() > comms_reliability[2]) tally = tally + 1.0;
}
}