How to resolve the algorithm Guess the number/With feedback (player) step by step in the Fortran programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Guess the number/With feedback (player) step by step in the Fortran programming language

Table of Contents

Problem Statement

Write a player for the game that follows the following rules: The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Guess the number/With feedback (player) step by step in the Fortran programming language

Source code in the fortran programming language

program Guess_a_number_Player
  implicit none
  
  integer, parameter :: limit = 100
  integer :: guess, mx = limit, mn = 1
  real :: rnum
  character(1) :: score
  
  write(*, "(a, i0, a)") "Think of a number between 1 and ", limit, &
                         " and I will try to guess it." 
  write(*, "(a)")  "You score my guess by entering: h if my guess is higher than that number"
  write(*, "(a)")  "                                l if my guess is lower than that number"
  write(*, "(a/)") "                                c if my guess is the same as that number"

  call random_seed
  call random_number(rnum)
  guess = rnum * limit + 1
  do
    write(*, "(a, i0, a,)", advance='no') "My quess is: ", guess, "   Score(h, l or c)?: "
    read*, score
    select case(score)
      case("l", "L")
        mn = guess
        guess = (mx-guess+1) / 2 + mn 
        
      case("h", "H")
        mx = guess
        guess = mx - (guess-mn+1) / 2 

      case("c", "C")
        write(*, "(a)") "I solved it!"
        exit

      case default
        write(*, "(a)") "I did not understand that"
    end select
  end do
end program


  

You may also check:How to resolve the algorithm Increment a numerical string step by step in the UNIX Shell programming language
You may also check:How to resolve the algorithm Super-Poulet numbers step by step in the Wren programming language
You may also check:How to resolve the algorithm Weird numbers step by step in the Python programming language
You may also check:How to resolve the algorithm 99 bottles of beer step by step in the IDL programming language
You may also check:How to resolve the algorithm Mutual recursion step by step in the Euphoria programming language