In: Computer Science
Write a program that will guess an integer that the user has picked. Imagine that the user will write down a positive integer x on a piece of paper and your program will repeatedly ask questions in order to guess what x is, and the user replies honestly. Your program will start by asking for an int n, and you must have 1 ≤ x ≤ n. After that, the program will successively guess what x is, and the user must tell the computer if x is equal to the guess (entering ’e’), larger than the guess (entering ’l’), or smaller than the guess (entering ’s’). Your program will guess by maintaining a lower bound (initially 1) and upper bound (initially n) and pick the largest integer equal to or smaller than1 the midpoint of the lower bound and upper bound. If the user responds with ’l’ indicating that x is larger, the guess becomes the new lower bound plus one. If the user responds with ’s’ indicating that x is smaller, the guess becomes the new upper bound minus one. If the user responds with ’e’ indicating that x is the guess, your program will report the number of guesses made and terminate execution:
Example 1)
Enter n: 50
Is your number 25? l
Is your number 38?
l Is your number 44? s
Is your number 41? e
Your number must be 41. I used 4 guesses.
Example 2)
Enter n: 9
Is your number 5? s
Is your number 2?
l Is your number 3? s
Error: that’s not possible.
Example 3)
Enter n: -2
Error: n must be positive.
Example 4)
Enter n: 9
Is your number 5? m
Error: invalid input.
Example 5)
Enter n: a
Error: invalid input.
import java.*;
import java.util.Scanner;
public class nnnn {
public static void main(String args[])
{
Scanner s=new
Scanner(System.in);
System.out.print("Enter the
no.");
int n=s.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=i;
}
nnna ob=new nnna();
int r= ob.binarySearch(arr,0,n-1);
System.out.println("I used "+r+"guesses");
}
}
public class nnna {
int a=0;
int binarySearch(int arr[], int l, int r)
{
Scanner sc=new
Scanner(System.in);
if (r>=l)
{
int mid = l + (r - l)/2;
System.out.println("Is your number
"+arr[mid]+"");
char c = sc.next().charAt(0);
// If the element is present at the middle
itself
if (c=='e')
{
a++;
}
// If element is smaller than mid, then it can
only
// be present in left subarray
if (c=='s')
{
a++;
binarySearch(arr, l, mid-1);
}
// Else the element can only be present in right
// subarray
if(c=='l')
{
a++;
binarySearch(arr, mid+1, r);
}
}
// We reach here when element is not present in
array
return a;
}
}