package games;

import math.Maths;
import stdlib.StdIn;
import stdlib.StdOut;

/**
 *  I'm thinking of a number between 1 and 1,000,000<br />
 *  What's your guess? 500000 <br />
 *  Too high <br />
 *  What's your guess? 250000<br /> 
 *  Too low <br />
 *  What's your guess? 375000<br /> 
 *  Too high <br />
 *  What's your guess? 312500<br /> 
 *  Too high <br />
 *  What's your guess? 300500<br /> 
 *  Too low <br />
 *  ... <br />
 */
public class TwentyQuestions {

    public static void million() {
        // Generate a number and answer questions
        // while the user tries to guess the value.
        int N = 1 + (int) Maths.random(1000000);
        StdOut.print("I'm thinking of a number ");
        StdOut.println("between 1 and 1,000,000");
        int m = 0; 
        while (m != N) {
            // Solicit one guess and provide one answer
            StdOut.print("What's your guess? ");
            m = StdIn.readInt();
            if (m == N) StdOut.println("You win!");
            if (m < N)  StdOut.println("Too low ");
            if (m > N)  StdOut.println("Too high");
        }
    }
	
    // invariant: answer is in [lo, hi)
    public static int search(int lo, int hi) {
        if ((hi - lo) == 1) return lo;
        int mid = lo + (hi - lo) / 2;
        StdOut.printf("Is it less than %d?  ", mid);
        if (StdIn.readBoolean()) return search(lo, mid);
        else                     return search(mid, hi);
    }

    /**
     * This code uses binary search to play the game of twenty questions.
     * It takes a command-line argument n, asks you to think of a number
     * between 0 and N-1, where N = 2^n, and always guesses the answer
     * with n questions.
     * Answer with true and false or 1 and 0
     * @param n
     */
    public static void toThePowerOfTwo(int n) {
        int N = (int) Math.pow(2, n);
        StdOut.printf("Think of an integer between %d and %d\n", 0, N-1);
        int v = search(0, N);
        System.out.printf("Your number is %d\n", v);
    }

    public static void main(String[] args) {
//    	million();
    	toThePowerOfTwo(20);
    }
} 