Skip to content

Instantly share code, notes, and snippets.

@kevingrant
Created July 21, 2012 15:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevingrant/3156157 to your computer and use it in GitHub Desktop.
Save kevingrant/3156157 to your computer and use it in GitHub Desktop.
The Two Egg Problem
#include <stdio.h>
#include <algorithm>
#include <vector>
struct State
{
int answer;
int where;
bool calculated;
State() : answer(0), where(0), calculated( false ) {}
};
int eggs( std::vector< State >& t, int total )
{
if ( t[total].calculated )
{
return t[total].answer;
}
int best = total + 1;
int where = 1;
for ( int i = 1; i <= total; i++ )
{
int current = 1 + std::max( i - 1, eggs( t, total - i ) );
if ( current < best )
{
best = current;
where = i;
}
}
t[total].answer = best;
t[total].where = where;
t[total].calculated = true;
return best;
}
int main()
{
int total = 100;
std::vector< State > t( total + 1 );
int ans = eggs( t, total );
printf( "%d\n", ans );
int floors = total;
int w = 0;
while ( floors > 0 )
{
w += t[ floors ].where;
printf("%d ", w );
floors = floors - t[ floors ].where;
}
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment