Download and view my resume (PDF)

Friday, October 16, 2009

Coins In Fewer Lines Of C++

I revisited my coins program and reduced it from 11 to 7 lines of code. I didn't realize before that you could have multiple import statements one one line, but apparently you can. And I realized that a for loop would of course provide a syntax for combining a few lines into one. If I were a glutton for horizontal scrolling, I could combine the cout line with the for loop line. I could also remove the srand line, if I didn't care about seeding the random number generator; but besides that I think that's about as minimal as it could possibly get.

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

No comments:

Post a Comment