Random number near the best guess (binary search with variety)


#1

public class NumberWizard : MonoBehaviour
{
    [SerializeField] public int min = 1;
    [SerializeField] public int max = 1000;
    [SerializeField] public TextMeshProUGUI gameText;

    private int guess;
    private int numberOfGuesses;

    // Start is called before the first frame update
    void Start()
    {
        NewGuess();
        gameText.SetText("Is it " + guess + "?");
    }


    void NewGuess()
    {
        numberOfGuesses++;
        var bestGuess = Mathf.FloorToInt((min + max) / 2);
        var rangeMin = bestGuess - Mathf.FloorToInt((bestGuess - min) / 2);
        var rangeMax = bestGuess + Mathf.FloorToInt((max - bestGuess) / 2);
        guess = Random.Range(rangeMin, rangeMax);
    }

    public void OnPressHigher()
    {
        min = guess;
        NewGuess();
        gameText.SetText(guess + "?");
    }

    public void OnPressLower()
    {
        max = guess;
        NewGuess();
        gameText.SetText(guess + "?");
    }

}