Guessing an Integer Number in a Range in Python

                                               Guessing an Integer Number in a Range

Problem statement 

     The objective is to randomly generate integer number from 0 to n.  Then the player has to guess the number. If the player guesses the number correctly output an appropriate message.

     If the guessed number is less than the random number generated, output the message "Your guess is lower than the number.  Guess again." , otherwise output the message "Your guess is higher than the number.  Guess again:.

     Then the player guesses another number.  This process is repeated until the player guesses the correct number.  


Algorithm 


     1.  Start. 

     2.  Generate a random numbers and read num.

                 a.  Enter the number to guess. 

                 b.  If ( guess is equal to num ) 

                                   Print "You guess the correct number".

                      Otherwise 

                                If (guess is less than num)

                                    Print " Your guess is lower than the number. Guess again".

     3.  Stop 


Flow Chart



Example 


     Consider to guess a number between 1 and 100.  The number selected for guess is 82.  Now the player wants to guess this number.  

     The best strategy is choosing 50 as the first guess.  If that guess is high, then the player should guess 25.  If 50 is low then guess 75.  Each guess, select a new midpoint by adjusting the lower range or the upper range of the numbers, which becomes the next guess.  This strategy will eventually guess the correct number.  

     Following example demonstrate how this method works if the number to be chosen is 82. 

     Guessing Game-Secret  number is 82


Guessing a Number in a Range 

Pseudocode 

                     Binsearch( int value)

                     {

                      int upperBound, lowerBound, mid;

                      upperBound = n-1;

                      lowerBound = 0;

                      while (lowerBound <=upperBound)

                      {

                            mid = (upperBound+lowerBound) / 2; 

                            if (A[mid] = = value)

                            return mid;

                      else

                            if (value < A [mid])

                                    upperBound = mid-1;

                            else

                                    lowerBound = mid+1;

                       }

                       return;

                       } 

Comments

Popular posts from this blog

Health is wealth meaning

Your Aim is Gold.

Many men many mind proverb reasons