Guess the Number

This is a very common game. The player has to guess a randomly generated number.

Source

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

int main() {
	int curr=0, real, tries=0;
	time_t seed;
	time(&seed);
	srand((unsigned int)seed/getpid());
	real = (rand()%1000)+1;
	
	puts("It's between 1 and 1000...");
	
	while (1) {
		fputs("Your Guess:  ",stdout);
		scanf("%d",&curr);
		
		if (curr != real) {
			tries++;
			if (curr > real) puts(">> Smaller!\n");
			if (curr < real) puts(">> Bigger!\n");
		}
		else {
			puts(">> You're right!");
			printf(">> The number is %d,
				you had %d wrong guesses.\n",real,tries);
			break;
		}
	}
	
	return EXIT_SUCCESS;
}
	

Compile with tcc guess.c -o guess and run with ./guess.

Theory

Play the game a few times. Maybe you use a smart and fast method to guess the number:

  1. 500: Bigger
  2. 750: Bigger
  3. 875: Bigger
  4. 937: Bigger
  5. 968: Smaller
  6. 960: Smaller
  7. 950: Smaller
  8. 940: Bigger
  9. 945: Bigger
  10. 947: Bigger
  11. 948: Bingo!

It is very probable that you always have 9..10 wrong guesses. Rather 10. Let's do some mathematics!

We want to calculate the likeliest number of wrong guesses, assuming we use the smart, "direct", way.

1000/2x = 1

The real solution is

x = 3*(log(5)+log(2))/log(2)

… which equates to …

x ≈ 9.965784284662087…

Well, that sounds pretty good. Our expectation was right.