Created
March 27, 2017 06:11
-
-
Save DavZim/119a158c8052c2ce3b28bf620a15db02 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
// samples the height of one structure for a given maximum height (H) | |
int sample_height(int maxHeight) { | |
int height = 0; | |
while (rand() % 2 == 1 & height < maxHeight) { | |
height++; | |
} | |
return height; | |
} | |
// returns a boolean if the round matches the criteria (equal or smaller set of structures) | |
// for a numer of structure N and a maximum height (H) | |
bool simulate_round (int N, int H){ | |
int lastStrucHeight = H; | |
int strucHeight; | |
for (int i = 0; i < N; ++i) { | |
strucHeight = sample_height(H); | |
// compare the height of the current structure to the former | |
// if larger, we can abort the inner for loop (the creation of the structures for this round) | |
if (strucHeight > lastStrucHeight) { | |
return false; | |
} | |
lastStrucHeight = strucHeight; | |
} | |
return true; | |
} | |
// takes the number of simulation rounds, the number of structures per round, the maximum height | |
// and returns the chance of matching the criteria | |
double simulate(int nRounds, int N, int H) { | |
int countSmallerEqual = 0; // initiate the count of matching | |
int countLarger = 0; | |
bool allSmallerEqual; | |
// simulate nRounds rounds | |
for (int round = 0; round < nRounds; ++round){ | |
// get N structures | |
allSmallerEqual = simulate_round(N, H); | |
// add the result to our overall counters | |
if (allSmallerEqual) { | |
countSmallerEqual++; | |
} else { | |
countLarger++; | |
} | |
} | |
// calculate the chance of matching the criteria | |
double chance = (double) countSmallerEqual / nRounds; | |
return chance; | |
} | |
// main function of the simulation | |
int main () { | |
int nRounds = 1000000; // rounds of simulation (N = 3, H = 3, nRounds = 100mil takes roughly 8 seconds) | |
int N = 2; // number of structures | |
int H = 3; // max Height, beware, we start at 0 (see the declaration in sample_height()) | |
// Single run | |
// double chance = simulate(nRounds, N, H); // simulate the chance with nRounds rounds, N structures, and H as the max height | |
// printf("N = %3d & H = %2d | chance = %.6f\n", N, H, simulate(nRounds, N, H)); | |
// printf("-----------------------------------\n"); | |
// multiple runs of N = 2 to 20 | |
printf("Running %d simulations each:\n", nRounds); | |
printf("-----------------------------------\n"); | |
for (int Nmult = 2; Nmult < 20; Nmult++) { | |
printf("N = %3d & H = %2d | chance = %.6f\n", Nmult, H, simulate(nRounds, Nmult, H)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment