Home > Articles, Data Structures & Algorithms > Implementation of algorithm for the simulation of the ‘twisting’ of a coin.

Implementation of algorithm for the simulation of the ‘twisting’ of a coin.

The program generally simulates a Bernoulli trials sequence, a familiar and abstract notion of probability theory. So, if you flip a coin N times, we expect “head” to occur N/2 times – but it could occur anything between 0 and N times. The program performs the experiment M times, reading the N and M from the command line. It uses an array ‘f’ to count the frequency with which the result “i heads” appears for 0 <= i <= N, and then displays a histogram of the results of experiments with an asterisk for every 10 appearances. Also, the operation behind the program – of indexing an array with a calculated value – is critical to the effectiveness of many computational procedures.

You should know that the implementation of the algorithm does not take into account issues of data input validation or proper management of dynamic memory (e.g. avoiding memory leaks) because it is only necessary to highlight the logic of the algorithm.

#include <iomanip>
#include <iostream>
#include <cstdlib>
using namespace std;

int
heads () {
  return rand () < RAND_MAX / 2;
}

int
main (int argc, char *argv[]) {
  int i, j, cnt, N, M;

  if (!argv[1] || !argv[2])
    return EXIT_FAILURE;

  N = atoi (argv[1]);
  M = atoi (argv[2]);

  srand (time (NULL));

  int * f = new int[N+1];

  for (j = 0; j <= N; j++) f[j] = 0;

  for (i = 0; i < M; i++, f[cnt]++)
    for (cnt = 0, j = 0; j <= N; j++)
      if (heads ())
        cnt++;

  for (j = 0; j <= N; j++) {
    if (f[j] == 0)
      cout << ".";

    for (i = 0; i < f[j]; i += 10)
      cout << "*";

    cout << endl;
  }

  return EXIT_SUCCESS;
}
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: