Home c++ Monte Carlo method

Monte Carlo method

Author

Date

Category

It is necessary to calculate the probability of coincidence of 2 numbers (similar to the birthday paradox) using the Monte Carlo method. I seem to be doing it right, but the correct probability does not work, what needs to be corrected?

int main () {
  int amount;
  int count = 0;
  float experiment;
  cin & gt; & gt; people;
  cin & gt; & gt; experiment;
  int match [people + 1];
  for (int k = 1; k & lt; (people + 1); k ++) {
    match [k] = rand ()% 365 + 1;
  }
  for (int i = 0; i & lt; (people + 1); i ++) {
    for (int j = 0; j & lt; (people + 1); j ++) {
      if (match [i] == match [j]) {
        count ++;
      }
    }
  }
  cout & lt; & lt; "Result:" & lt; & lt; count / experiment;
  return 0;
}

Answer 1, authority 100%

Checked on Dev – it works

# include & lt; iostream & gt;
#include & lt; stdlib.h & gt;
int main () {
  int people, i, j;
  int count = 0;
  float experiment;
  std :: cin & gt; & gt; people;
  std :: cin & gt; & gt; experiment;
  int birthday [people];
  count = 0;
  for (int n = 0; n & lt; experiment; n ++) {
    // Form a random group
    for (int k = 0; k & lt; people; k ++) {
      birthday [k] = rand ()% 365 + 1;
      // std :: cout & lt; & lt; birthday [k] & lt; & lt; "\ n";
    }
    // Look for a match DR
    for (i = 0; i & lt; people; i ++)
      for (j = i + 1; j & lt; people; j ++)
        if (birthday [i] == birthday [j]) {
          count ++;
          i = people; // Stop Loop
          j = people; // match checks
        }
  }
  std :: cout & lt; & lt; "Result:" & lt; & lt; count / experiment;
  return 0;
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions