How to resolve the algorithm Guess the number/With feedback (player) step by step in the Nim 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 Nim 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 Nim programming language

Source code in the nim programming language

import strutils

let oRange = 1..10
var iRange = oRange

echo """Think of a number between $# and $# and wait for me to guess it.
On every guess of mine you should state whether the guess was
too high, too low, or equal to your number by typing h, l, or =""".format(iRange.a, iRange.b)

var i = 0
while true:
  inc i
  let guess = (iRange.a + iRange.b) div 2
  stdout.write "Guess $# is: $#. The score for which is (h,l,=): ".format(i, guess)
  let txt = stdin.readLine()

  case txt
  of "h": iRange.b = guess - 1
  of "l": iRange.a = guess + 1
  of "=":
    echo "  Ye-Haw!!"
    break
  else: echo "  I don't understand your input of '%s'?".format(txt)

  if iRange.a > iRange.b or iRange.a < oRange.a or iRange.b > oRange.b:
    echo "Please check your scoring as I cannot find the value"
    break

echo "Thanks for keeping score."


  

You may also check:How to resolve the algorithm Memory layout of a data structure step by step in the PL/I programming language
You may also check:How to resolve the algorithm Window creation step by step in the Common Lisp programming language
You may also check:How to resolve the algorithm Multifactorial step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Break OO privacy step by step in the OCaml programming language
You may also check:How to resolve the algorithm Array length step by step in the C# programming language