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

Source code in the racket programming language

#lang racket

(define (guess low high)
  (define (input-loop available)
    (define input (car (string->list (symbol->string (read)))))
    (if (member input available)
        input
        (begin
          (printf "Invalid Input\n") (input-loop available))))
  
  (define (guess-loop low high)
    (define guess (floor (/ (+ low high) 2)))
    (printf "My guess is ~a.\n" guess)
    (define input (input-loop (list #\c #\l #\h)))
    (case input
      ((#\c) (displayln "I knew it!\n"))
      ((#\l) (guess-loop low (sub1 guess)))
      ((#\h) (guess-loop (add1 guess) high))))
  
  (printf "Think of a number between ~a and ~a.
Use (h)igh, (l)ow and (c)orrect to guide me.\n" low high)
  (guess-loop low high))


#lang racket
(define (guess minimum maximum)
  (printf "Think of a number from ~a to ~a, use (h)igh, (l)ow and (c)orrect." minimum maximum)
  
  (define input "")
  
  (do ((guess (round (/ (+ maximum minimum) 2))  (round (/ (+ maximum minimum) 2))))
    ((string=? input "c"))
    (printf "My guess is: ~a\n(h/l/=) > ")
    (when (string=? input "h")
      (begin (display "OK...")
               (set! maximum (sub1 guess))))
        (when (string=? input "l")
          (begin (display "OK...")
                 (set! minimum (add1 guess)))))
  (displayln "I was RIGHT!"))


  

You may also check:How to resolve the algorithm Sylvester's sequence step by step in the Swift programming language
You may also check:How to resolve the algorithm Trigonometric functions step by step in the SparForte programming language
You may also check:How to resolve the algorithm 24 game/Solve step by step in the Gosu programming language
You may also check:How to resolve the algorithm 99 bottles of beer step by step in the Jakt programming language
You may also check:How to resolve the algorithm Conway's Game of Life step by step in the JavaScript programming language