Skip to content

Instantly share code, notes, and snippets.

@oshea00
Created January 12, 2017 21:35
Show Gist options
  • Save oshea00/6e396465fbb9f213810dbba4ed4dafcc to your computer and use it in GitHub Desktop.
Save oshea00/6e396465fbb9f213810dbba4ed4dafcc to your computer and use it in GitHub Desktop.
// flipfunc.c : Flips a coin
#include "time.h"
#include "stdio.h"
#include "stdlib.h"
double f(int, int *i, int *hist);
// Input: flips - how many times to flip the coin.
// Output:
// *headsInARow - updates with a count of the longest run of heads in a row.
// hist[] - updates a list of counts in a row history.
// Returns: odds of heads (should be near 50%)
double f(int flips, int *headsInARow, int hist[])
{
int heads = 0;
int currentRun = 0;
for (int i = 0; i < flips; i++)
{
int flip = rand() % 2;
if (flip == 1)
{
heads++;
currentRun += 1;
}
else
{
if (currentRun > 2)
{
hist[currentRun]++;
*headsInARow = (*headsInARow < currentRun) ? currentRun : *headsInARow;
}
currentRun = 0;
}
}
if (currentRun)
{
*headsInARow = (*headsInARow < currentRun) ? currentRun : *headsInARow;
hist[currentRun]++;
}
return heads / (double) flips;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment