I don't have a lot to say, but this is my little bit.

Friday, October 9, 2009

Coins In A Few Lines Of C++

Here is a coin-flipping program in a reduced size. I tried to take advantage of nuanced C syntax to reduce the number of lines it took to produce a line of text showing the total number of coin flips, the number of heads, the number of tails, the difference between those numbers (the gap), and the biggest gap seen so far.

#include <iostream>
#include <time.h>
using namespace std;
int main() {
std::srand( time(NULL) );
int h = 0, t = 0, g = 0, gap = 0;
while( 0 == std::rand() % 2 ? ++h : ++t ) {
if( std::abs(gap = h - t) > abs(g) ) g = gap;
cout << "Total: " << h+t << "\tHeads: " << h << "\tTails: " << t << "\tGap: " << gap << "\tBiggest Gap: " << g << endl;
}
}

No comments:

Post a Comment