jeudi 11 février 2021

Optimizing my guessing algorithm for number guesser

I'm a relatively new coder learning Java, and my CompSci teacher assigned us something called a number guesser game, where you have to guess a random number. However, in assignment was a section on extra credit, where the user thinks of a number, and the computer has to guess what the number is in as few tries as possible.

Right now, my code for doing so looks something like this:

public static void gamone() {
        System.out.println("Think of a number between 1 and anything- I'll try and guess it.");
        System.out.println("What is the end of the range?");
        double range = s.nextDouble();
        int guess, count=0, which = 0;
        double base = 0;
        String response;
        guess = (int) (range / 2.0);
            while (count < 15) {
                count++;
                System.out.println("Is the number " + guess + "?");
                response = s.nextLine();
                response = response.toLowerCase();
                
                
                if (response.contains("yes")) {
                    System.out.println("I'm just that good, huh?");
                    break;
                }
                
                
                else if (response.contains("no")){  
                    System.out.println("Was is higher or lower?");
                    response = s.nextLine();
                    response = response.toLowerCase();

                    if (response.contains("h")) {
                        base = guess;
                    
                            guess = (int) ((range - guess) / 2.0) + guess;
                        
                    }else if (response.contains("l")) {
                        range = guess;

                            guess = guess - (int)((guess - base) / 2.0);

                    }
                    
                    
            }
        
        
        }
            System.out.println(count);
    }

I Understand the best way mathematically is to simply do what I did- to divide the difference by 2 and add or subtract that. However, is there a way I could use things like random numbers to actually make it better at guessing numbers?




Aucun commentaire:

Enregistrer un commentaire