How to resolve the algorithm Guess the number/With feedback (player) step by step in the Swift 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 Swift 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 Swift programming language
Source code in the swift programming language
import Cocoa
var found = false
let fh = NSFileHandle.fileHandleWithStandardInput()
println("Enter an integer between 1 and 100 for me to guess: ")
let data = fh.availableData
var num:Int!
var low = 0.0
var high = 100.0
var lastGuess:Double!
if let numFromData = NSString(data: data, encoding: NSUTF8StringEncoding)?.intValue {
num = Int(numFromData)
}
func guess() -> Double? {
if (high - low == 1) {
println("I can't guess it. I think you cheated.");
return nil
}
return floor((low + high) / 2)
}
while (!found) {
if let guess = guess() {
lastGuess = guess
} else {
break
}
println("My guess is: \(Int(lastGuess))")
println("How was my guess? Enter \"higher\" if it was higher, \"lower\" if it was lower, and \"correct\" if I got it")
let data = fh.availableData
let str = NSString(data: data, encoding: NSUTF8StringEncoding)
if (str == nil) {
continue
}
if (str! == "correct\n") {
found = true
println("I did it!")
} else if (str! == "higher\n") {
low = lastGuess
} else if (str! == "lower\n") {
high = lastGuess
}
}
You may also check:How to resolve the algorithm Sum of a series step by step in the Maple programming language
You may also check:How to resolve the algorithm File input/output step by step in the M2000 Interpreter programming language
You may also check:How to resolve the algorithm Filter step by step in the 11l programming language
You may also check:How to resolve the algorithm Ultra useful primes step by step in the Phix programming language
You may also check:How to resolve the algorithm Runtime evaluation/In an environment step by step in the EchoLisp programming language