subject :

java Automatically generate a 0 reach 1000000000 Number between , And guess for yourself ( Until you guess right , The computer will tell you to guess big or small ), And record the number of guesses and the value of guesses .

First, we need to create a random number , And let him be our guess .
Random r=new Random(); int x=r.nextInt(1000000000);

Imagine , If we guess , We won't guess blindly ( If you keep guessing, you will succeed , But the time and frequency of consumption are very large ), We'll keep narrowing the range of guesses , For example, our guess is 21, Our first guess was 40,40 Bigger than we guessed , We'll be there 0 reach 40 Guess between , The number we guessed for the second time was 11,11 Smaller than we have to guess , So next time we guess the number will be 11 reach 40 between , In this way, we will continue to compress the range in future guessing ( Boundary problem ), To guess our target number .

We use xr and xl As right and left boundaries count As the number of guesses , And initialize (xl=0,xr=1000000000,count=0).
int xl=0,xr=1000000000,count=0;

We pass while The cycle keeps the machine guessing , Each guess will compress the range , Until you guess the number and jump out of the loop .

All codes are as follows :
import java.util.Random; public class cai_shu { public static void
main(String[] args) { Random r=new Random(); int x=r.nextInt(1000000000); int
xl=0,xr=1000000000,count=0; System.out.println(" The number to guess is "+x); boolean key=true;
while(key) { count++;// Addition times int y=new Random().nextInt(xr);// The number guessed by the machine if(y<=xl) {
y=xl+new Random().nextInt(xr-xl);// Keep the number guessed by the machine within the left and right boundaries . }
System.out.println(" The number of guesses this time is "+y); if(y==x) {
key=false;// Jump out of loop , use break Words ,while The condition of the cycle is xr!=xl. System.out.println(" Finally guessed right ");
}else {// If you don't guess right, you need to compress the range if(y>x&&y<=xr) { xr=y; } if(y<x&&y>=xl){ xl=y; } } }
System.out.println(" I guess "+count+" second "); } }
Note that the class name should be consistent !

After many tests , The test results are generally maintained at 60 Within one time ( The effect is ideal !).

  be accomplished , If you don't understand something, please leave a message in the comment area .....

thanks everyone!

Technology
©2019-2020 Toolsou All rights reserved,
C++ of string of compare usage Python Study notes ( one )evo Tool usage problems ——Degenerate covariance rank, Umeyama alignment is not possibleRISC-V_GD32VF103-TIMER0 timer interrupt java Array subscript variable _Java Basic grammar : array be based on stm32 Control four-wheel trolley motor drive ( one ) be based on redis Design of liking function Software engineering career planning mysql Query random data by conditions _MySQL Random query of several qualified records centos7 install RabbitMq