Guess the number/With feedback (player): Difference between revisions

Added Easylang
(Added Easylang)
 
(119 intermediate revisions by 61 users not shown)
Line 1:
{{task|Games}}
 
The task is to write a player for the game that follows the following rules:
;Task:
Write a player for the game that follows the following rules:
:The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the scorer scores, in turn, until the computer correctly guesses the target number.
 
The computer should guess intelligently based on the accumulated scores given. One way is to use a [[Binary search]] based algorithm.
 
 
Cf. [[Guess the number/With Feedback]], [[Bulls and cows/Player]]
;Related tasks:
*   [[Guess the number/With Feedback]]
*   [[Bulls and cows/Player]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V (target_min, target_max) = (1, 10)
V (mn, mx) = (target_min, target_max)
 
print(
‘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(target_min, target_max))
 
V i = 0
L
i++
V guess = (mn + mx) I/ 2
V txt = input(‘Guess #2 is: #2. The score for which is (h,l,=): ’.format(i, guess)).trim(‘ ’).lowercase()[0]
I txt !C ‘hl=’
print(‘ I don't understand your input of '#.' ?’.format(txt))
L.continue
I txt == ‘h’
mx = guess - 1
I txt == ‘l’
mn = guess + 1
I txt == ‘=’
print(‘ Ye-Haw!!’)
L.break
I (mn > mx) | (mn < target_min) | (mx > target_max)
print(‘Please check your scoring as I cannot find the value’)
L.break
 
print("\nThanks for keeping score.")</syntaxhighlight>
 
{{out}}
<pre>
Think of a number between 1 and 10 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 =
 
Guess 1 is: 5. The score for which is (h,l,=): l
Guess 2 is: 8. The score for which is (h,l,=): l
Guess 3 is: 9. The score for which is (h,l,=): l
Guess 4 is: 10. The score for which is (h,l,=): =
Ye-Haw!!
 
Thanks for keeping score.
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Main()
BYTE n,min=[1],max=[100]
CHAR c
 
PrintF("Think a number in range %B-%B%E",min,max)
DO
n=(max+min) RSH 1
PrintF("My guess is %B%E",n)
PrintF("Is it (E)qual, (L)ower or (H)igher?")
c=GetD(7)
Put(c) PutE()
IF c='E THEN
Print("I guessed!")
EXIT
ELSEIF c='L THEN
max=n-1
ELSEIF c='H THEN
min=n+1
FI
IF max<min THEN
Print("You are cheating...")
EXIT
FI
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Guess_the_number_with_feedback_(player).png Screenshot from Atari 8-bit computer]
<pre>
Think a number in range 1-100
My guess is 50
Is it (E)qual, (L)ower or (H)igher?L
My guess is 25
Is it (E)qual, (L)ower or (H)igher?L
My guess is 12
Is it (E)qual, (L)ower or (H)igher?H
My guess is 18
Is it (E)qual, (L)ower or (H)igher?L
My guess is 15
Is it (E)qual, (L)ower or (H)igher?L
My guess is 13
Is it (E)qual, (L)ower or (H)igher?E
I guessed!
</pre>
 
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
procedure Guess_Number_Player is
procedure Guess_Number (Lower_Limit : Integer; Upper_Limit : Integer) is
Line 44 ⟶ 143:
end loop;
Guess_Number (Lower_Limit, Upper_Limit);
end Guess_Number_Player;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
<syntaxhighlight lang="algol68">BEGIN
INT lower := 1;
INT upper := 100;
print( ( "Think of a number between ", whole( lower, 0 ), " and ", whole( upper, 0 ), newline ) );
print( ( "Please enter Y if I guess correctly, L is it is lower, G if it is greater or Q if you've had enough", newline ) );
WHILE
INT mid = lower + ( ( upper - lower ) OVER 2 );
CHAR reply;
WHILE
print( ( "Is it ", whole( mid, 0 ), "? Y/L/G/Q: " ) );
read( ( reply, newline ) );
NOT char in string( reply, NIL, "YLGQylgq" )
DO SKIP OD;
IF reply = "Q" OR reply = "q" OR reply = "Y" OR reply = "y"
THEN FALSE
ELIF lower >= upper THEN
print( ( "Based on your answers so far, it must be ", whole( lower, 0 ), newline ) );
FALSE
ELSE
IF reply = "L" OR reply = "l" THEN upper := mid - 1
ELIF reply = "G" OR reply = "g" THEN lower := mid + 1
FI;
TRUE
FI
DO SKIP OD
END</syntaxhighlight>
 
=={{header|AppleScript}}==
 
<syntaxhighlight lang="applescript">-- defining the range of the number to be guessed
property minLimit : 1
property maxLimit : 100
 
on run
-- ask the user to think of a number in the given range
display dialog "Please think of a number between " & minLimit & " and " & maxLimit
-- prepare a variable for the lowest guessed value
set lowGuess to minLimit
-- prepare a variable for the highest guessed value
set highGuess to maxLimit
repeat
-- guess a number inside the logical range
set computersGuess to (random number from lowGuess to highGuess)
-- ask the user to check my guess
set guessResult to button returned of (display dialog "I guess " & computersGuess & "!" & return & "What do you think?" buttons {"Lower", "Correct", "Higher"})
if guessResult = "Lower" then
-- the number is less than the guess, switch the upper limit to the guess
set highGuess to computersGuess
else if guessResult = "Higher" then
-- the number is greater than the guess, switch the lower limit to the guess
set lowGuess to computersGuess
else if guessResult = "Correct" then
-- the computer guessed the number, beep and exit
beep
exit repeat
end if
end repeat
end run</syntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">print {:
Think of a number between 1 and 10 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 =
:}
 
rmin: 1
rmax: 10
 
while ø [
guess: random rmin rmax
print ["My guess is:" guess]
inputOk: false
while [not? inputOk][
hle: strip input "How did I do? (h)igh, (l)ow, (=): "
case [hle]
when? [="h"][
if? rmin =< dec guess [rmax: dec guess, inputOk: true]
else -> print "\tThat doesn't make any sense. I cannot find the number..."
]
when? [="l"][
if? (inc guess) =< rmax [rmin: inc guess, inputOk: true]
else -> print "\tThat doesn't make any sense. I cannot find the number..."
]
when? [="="][
print ""
print "Great! I found it! :)"
print "Thanks for keeping the score."
exit
]
else [
print "\tPlease, check your input; it doesn't appear to be correct!"
]
]
print ""
]</syntaxhighlight>
 
{{out}}
 
<pre>Think of a number between 1 and 10 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 =
 
My guess is: 7
How did I do? (h)igh, (l)ow, (=): h
 
My guess is: 1
How did I do? (h)igh, (l)ow, (=): fff
Please, check your input; it doesn't appear to be correct!
How did I do? (h)igh, (l)ow, (=): l
 
My guess is: 3
How did I do? (h)igh, (l)ow, (=): h
 
My guess is: 2
How did I do? (h)igh, (l)ow, (=): l
That doesn't make any sense. I cannot find the number...
How did I do? (h)igh, (l)ow, (=): =
 
Great! I found it! :)
Thanks for keeping the score.</pre>
 
=={{header|AsciiDots}}==
 
This is certainly not the fastest or smallest AsciiDots implementation of this task, but it works consistently.
 
The instructions print in order only because the ends of the lines are aligned. If they were not, they might print in a different order. The "Impossible" error message indicates that their are no remaining logical guesses. The range of 1 to 127 was chosen because it's easy to binary-search. All numbers are floating-point integers in AsciiDots, so rounding would be needed to use a range like 1 to 100.
 
<syntaxhighlight lang="asciidots">
/.
*$"Think of a number from 1 to 127"
*$"Enter H if my guess is too high" /#67\
*-$"Enter L if my guess is too low" *--{=}:$""$"I WIN"&
\-$"Enter C if my guess is correct"\| /------~*{-}\
/23@-------------------------------/|/#72\ | !| @ |
\#64>*$_"Is it "$_#$_"? (H/L/C) "#a?**--{=}+------/\-/ |
/---/| | | |
| \------------------------------+------*~*{+}------v
| /#1{>}:$"Impossible"&|/#76\ !| @ |
|#a_$01#\ /2#\ | @ \*--{=}-/\-/ |
\-------*{/}@*-*---*-----------------------------------/
</syntaxhighlight>
 
=={{header|AutoHotkey}}==
Line 50 ⟶ 297:
Works with the AutoHotkey entry at: [[Guess the number/With feedback]]
 
<langsyntaxhighlight AutoHotkeylang="autohotkey">MaxGuesses = 50
 
GetParams(LowerBound,UpperBound)
Line 103 ⟶ 350:
Else
Return, "Too High"
}</langsyntaxhighlight>
 
=={{header|Batch File}}==
<syntaxhighlight lang="dos">
@echo off
 
:: Player is prompted to give a number between %min% and %max%. If the input is out of those limits they are prompted to choose again
:choose
set min=0
set max=100
 
set /p "number=Choose a number [%min%-%max%]: "
if %number% gtr %max% goto choose
if %number% lss %min% goto choose
set attempts=0
 
:: Loops the guessing process until completed
:comp
set /a attempts+=1
set /a guess=(%max%-%min%)/2+%min%
choice /c "HLE" /n /m "Guess: %guess% - [H]igher, [L]ower or [E]qual"
if errorlevel 3 goto end
if errorlevel 2 (
set max=%guess%
goto comp
)
if errorlevel 1 (
set min=%guess%
goto comp
)
 
:end
echo Guesses: %attempts%
pause>nul
</syntaxhighlight>
{{out}}
<pre>
Choose a number [0-100]: 42
Guess: 50 - [H]igher, [L]ower or [E]qual L
Guess: 25 - [H]igher, [L]ower or [E]qual H
Guess: 37 - [H]igher, [L]ower or [E]qual H
Guess: 43 - [H]igher, [L]ower or [E]qual L
Guess: 40 - [H]igher, [L]ower or [E]qual H
Guess: 41 - [H]igher, [L]ower or [E]qual H
Guess: 42 - [H]igher, [L]ower or [E]qual E
Guesses: 7
</pre>
 
=={{header|BASIC}}==
<syntaxhighlight lang="basic">10 DEFINT A-Z
20 INPUT "Lower limit? ",L
30 INPUT "Upper limit? ",H
40 IF L>H THEN PRINT "Invalid input": END
50 PRINT "My guess is ";(H-L)\2+L
55 T=T+1
60 INPUT "Too low (L), too high (H), or correct (C)? ",R$
70 ON INSTR("LlHhCc",R$) GOTO 90,90,100,100,110,110
80 PRINT "Invalid input": GOTO 50
90 L=(H-L)\2+L: GOTO 40
100 H=(H-L)\2+L: GOTO 40
110 PRINT "It took";T;"tries."</syntaxhighlight>
{{out}}
<pre>Lower limit? 1
Upper limit? 100
My guess is 50
Too low (L), too high (H), or correct (C)? L
My guess is 75
Too low (L), too high (H), or correct (C)? L
My guess is 87
Too low (L), too high (H), or correct (C)? H
My guess is 81
Too low (L), too high (H), or correct (C)? L
My guess is 84
Too low (L), too high (H), or correct (C)? L
My guess is 85
Too low (L), too high (H), or correct (C)? C
It took 6 tries.</pre>
 
=={{header|BBC BASIC}}==
<syntaxhighlight lang="bbcbasic"> min% = 1
max% = 100
PRINT "Think of a number between "; min% " and " ;max%
PRINT "I will try to guess your number."
REPEAT
guess% = (min% + max%) DIV 2
PRINT "My guess is " ; guess%
INPUT "Is it higher than, lower than or equal to your number", answer$
CASE LEFT$(answer$,1) OF
WHEN "L","l": min% = guess% + 1
WHEN "H","h": max% = guess% - 1
WHEN "E","e": EXIT REPEAT
OTHERWISE: PRINT "Sorry, I didn't understand your answer."
ENDCASE
UNTIL FALSE
PRINT "Goodbye."
END</syntaxhighlight>
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
let reads(s) = valof
$( s%0 := 0
$( let c = rdch()
if c = endstreamch resultis false
if c = '*N' resultis true
s%0 := s%0 + 1
s%(s%0) := c
$) repeat
$)
 
let choose(chs) = valof
$( let ans = vec 80
writef("[%S]? ",chs)
unless reads(ans) finish
unless ans%0=1 loop
for i=1 to chs%0
if (ans%1|32) = (chs%i|32) resultis chs%i
$) repeat
 
let tantrum() be
$( writes("Cheater!*N")
finish
$)
 
let guess(lo, hi, t) = valof
$( let ans = vec 80
test hi<lo do tantrum()
or test hi=lo
$( writef("Is the number %N ",lo)
test choose("yn")='y' resultis t or tantrum()
$)
or
$( let g = (hi-lo)/2+lo
writef("My guess is %N. Too low, too high, or correct ",g)
switchon choose("lhc") into
$( case 'l': resultis guess(g, hi, t+1)
case 'h': resultis guess(lo, g, t+1)
case 'c': resultis t
$)
$)
$)
 
let start() be
$( let min = ? and max = ?
writes("Lower bound? ") ; min := readn()
writes("Upper bound? ") ; max := readn()
writef("It took %N attempts.*N", guess(min, max, 1))
$)</syntaxhighlight>
{{out}}
<pre>Lower bound? 1
Upper bound? 100
My guess is 50. Too low, too high, or correct [lhc]? l
My guess is 75. Too low, too high, or correct [lhc]? l
My guess is 87. Too low, too high, or correct [lhc]? h
My guess is 81. Too low, too high, or correct [lhc]? l
My guess is 84. Too low, too high, or correct [lhc]? l
My guess is 85. Too low, too high, or correct [lhc]? c
It took 6 attempts.</pre>
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
 
int main(){
Line 135 ⟶ 539:
 
return 0;
}</langsyntaxhighlight>
 
Demonstration (number is 57):
Line 148 ⟶ 552:
Awwwright</pre>
 
----
=={{header|C++}}==
 
A clever solution that takes advantage of C++'s built-in binary search function <code>lower_bound()</code>. Instead of searching a slice of a container, we search a range of numbers by implementing a specially-designed custom iterator.
The following is a hacky solution using <tt>bsearch()</tt> and pointers to represent integers. Although the pointers do not point to valid things, <tt>bsearch()</tt> doesn't actually dereference the pointers or care what they point to; it just passes them to the comparator and searches the space of pointers. We can use that to search any space of integers.
{{trans|Go}}
{{trans|Java}}
<lang cpp>#include <iostream>
<syntaxhighlight lang="c">#include <algorithmstdio.h>
#include <stringstdlib.h>
#include <iteratorctype.h>
 
enum {
struct GuessNumberIterator : std::iterator<std::random_access_iterator_tag, int> {
intLOWER i;= 0,
UPPER = 100,
GuessNumberIterator() { }
KEY = LOWER-1 // some value that is not in the valid range
GuessNumberIterator(int _i) : i(_i) { }
};
GuessNumberIterator& operator++() { ++i; return *this; }
 
GuessNumberIterator operator++(int) {
char dummy;
GuessNumberIterator tmp = *this; ++(*this); return tmp; }
// A pointer to represent the integer 0, and the basis of our integer-as-pointer
bool operator==(const GuessNumberIterator& y) { return i == y.i; }
// representation. We can't use the null pointer because bsearch() returns that
bool operator!=(const GuessNumberIterator& y) { return i != y.i; }
// for not found.
int operator*() {
#define ZERO ((void *)&dummy)
std::cout << "Is your number less than or equal to " << i << "? ";
 
std::string s;
int get_value(int x) {
std::cin >> s;
if (x == KEY)
return (s != "" && (s[0] == 'y' || s[0] == 'Y')) ? 0 : -1;
return 0;
printf("My guess is: %d. Is it too high, too low, or correct? (H/L/C) ", x);
char input[2] = " ";
scanf("%1s", input);
switch (tolower(input[0])) {
case 'l':
return -1;
case 'h':
return 1;
case 'c':
return 0;
}
fprintf(stderr, "Invalid input\n");
GuessNumberIterator& operator--() { --i; return *this; }
exit(1);
GuessNumberIterator operator--(int) {
return 0;
GuessNumberIterator tmp = *this; --(*this); return tmp; }
}
GuessNumberIterator& operator+=(int n) { i += n; return *this; }
 
GuessNumberIterator& operator-=(int n) { i -= n; return *this; }
int my_cmp(const void *x, const void *y) {
GuessNumberIterator operator+(int n) {
return get_value(x - ZERO) - get_value(y - ZERO);
GuessNumberIterator tmp = *this; return tmp += n; }
}
GuessNumberIterator operator-(int n) {
 
GuessNumberIterator tmp = *this; return tmp -= n; }
int operator-(const GuessNumberIterator &y) { return i - y.i; }
int operator[](int n) { return *(*this + n); }
bool operator<(const GuessNumberIterator &y) { return i < y.i; }
bool operator>(const GuessNumberIterator &y) { return i > y.i; }
bool operator<=(const GuessNumberIterator &y) { return i <= y.i; }
bool operator>=(const GuessNumberIterator &y) { return i >= y.i; }
};
inline GuessNumberIterator operator+(int n, GuessNumberIterator &i) { return i + n; }
const int lower = 0;
const int upper = 100;
int main() {
std::cout << printf("Instructions:\n"
<< "Think of integer number from "%d <<(inclusive) lowerto << "%d (inclusiveexclusive) to and\n"
"I will guess it. After each guess, you respond with L, H, or C depending\n"
<< upper << " (exclusive) and\n"
"on if << "I willmy guess it.was Aftertoo each guesslow, Itoo willhigh, askor you if it is less thancorrect.\n",
LOWER, UPPER);
<< "or equal to some number, and you will respond with \"yes\" or \"no\".\n";
void *result = bsearch(ZERO + KEY, ZERO + LOWER, UPPER-LOWER, 1, my_cmp);
int answer = std::lower_bound(GuessNumberIterator(lower), GuessNumberIterator(upper), 0).i;
if (result == NULL)
std::cout << "Your number is " << answer << ".\n";
fprintf(stderr, "That is impossible.\n");
else
printf("Your number is %d.\n", (int)(result - ZERO));
return 0;
}</langsyntaxhighlight>
 
=={{header|C# sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 336 ⟶ 742:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
A clever solution that takes advantage of C++'s built-in binary search function <code>lower_bound()</code>. Instead of searching a slice of a container, we search a range of numbers by implementing a specially-designed custom iterator.
{{trans|Go}}
<syntaxhighlight lang="cpp">#include <iostream>
#include <algorithm>
#include <string>
#include <iterator>
struct GuessNumberIterator : std::iterator<std::random_access_iterator_tag, int> {
int i;
GuessNumberIterator() { }
GuessNumberIterator(int _i) : i(_i) { }
GuessNumberIterator& operator++() { ++i; return *this; }
GuessNumberIterator operator++(int) {
GuessNumberIterator tmp = *this; ++(*this); return tmp; }
bool operator==(const GuessNumberIterator& y) { return i == y.i; }
bool operator!=(const GuessNumberIterator& y) { return i != y.i; }
int operator*() {
std::cout << "Is your number less than or equal to " << i << "? ";
std::string s;
std::cin >> s;
return (s != "" && (s[0] == 'y' || s[0] == 'Y')) ? 0 : -1;
}
GuessNumberIterator& operator--() { --i; return *this; }
GuessNumberIterator operator--(int) {
GuessNumberIterator tmp = *this; --(*this); return tmp; }
GuessNumberIterator& operator+=(int n) { i += n; return *this; }
GuessNumberIterator& operator-=(int n) { i -= n; return *this; }
GuessNumberIterator operator+(int n) {
GuessNumberIterator tmp = *this; return tmp += n; }
GuessNumberIterator operator-(int n) {
GuessNumberIterator tmp = *this; return tmp -= n; }
int operator-(const GuessNumberIterator &y) { return i - y.i; }
int operator[](int n) { return *(*this + n); }
bool operator<(const GuessNumberIterator &y) { return i < y.i; }
bool operator>(const GuessNumberIterator &y) { return i > y.i; }
bool operator<=(const GuessNumberIterator &y) { return i <= y.i; }
bool operator>=(const GuessNumberIterator &y) { return i >= y.i; }
};
inline GuessNumberIterator operator+(int n, GuessNumberIterator &i) { return i + n; }
const int lower = 0;
const int upper = 100;
int main() {
std::cout << "Instructions:\n"
<< "Think of integer number from " << lower << " (inclusive) to "
<< upper << " (exclusive) and\n"
<< "I will guess it. After each guess, I will ask you if it is less than\n"
<< "or equal to some number, and you will respond with \"yes\" or \"no\".\n";
int answer = std::lower_bound(GuessNumberIterator(lower), GuessNumberIterator(upper), 0).i;
std::cout << "Your number is " << answer << ".\n";
return 0;
}</syntaxhighlight>
 
=={{header|Ceylon}}==
<syntaxhighlight lang="ceylon">shared void run() {
while(true) {
variable value low = 1;
variable value high = 10;
variable value attempts = 1;
print("Please choose a number between ``low`` and ``high``.
Press enter when ready.");
process.readLine();
while(true) {
if(low > high) {
print("Something is wrong. I give up.");
break;
}
variable value guess = (low + high) / 2;
print("Is ``guess`` (e)qual, (h)igher or (l)ower to your number?
(enter q to quit)");
value answer = process.readLine()?.trimmed?.lowercased;
switch(answer)
case("e") {
print("I got it in only ``attempts`` ``attempts == 1 then "try" else "tries"``!");
break;
}
case("h") {
high = guess - 1;
attempts++;
}
case("l") {
low = guess + 1;
attempts++;
}
case("q") {
return;
}
else {
print("Please enter an e, h, l or q");
}
}
}
}</syntaxhighlight>
 
=={{header|Clojure}}==
 
<langsyntaxhighlight Clojurelang="clojure">(require '[clojure.string :as str])
 
(defn guess-game [low high]
Line 353 ⟶ 855:
\c (println "Huzzah!")
(do (println "Invalid input.")
(recur guess step)))))</langsyntaxhighlight>
Output
<pre>user=> (guess-game 1 100)
Line 370 ⟶ 872:
Huzzah!
</pre>
 
=={{header|Common Lisp}}==
An imperative solution using LOOP:
<syntaxhighlight lang="lisp">
(defun guess-the-number (&optional (max 1000) (min 0))
(flet ((get-feedback (guess)
(loop
initially (format t "I choose ~a.~%" guess)
for answer = (read)
if (member answer '(greater lower correct))
return answer
else do (write-line "Answer greater, lower, or correct."))))
(loop
initially (format t "Think of a number between ~a and ~a.~%" min max)
for guess = (floor (+ min max) 2)
for answer = (get-feedback guess)
until (eq answer 'correct)
if (eq answer 'greater) do (setf min guess)
else do (setf max guess)
finally (write-line "I got it!"))))
</syntaxhighlight>
 
A recursive solution (we use LABELS instead of FLET for the local function definitions in this version so that GUESS-LOOP will be able to call itself recursively):
<syntaxhighlight lang="lisp">
(defun guess-the-number (&optional (max 1000) (min 0))
(labels ((guess-loop (min max)
(let ((guess (floor (+ min max) 2)))
(format t "I choose ~a.~%" guess)
(case (read)
(greater (guess-loop guess max))
(lower (guess-loop min guess))
(correct (write-line "I got it!"))
(otherwise
(write-line "Please answer greater, lower, or correct.")
(guess-loop min max))))))
(format t "Think of a number between ~a and ~a.~%" min max)
(guess-loop min max)))
</syntaxhighlight>
 
=={{header|D}}==
{{trans|Python}}
<syntaxhighlight lang="d">import std.stdio, std.string;
 
void main() {
immutable mnOrig = 1, mxOrig = 10;
int mn = mnOrig, mx = mxOrig;
 
writefln(
"Think of a number between %d and %d 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 =",
mn, mx);
 
LOOP: for (int i = 1; ; i++) {
immutable guess = (mn + mx) / 2;
writef("Guess %2d is: %2d. The score for which is (h,l,=): ",
i, guess);
immutable string txt = readln().strip().toLower();
 
switch (txt) {
case "h":
mx = guess - 1;
break;
case "l":
mn = guess + 1;
break;
case "=":
writeln(" Yeehaw!!");
break LOOP;
default:
writefln(" I don't understand your input '%s'.",
txt);
continue LOOP;
}
 
if (mn > mx || mn < mnOrig || mx > mxOrig) {
writeln("Please check your scoring as" ~
" I cannot find the value");
break;
}
}
writeln("\nThanks for keeping score.");
}</syntaxhighlight>
{{out}}
<pre>Think of a number between 1 and 10 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 =
Guess 1 is: 5. The score for which is (h,l,=): l
Guess 2 is: 8. The score for which is (h,l,=): h
Guess 3 is: 6. The score for which is (h,l,=): l
Guess 4 is: 7. The score for which is (h,l,=): =
Yeehaw!!
 
Thanks for keeping score.</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| system.console}}
Thanks JensBorrisholt for System.Console [https://github.com/JensBorrisholt/DelphiConsole/tree/master/Console].
<syntaxhighlight lang="delphi">
program Guess_the_number;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
system.console;
 
type
TCharSet = set of char;
 
var
PlayerNumber, CPUNumber: word;
CPULow: word = 0;
CPUHi: word = 1000;
PlayerLow: word = 0;
PlayerHi: word = 1000;
CPUWin, PlayerWin: boolean;
CPUGuessList: string = 'Previus guesses:'#10;
PlayerGuessList: string = 'Previus guesses:'#10;
 
function WaitKey(validSet: TCharSet): char;
begin
repeat
Result := Console.ReadKey.KeyChar;
until (Result in validSet);
end;
 
function QueryNumber(msg: string): Integer;
var
buf: string;
begin
repeat
Console.WriteLine(msg);
buf := Console.ReadLine.Replace(#10, '').Replace(#13, '');
until TryStrToInt(buf, result);
end;
 
procedure Wait;
begin
Console.ForegroundColor := TConsoleColor.Yellow;
Console.WriteLine(#10'Press Enter to continue');
WaitKey([#13]);
Console.ForegroundColor := TConsoleColor.White;
end;
 
function PlayLuck: integer;
var
cpu, player: double;
begin
cpu := CPUHi - CPULow + 1;
player := PlayerHi - PlayerLow + 1;
 
Result := round(100 * cpu / (cpu + player));
end;
 
function PlayerTurn: boolean;
var
guess: word;
begin
Console.Clear;
Console.WriteLine('Player Turn({0}%%):'#10, [PlayLuck]);
Console.ForegroundColor := TConsoleColor.Gray;
console.WriteLine(PlayerGuessList + #10);
 
console.WriteLine(#10 + 'Tip: {0}..{1}' + #10, [PlayerLow, PlayerHi]);
Console.ForegroundColor := TConsoleColor.Red;
 
guess := QueryNumber('Enter your guess number:');
Console.ForegroundColor := TConsoleColor.White;
 
if guess > CPUNumber then
begin
Console.WriteLine('{0} is to high', [guess]);
PlayerGuessList := PlayerGuessList + ' ' + guess.tostring + ' is to high'#10;
PlayerHi := guess - 1;
end;
 
if guess < CPUNumber then
begin
Console.WriteLine('{0} is to Low', [guess]);
PlayerGuessList := PlayerGuessList + ' ' + guess.tostring + ' is to low'#10;
PlayerLow := guess + 1;
end;
 
Result := guess = CPUNumber;
if Result then
Console.WriteLine('Your guess is correct, you rock!')
else
Wait;
end;
 
function CPUTurn: boolean;
var
guess: word;
ans: char;
begin
guess := ((CPUHi - CPULow) div 2) + CPULow;
 
Console.Clear;
Console.WriteLine('CPU Turn({0}%%):'#10, [100 - PlayLuck]);
Console.ForegroundColor := TConsoleColor.Gray;
console.WriteLine(CPUGuessList + #10);
console.WriteLine(#10 + 'Tip: {0}..{1}' + #10, [CPULow, CPUHi]);
Console.ForegroundColor := TConsoleColor.Red;
Console.WriteLine('My guess number is {0}'#10, [guess]);
Console.ForegroundColor := TConsoleColor.White;
 
Console.WriteLine('Press "l" = too low, "h" = too high, "c" = correct', [guess]);
ans := WaitKey(['l', 'h', 'c']);
 
Result := false;
case ans of
'l':
begin
CPULow := guess + 1;
Console.WriteLine(#10'Then my guess is to low'#10);
CPUGuessList := CPUGuessList + ' ' + guess.tostring + ' is to low'#10;
end;
'h':
begin
CPUHi := guess - 1;
Console.WriteLine(#10'Then my guess is to high'#10);
CPUGuessList := CPUGuessList + ' ' + guess.tostring + ' is to high'#10;
end
else
Result := True;
end;
 
if Result then
Console.WriteLine(#10'My guess is correct, Good luck in the next time')
else
Wait;
end;
 
begin
Randomize;
CPUNumber := Random(1001);
Console.WriteLine('Press Enter and I will start to guess the number.');
 
repeat
PlayerWin := PlayerTurn();
if PlayerWin then
Break;
CPUWin := CPUTurn();
if CPUWin then
Break;
until false;
 
Console.ForegroundColor := TConsoleColor.Green;
 
if PlayerWin then
Console.WriteLine('Player win!')
else
begin
Console.WriteLine('CPU win!');
Console.WriteLine('If you wanna know, my number was {0}', [CPUNumber]);
end;
 
readln;
end.</syntaxhighlight>
=={{header|EasyLang}}==
{{trans|Ring}}
<syntaxhighlight>
min = 1
max = 100
print "Think of a number between " & min & " and " & max
print "I will try to guess your number."
repeat
guess = (min + max) div 2
print "My guess is " & guess
write "Is it higher than, lower than or equal to your number? "
answer$ = input
print answer$
ans$ = substr answer$ 1 1
until ans$ = "e"
if ans$ = "l"
min = guess + 1
elif ans$ = "h"
max = guess - 1
else
print "Sorry, i didn't understand your answer."
.
.
print "Goodbye."
</syntaxhighlight>
 
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
<syntaxhighlight lang="elixir">defmodule Game do
def guess(a..b) do
x = Enum.random(a..b)
guess(x, a..b, div(a+b, 2))
end
defp guess(x, a.._b, guess) when x < guess do
IO.puts "Is it #{guess}? Too High."
guess(x, a..guess-1, div(a+guess, 2))
end
defp guess(x, _a..b, guess) when x > guess do
IO.puts "Is it #{guess}? Too Low."
guess(x, guess+1..b, div(guess+b+1, 2))
end
defp guess(x, _, _) do
IO.puts "Is it #{x}?"
IO.puts " So the number is: #{x}"
end
end
Game.guess(1..100)</syntaxhighlight>
 
{{out|sample}}
<pre>
Is it 50? Too High.
Is it 25? Too High.
Is it 13? Too High.
Is it 7? Too Low.
Is it 10?
So the number is: 10
</pre>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">% Implemented by Arjun Sunel
-module(guess_game).
-export([main/0]).
 
main() ->
L = 1 , % Lower Limit
U = 100, % Upper Limit
io:fwrite("Player 1 : Guess my number between ~p and ", [L]),
io:fwrite("and ~p until you get it right.\n", [U]),
N = random:uniform(100),
guess(L,U,N).
 
guess(L,U,N) ->
K = (L+U) div 2,
io:format("Player 2 : Number guessed : ~p~n",[K]),
if
K=:=N ->
io:format("Well guessed!! by Player 2\n");
true ->
if
K > N ->
io:format("Player 1 : Your guess is too high!\n"),
guess(L,K,N);
true ->
io:format("Player 1 : Your guess is too low!\n"),
guess(K,U,N)
end
end.</syntaxhighlight>
{{out}}
<pre>Player 1 : Guess my number between 1 and and 100 until you get it right.
Player 2 : Number guessed : 50
Player 1 : Your guess is too high!
Player 2 : Number guessed : 25
Player 1 : Your guess is too high!
Player 2 : Number guessed : 13
Player 1 : Your guess is too high!
Player 2 : Number guessed : 7
Player 1 : Your guess is too low!
Player 2 : Number guessed : 10
Well guessed!! by Player 2
ok</pre>
 
=={{header|Euphoria}}==
{{trans|PureBasic}}
<langsyntaxhighlight lang="euphoria">include get.e
include wildcard.e
 
Line 403 ⟶ 1,267:
puts(1,"I do not understand that...\n")
end if
end while</langsyntaxhighlight>
 
=={{header|Factor}}==
This solution uses the <code>search</code> combinator. It performs a binary search on a sequence by placing the "guess" on top of the data stack and expecting an ordering specifier in return.
<syntaxhighlight lang="factor">USING: binary-search formatting io kernel math.ranges words ;
 
: instruct ( -- )
"Think of a number between 1 and 100." print
"Score my guess with +lt+ +gt+ or +eq+." print nl ;
 
: score ( n -- <=> )
"My guess is %d. " printf readln "math.order" lookup-word ;
 
: play-game ( -- n )
100 [1,b] [ score ] search nip nl ;
 
: gloat ( n -- )
"I did it. Your number was %d!\n" printf ;
 
instruct play-game gloat</syntaxhighlight>
{{out}}
<pre>
Think of a number between 1 and 100.
Score my guess with +lt+ +gt+ or +eq+.
 
My guess is 51. +lt+
My guess is 26. +gt+
My guess is 38. +lt+
My guess is 32. +gt+
My guess is 35. +lt+
My guess is 33. +eq+
 
I did it. Your number was 33!
</pre>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 444 ⟶ 1,341:
}
}
</syntaxhighlight>
</lang>
 
Example:
Line 477 ⟶ 1,374:
I got it correct - thankyou!
</pre>
 
=={{header|FOCAL}}==
<syntaxhighlight lang="focal">01.10 A "LOWER LIMIT",L
01.15 A "UPPER LIMIT",H
01.20 S T=0
01.25 I (L-H)1.3;T "INVALID INPUT"!;Q
01.30 S G=FITR((H-L)/2+L)
01.35 T "MY GUESS IS",%4,G,!
01.37 S T=T+1
01.40 A "TOO (L)OW, TOO (H)IGH, OR (C)ORRECT",R
01.45 I (R-0L)1.5,1.65,1.5
01.50 I (R-0H)1.55,1.7,1.55
01.55 I (R-0C)1.6,1.75,1.6
01.60 T "INVALID INPUT"!;G 1.3
01.65 S L=G;G 1.3
01.70 S H=G;G 1.3
01.75 T "ATTEMPTS",T,!
01.80 Q</syntaxhighlight>
{{out}}
<pre>LOWER LIMIT:1
UPPER LIMIT:100
MY GUESS IS= 50
TOO (L)OW, TOO (H)IGH, OR (C)ORRECT:L
MY GUESS IS= 75
TOO (L)OW, TOO (H)IGH, OR (C)ORRECT:L
MY GUESS IS= 87
TOO (L)OW, TOO (H)IGH, OR (C)ORRECT:H
MY GUESS IS= 81
TOO (L)OW, TOO (H)IGH, OR (C)ORRECT:L
MY GUESS IS= 84
TOO (L)OW, TOO (H)IGH, OR (C)ORRECT:L
MY GUESS IS= 85
TOO (L)OW, TOO (H)IGH, OR (C)ORRECT:C
ATTEMPTS= 6</pre>
 
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<langsyntaxhighlight lang="fortran">program Guess_a_number_Player
implicit none
Line 517 ⟶ 1,448:
end select
end do
end program</langsyntaxhighlight>
Output
<pre>Think of a number between 1 and 100 and I will try to guess it.
Line 531 ⟶ 1,462:
My guess is: 57 Score(h, l or c)?: c
I solved it!</pre>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim hle As String
Dim lowest As Integer = 1
Dim highest As Integer = 20
Dim guess As Integer = 10
Print "Please choose a number between 1 and 20 but don't tell me what it is yet"
Print
Do
Print "My guess is"; guess
Do
Input "Is this higher/lower or equal to your chosen number h/l/e : "; hle
hle = LCase(hle)
If hle = "l" AndAlso guess = highest Then
Print "It can't be more than"; highest; ", try again"
hle = "i" '' invalid
ElseIf hle = "h" AndAlso guess = lowest Then
Print "It can't be less than"; lowest; ", try again"
hle = "i"
End If
Loop Until hle = "h" OrElse hle = "l" OrElse hle = "e"
If hle = "e" Then
Print "Good, thanks for playing the gaame with me!"
Exit Do
ElseIf hle = "h" Then
If highest > guess - 1 Then highest = guess - 1
Else
If lowest < guess + 1 Then lowest = guess + 1
End If
guess = (lowest + highest)\2
Loop
End</syntaxhighlight>
 
Sample input/output
{{out}}
<pre>
Please choose a number between 1 and 20 but don't tell me what it is yet
 
My guess is 10
Is this higher/lower or equal to your chosen number h/l/e : ? l
My guess is 15
Is this higher/lower or equal to your chosen number h/l/e : ? h
My guess is 12
Is this higher/lower or equal to your chosen number h/l/e : ? h
My guess is 11
Is this higher/lower or equal to your chosen number h/l/e : ? e
Good, thanks for playing the gaame with me!
</pre>
 
=={{header|Go}}==
Go's binary search function (<code>sort.Search()</code>) is general enough to be able to do this type of task, as mentioned in the documentation for the function itself.[http://golang.org/pkg/sort/#Search]
<langsyntaxhighlight lang="go">package main
 
import (
Line 554 ⟶ 1,536:
})
fmt.Printf("Your number is %d.\n", lower+answer)
}</langsyntaxhighlight>
 
Manual solution:
<langsyntaxhighlight lang="go">package main
 
import (
Line 594 ⟶ 1,576:
}
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
 
Explicit version with arbitrary range:
<syntaxhighlight lang="haskell">
main :: IO ()
main = do
putStrLn "Please enter the range:"
putStr "From: "
from <- getLine
putStr "To: "
to <- getLine
case (from, to) of
(_) | [(from', "")] <- reads from
, [(to' , "")] <- reads to
, from' < to' -> loop from' to'
(_) -> putStrLn "Invalid input." >> main
 
loop :: Integer -> Integer -> IO ()
loop from to = do
let guess = (to + from) `div` 2
putStrLn $ "Is it " ++ show guess ++ "? ((l)ower, (c)orrect, (h)igher)"
answer <- getLine
case answer of
"c" -> putStrLn "Awesome!"
"l" -> loop from guess
"h" -> loop guess to
(_) -> putStrLn "Invalid answer." >> loop from to
</syntaxhighlight>
 
Short version with set limits:
<syntaxhighlight lang="haskell">
main = f 0 100
where f x y = let g = div (x + y) 2 in
putStrLn (show g ++ "? (l,h,c)") >>
getLine >>= \a -> case a of
"l" -> f x g
"h" -> f g y
"c" -> putStrLn "Yay!"
</syntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
{{trans|Fantom}}
 
<syntaxhighlight lang="icon">
<lang Icon>
procedure main ()
lower_limit := 1
Line 629 ⟶ 1,651:
}
end
</syntaxhighlight>
</lang>
 
=={{header|IS-BASIC}}==
<syntaxhighlight lang="is-basic">100 PROGRAM "GuessIt.bas"
110 LET N=100
120 TEXT 80
130 PRINT "Choose a number between 1 and;" N:PRINT "I will start guess the number."
140 LET BL=1:LET UL=100:LET NR=0
150 DO
160 LET GUESS=INT((BL+UL)/2):LET NR=NR+1
170 SET #102:INK 3:PRINT :PRINT "My";NR;". guess: ";GUESS:SET #102:INK 1
180 LET ANSWER=QUESTION
190 SELECT CASE ANSWER
200 CASE 1
210 LET UL=GUESS-1
220 CASE 2
230 LET BL=GUESS+1
240 CASE ELSE
250 END SELECT
260 IF BL>UL THEN PRINT "You are cheating!":LET ANSWER=9
270 LOOP UNTIL ANSWER=0 OR ANSWER=9
280 PRINT "So the number is:" GUESS
290 DEF QUESTION
300 PRINT "Your number: 1 - Is lower?; 2 - Is higher?; 0 - Is equal?"
310 DO
320 LET K$=INKEY$
330 LOOP UNTIL K$>="0" AND K$<="3"
340 LET QUESTION=VAL(K$)
350 END DEF</syntaxhighlight>
 
=={{header|J}}==
 
<langsyntaxhighlight lang="j">require 'misc'
guess=:3 :0
'lo hi'=.y
Line 647 ⟶ 1,697:
end.
end.
)</langsyntaxhighlight>
 
Example session:
 
<syntaxhighlight lang="text"> guess 1 100
guessing a number between 1 and 100
is it 86? hi
Line 670 ⟶ 1,720:
guessing a number between 49 and 50
is it 49? lo
50</langsyntaxhighlight>
 
This could be made more efficient by replacing <code>guess=.lo+?hi-lo</code> with <code>guess=.<.-:lo+hi</code>. (The above example would have finished on the first guess, but the range 1..100 would never take more than 6 guesses -- the remaining answers would be determined after six guesses.)
Line 677 ⟶ 1,727:
A clever solution that uses the built-in binary search functions with a virtual list.
{{trans|Go}}
<langsyntaxhighlight lang="java5">import java.util.AbstractList;
import java.util.Collections;
import java.util.Scanner;
Line 712 ⟶ 1,762:
System.out.printf("Your number is %d.\n", result);
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
=== Spidermonkey version ===
 
A boring solution that does nothing clever or inscrutable.
 
Well, it does use recursion for the guessing function, but that's OK because the depth is bounded by LOG<sub>2</sub> of the range. That's not true if the user changes his number, but then he gets what he deserves.
 
<syntaxhighlight lang="javascript">#!/usr/bin/env js
 
var DONE = RIGHT = 0, HIGH = 1, LOW = -1;
 
function main() {
showInstructions();
while (guess(1, 100) !== DONE);
}
 
function guess(low, high) {
if (low > high) {
print("I can't guess it. Perhaps you changed your number.");
return DONE;
}
var g = Math.floor((low + high) / 2);
var result = getResult(g);
switch (result) {
case RIGHT:
return DONE;
case LOW:
return guess(g + 1, high);
case HIGH:
return guess(low, g - 1);
}
}
 
function getResult(g) {
while(true) {
putstr('Is it ' + g + '? ');
var ans = readline().toUpperCase().replace(/^\s+/, '') + ' ';
switch (ans[0]) {
case 'R':
print('I got it! Thanks for the game.');
return RIGHT;
case 'L':
return LOW;
case 'H':
return HIGH;
default:
print('Please tell me if I am "high", "low" or "right".');
}
}
}
 
function showInstructions() {
print('Think of a number between 1 and 100 and I will try to guess it.');
print('After I guess, type "low", "high" or "right", and then press enter.');
putstr("When you've thought of a number press enter.");
readline();
}
 
main();
</syntaxhighlight>
 
An example session:
Think of a number between 1 and 100 and I will try to guess it.
After I guess, type "low", "high" or "right", and then press enter.
When you've thought of a number press enter.
Is it 50? high
Is it 25? high
Is it 12? low
Is it 18? high
Is it 15? high
Is it 13? right
I got it! Thanks for the game.
 
Another example session:
Think of a number between 1 and 100 and I will try to guess it.
After I guess, type "low", "high" or "right", and then press enter.
When you've thought of a number press enter.
Is it 50? n
Please tell me if I am "high", "low" or "right".
Is it 50? h
Is it 25? h
Is it 12? h
Is it 6? h
Is it 3? h
Is it 1? h
I can't guess it. Perhaps you changed your number.
 
=={{header|jq}}==
''Adapted from [[#Wren|Wren]]''
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq'''
<syntaxhighlight lang=jq>
# Pick an integer from $lowest through $highest ...
def play($lowest; $highest):
# Helper function for guessing
def prompt:
.guess = (((.lowest + .highest)/2)|floor)
| .emit += "\nMy guess is \(.guess)." +
"\nIs this higher/lower than or equal to your chosen number? h/l/e : " ;
"Please choose a number from \($lowest) to \($highest) inclusive and then answer the questions.",
( {$highest, $lowest}
| prompt
| .emit,
( label $out
| foreach inputs as $in (.;
.emit = null
| .hle = ($in|ascii_downcase)
| if .hle == "l" and .guess == .highest
then .emit = "It can't be more than \(highest), try again."
elif .hle == "h" and .guess == .lowest
then .emit = "It can't be less than \(.lowest), try again."
elif .hle == "e"
then .emit = "Good, thanks for playing the game with me!"
| .quit = true
elif .hle == "h"
then if (.highest > .guess - 1) then .highest = .guess - 1
else .
end
elif .hle == "l"
then if (.lowest < .guess + 1) then .lowest = .guess + 1
else .
end
else .emit = "Please try again.\n"
end
| if .quit then ., break $out else prompt end ;
.emit
) ) ) ;
 
def play: play(1;20);
 
play
</syntaxhighlight>
'''Invocation:''' jq -nRr -f guess-the-number-with-feedback-player.jq
{{output}}
<pre>
Please choose a number from 1 to 20 inclusive and then answer the questions.
 
My guess is 10.
Is this higher/lower than or equal to your chosen number? h/l/e :
h
 
My guess is 5.
Is this higher/lower than or equal to your chosen number? h/l/e :
?
Please try again.
 
My guess is 5.
Is this higher/lower than or equal to your chosen number? h/l/e :
0
Please try again.
 
My guess is 5.
Is this higher/lower than or equal to your chosen number? h/l/e :
h
 
My guess is 2.
Is this higher/lower than or equal to your chosen number? h/l/e :
e
Good, thanks for playing the game with me!
$
</pre>
 
=={{header|Julia}}==
 
This version uses the expression <math>\left\lceil-\log\left(\frac{1}{\mathrm{upper} - \mathrm{lower}}\right) / \log(2)\right\rceil</math> to calculate the maximum number of guesses it will need.
 
<syntaxhighlight lang="julia">print("Enter an upper bound: ")
lower = 0
input = readline()
upper = parse(Int, input)
 
if upper < 1
throw(DomainError)
end
 
attempts = 1
print("Think of a number, ", lower, "--", upper, ", then press ENTER.")
readline()
const maxattempts = round(Int, ceil(-log(1 / (upper - lower)) / log(2)))
println("I will need at most ", maxattempts, " attempts ",
"(⌈-log(1 / (", upper, " - ", lower, ")) / log(2)⌉ = ",
maxattempts, ").\n")
previous = -1
guess = -1
 
while true
previous = guess
guess = lower + round(Int, (upper - lower) / 2, RoundNearestTiesUp)
 
if guess == previous || attempts > maxattempts
println("\nThis is impossible; did you forget your number?")
exit()
end
 
print("I guess ", guess, ".\n[l]ower, [h]igher, or [c]orrect? ")
input = chomp(readline())
while input ∉ ["c", "l", "h"]
print("Please enter one of \"c\", \"l\", or \"h\". ")
input = chomp(readline())
end
 
if input == "l"
upper = guess
elseif input == "h"
lower = guess
else
break
end
 
attempts += 1
end
 
println("\nI win after ", attempts, attempts == 1 ? " attempt." : " attempts.")</syntaxhighlight>
 
=={{header|Kotlin}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="scala">// version 1.0.5-2
 
fun main(args: Array<String>) {
var hle: Char
var lowest = 1
var highest = 20
var guess = 10
println("Please choose a number between 1 and 20 but don't tell me what it is yet\n")
 
while (true) {
println("My guess is $guess")
 
do {
print("Is this higher/lower than or equal to your chosen number h/l/e : ")
hle = readLine()!!.first().toLowerCase()
if (hle == 'l' && guess == highest) {
println("It can't be more than $highest, try again")
hle = 'i' // signifies invalid
}
else if (hle == 'h' && guess == lowest) {
println("It can't be less than $lowest, try again")
hle = 'i'
}
}
while (hle !in "hle")
when (hle) {
'e' -> { println("Good, thanks for playing the game with me!") ; return }
'h' -> if (highest > guess - 1) highest = guess - 1
'l' -> if (lowest < guess + 1) lowest = guess + 1
}
 
guess = (lowest + highest) / 2
}
}</syntaxhighlight>
Sample input/output:
{{out}}
<pre>
 
<Please choose a number between 1 and 20 but don't tell me what it is yet
 
My guess is 10
Is this higher/lower or equal to your chosen number h/l/e : h
My guess is 5
Is this higher/lower or equal to your chosen number h/l/e : l
My guess is 7
Is this higher/lower or equal to your chosen number h/l/e : l
My guess is 8
Is this higher/lower or equal to your chosen number h/l/e : e
Good, thanks for playing the game with me!
/pre>
 
=={{header|Lasso}}==
<syntaxhighlight lang="lasso">#!/usr/bin/lasso9
 
local(
mini=0,
maxi=100,
status = false,
count = 0,
response,
guess
)
 
stdoutnl('Think of a number between ' + #mini + ' and ' + #maxi + '
Each time I guess indicate if I was to high (H), to low (L) or just right (R).')
 
 
while(not #status) => {
 
if(not(#mini <= #maxi)) => {
 
stdout('I think you are trying to cheat me. I will not play anymore.')
#status = true
 
else
 
#guess = ((#maxi - #mini) /2 ) + #mini
 
stdout('You are thinking on ' + #guess + ' ')
#response = null
 
// the following bits wait until the terminal gives you back a line of input
while(not #response or #response -> size == 0) => {
#response = file_stdin -> readSomeBytes(1024, 1000)
}
#response -> replace(bytes('\n'), bytes(''))
 
match(string(#response)) => {
case('L')
#mini = #guess + 1
#count++
case('H')
#maxi = #guess - 1
#count++
case('R')
stdout('Am I smart or smart! I guessed it in ' + #count ' tries!')
#status = true
case()
stdout('Are you having issues reading instructions? ')
}
}
}</syntaxhighlight>
 
Examples:
<pre>Think of a number between 0 and 100
Each time I guess indicate if I was to high (H), to low (L) or just right (R).
You are thinking on 50 l
You are thinking on 75 l
You are thinking on 88 h
You are thinking on 81 r
Am I smart or smart! I guessed it in 4 tries!
</pre>
<pre>Think of a number between 0 and 100
Each time I guess indicate if I was to high (H), to low (L) or just right (R).
You are thinking on 50 k
Are you having issues reading instructions? You are thinking on 50 tr
Are you having issues reading instructions? You are thinking on 50 l
You are thinking on 75 l
You are thinking on 88 l
You are thinking on 94 l
You are thinking on 97 l
You are thinking on 99 h
You are thinking on 98 r
Am I smart or smart! I guessed it in 6 tries!
</pre>
<pre>You are thinking on 50 h
You are thinking on 24 h
You are thinking on 11 l
You are thinking on 17 l
You are thinking on 20 l
You are thinking on 22 l
You are thinking on 23 l
I think you are trying to cheat me. I will not play anymore.
</pre>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">mini=0
maxi=100
 
print "Think of a number between ";mini;" and ";maxi
print "Each time I guess a number you must state whether my"
print "guess was too high, too low, or equal to your number."
print
 
while response$<>"="
if not(mini<=maxi) then
print "Error"
exit while
end if
guess=int((maxi-mini)/2)+mini
print "My guess is ";guess;". Type L for low, H for high, = for correct."
input response$
response$=upper$(response$)
select case response$
case "L"
mini=guess+1
case "H"
maxi=guess-1
case "="
print guess;" is correct."
exit while
case else
print "Your response was not helpful."
end select
wend
print "Thanks for playing." </syntaxhighlight>
 
=={{header|Lua}}==
<syntaxhighlight lang="text">function wait(waittime)--wait function is used so that app will not quit immediately
local timer = os.time()
repeat until os.time() == timer + waittime
end
 
 
upperBound = 100
lowerBound = 0
print("Think of an integer between 1 to 100.")
print("I will try to guess it.")
while true do
upper1 = upperBound+1
upper2 = upperBound-1
if upperBound == lowerBound or upper1 == lowerBound or upper2 == lowerBound or lowerBound > upperBound then--make sure player is not cheating
io.write("You're cheating! I'm not playing anymore. Goodbye.")
wait(3)
break
else
Guess = math.floor((upperBound + lowerBound)/2)--guessing mechanism
print("My guess is: "..Guess..". Is it too high, too low, or correct? (h/l/c)")
input = io.read()
 
if input == "h" then --higher
upperBound = Guess
elseif input == "l" then --lower
lowerBound = Guess
elseif input == "c" then --correct
io.write("So I win? Thanks for playing with me.")
wait(3)
break
else
print("Invalid input. Please try again. ")
end
end
end
</syntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="text">guessnumber[min0_, max0_] :=
DynamicModule[{min = min0, max = max0, guess, correct = False},
guess[] := Round@Mean@{min, max};
Dynamic@If[correct, Row@{"Your number is ", guess[], "."},
Column@{Row@{"I guess ", guess[], "."},
Row@{Button["too high", max = guess[]],
Button["too low", min = guess[]],
Button["correct", correct = True]}}]];
guessnumber[1, 100]</syntaxhighlight>
 
=={{header|MATLAB}}==
<syntaxhighlight lang="matlab">function GuessNumberFeedbackPlayer
lowVal = input('Lower limit: ');
highVal = input('Upper limit: ');
fprintf('Think of your number. Press Enter when ready.\n')
pause
nGuesses = 1;
done = false;
while ~done
guess = floor(0.5*(lowVal+highVal));
score = input(sprintf( ...
'Is %d too high (H), too low (L), or equal (E)? ', guess), 's');
if any(strcmpi(score, {'h' 'hi' 'high' 'too high' '+'}))
highVal = guess-1;
nGuesses = nGuesses+1;
elseif any(strcmpi(score, {'l' 'lo' 'low' 'too low' '-'}))
lowVal = guess+1;
nGuesses = nGuesses+1;
elseif any(strcmpi(score, {'e' 'eq' 'equal' 'right' 'correct' '='}))
fprintf('Yay! I win in %d guesses.\n', nGuesses)
done = true;
else
fprintf('Unclear response. Try again.\n')
end
if highVal < lowVal
fprintf('Incorrect scoring. No further guesses.\n')
done = true;
end
end
end</syntaxhighlight>
{{out}}
<pre>Lower limit: 0
Upper limit: 50
Think of your number. Press Enter when ready.
Is 25 too high (H), too low (L), or equal (E)? L
Is 38 too high (H), too low (L), or equal (E)? H
Is 31 too high (H), too low (L), or equal (E)? H
Is 28 too high (H), too low (L), or equal (E)? L
Is 29 too high (H), too low (L), or equal (E)? E
Yay! I win in 5 guesses.</pre>
<pre>Lower limit: 0
Upper limit: 10
Think of your number. Press Enter when ready.
Is 5 too high (H), too low (L), or equal (E)? L
Is 8 too high (H), too low (L), or equal (E)? hello
Unclear response. Try again.
Is 8 too high (H), too low (L), or equal (E)? H
Is 6 too high (H), too low (L), or equal (E)? L
Is 7 too high (H), too low (L), or equal (E)? H
Incorrect scoring. No further guesses.</pre>
 
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">inclusiveRange = [1,100]
lowRange = inclusiveRange.x
maxRange = inclusiveRange.y
guesses = 1
inf = "Think of a number between % and % and I will try to guess it.\n" +\
"Type -1 if the guess is less than your number,\n"+\
"0 if the guess is correct, " +\
"or 1 if it's too high.\nPress esc to exit.\n"
clearListener()
format inf (int lowRange) (int maxRange)
while not keyboard.escpressed do
(
local chosen = ((lowRange + maxRange) / 2) as integer
if lowRange == maxRange do format "\nHaving fun?"
format "\nI choose %.\n" chosen
local theAnswer = getKBValue prompt:"Answer? "
case theAnswer of
(
(-1): (lowRange = chosen; guesses += 1)
(0): (format "\nYay. I guessed your number after % %.\n" \
guesses (if guesses == 1 then "try" else "tries")
exit with OK)
(1): (maxRange = chosen; guesses += 1)
default: (format "\nI don't understand your input.")
)
)</syntaxhighlight>
{{out}}
<syntaxhighlight lang="maxscript">
OK
Think of a number between 1 and 100 and I will try to guess it.
Type -1 if the guess is less than your number,
0 if the guess is correct, or 1 if it's too high.
Press esc to exit.
OK
 
I choose 50.
Answer? -1
I choose 75.
Answer? -1
I choose 87.
Answer? 1
I choose 81.
Answer? -1
I choose 84.
Answer? -1
I choose 85.
Answer? 0
Yay. I guessed your number after 6 tries.
OK
</syntaxhighlight>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE raden;
 
IMPORT InOut;
Line 750 ⟶ 2,340:
InOut.WriteString ("Thanks for letting me play with you.");
InOut.WriteLn
END raden.</langsyntaxhighlight>Example:<pre>raden
Choose a number between 0 and 1000.
 
Line 765 ⟶ 2,355:
So the number is 600
Thanks for letting me play with you.</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">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."</syntaxhighlight>
Output:
<pre>Think of a number between 1 and 10 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 =
Guess 1 is: 5. The score for which is (h,l,=): l
Guess 2 is: 8. The score for which is (h,l,=): h
Guess 3 is: 6. The score for which is (h,l,=): l
Guess 4 is: 7. The score for which is (h,l,=): =
Ye-Haw!!
Thanks for keeping score.</pre>
 
=={{header|NS-HUBASIC}}==
<syntaxhighlight lang="ns-hubasic">10 PRINT "THINK OF A NUMBER BETWEEN 1 AND";" 9, AND I'LL TRY TO GUESS IT."
20 ISVALID=0
30 GUESS=5
40 PRINT "I GUESS"GUESS"."
50 INPUT "IS THAT HIGHER THAN, LOWER THAN OR EQUAL TO YOUR NUMBER? ",ANSWER$
60 IF ANSWER$="LOWER THAN" THEN ISVALID=1:IF GUESS<9 THEN GUESS=GUESS+1
70 IF ANSWER$="HIGHER THAN" THEN ISVALID=1:IF GUESS>1 THEN GUESS=GUESS-1
80 IF ANSWER$="EQUAL TO" THEN PRINT "OH YES! I GUESSED CORRECTLY!":END
90 IF ISVALID=0 THEN PRINT "SORRY";", BUT THAT ANSWER IS INVALID."
100 GOTO 40</syntaxhighlight>
 
=={{header|Objective-C}}==
A clever solution that uses the built-in binary search functions with a virtual list.
{{trans|GoJava}}
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface GuessNumberFakeArray : NSArray {
int lower, upper;
}
- (instancetype)initWithLower:(int)l andUpper:(int)u;
@end
 
@implementation GuessNumberFakeArray
- (instancetype)initWithLower:(int)l andUpper:(int)u {
- (NSUInteger)count { return NSUIntegerMax; }
if ((self = [super init])) {
lower = l;
upper = u;
}
return self;
}
- (NSUInteger)count { return upper-lower; }
- (id)objectAtIndex:(NSUInteger)i {
printf("My guess is: %lud. Is it too high, too low, or correct? (H/L/C) ", lower + (int)i);
char input[2] = " ";
scanf("%1s", input);
switch (tolower(input[0])) {
case 'l':
return [NSNumber numberWithInt:@-1];
case 'h':
return [NSNumber numberWithInt:@1];
case 'c':
return [NSNumber numberWithInt:@0];
}
return nil;
Line 796 ⟶ 2,449:
 
int main(int argc, const char *argv[]) {
@autoreleasepool {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
printf("Instructions:\n"
"Think of integer number from %d (inclusive) to %d (exclusive) and\n"
"I will guess it. After each guess, you respond with L, H, or C depending\n"
"on if my guess was too low, too high, or correct.\n",
LOWER, UPPER);
GuessNumberFakeArray *fakeArray NSUInteger result = [[[GuessNumberFakeArray newalloc] initWithLower:LOWER andUpper:UPPER];
NSUInteger result = [fakeArray indexOfObject:[NSNumber numberWithInt: 0]
inSortedRange:NSMakeRange(LOWER0, UPPER - LOWER)
options:0
usingComparator:^(id x, id y){ return [x compare: y]; }];
if (result == NSNotFound)
[fakeArray release];
NSLog printf(@"Your numberThat is %luimpossible.\n", result);
else
printf("Your number is %d.", LOWER + (int)result);
}
[pool release];
return 0;
}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
 
<langsyntaxhighlight lang="parigp">
guessnumber2(b)={
my(c=0,d=b,a=0);
Line 840 ⟶ 2,495:
);
}
</syntaxhighlight>
</lang>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program GuessIt(input, output);
 
var
Line 874 ⟶ 2,529:
writeln ('So the number is: ', guess:4);
writeln ('It was nice to play with you.');
end.</langsyntaxhighlight>
Output:
<pre>:> ./GuessTheNumberPlayerFeedback
Line 893 ⟶ 2,548:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
my $min = 1;
my $max = 99;
my $guess = int(rand $max) + $min;
 
my $tries = 0;
print "=>> Think of a number between $min and $max and I'll guess it!\n
Press <ENTER> when are you ready... ";
 
<STDIN>;
 
{
my $guess = int(rand $max) + $min;
do {
my $tries = 0;
 
$tries++;
sub question {
print "\n=>> My guess is: $guess Is your number higher, lower, or equal? (h/l/e)\n> ";
my $guess = shift();
print "\n=>> My guess is: $guess. Is your number higher, lower or equal? (h/l/e)\n> ";
++$tries;
}
 
my $score = <STDIN>;
question $guess;
 
while (1) {
my $score = <STDIN>;
 
if (lc substr($score, 0, 1) eq 'h') {
$min = $guess + 1;
}
elsif (lc substr($score, 0, 1) eq 'l') {
$max = $guess;
}
elsif (lc substr($score, 0, 1) eq 'e') {
print "\nI knew it! It took me only $tries tries.\n";
last;
}
else {
print "error: invalid score\n";
}
 
print "\nI gave up...\n" and last if ($max <= $min;) {
print "\nI give up...\n" and last;
} elsif ($score =~ /^h/i) {
$min = $guess + 1;
} elsif ($score =~ /^l/i) {
$max = $guess;
} elsif ($score =~ /^e/i) {
print "\nI knew it! It took me only $tries tries.\n" and last;
} else {
print "error: invalid score\n";
}
 
$guess = int(($max + $min) / 2);
 
question} $guesswhile(1);
}</langsyntaxhighlight>
<pre>=>> Think of a number between 1 and 99 and I'll guess it!
 
Line 958 ⟶ 2,605:
I knew it! It took me only 5 tries.</pre>
 
=={{header|Perl 6Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
 
<span style="color: #000080;font-style:italic;">--
<lang perl6>multi sub MAIN() { MAIN(0, 100) }
-- demo\rosetta\Guess_the_number2.exw
multi sub MAIN($min is copy where ($min >= 0), $max is copy where ($max > $min)) {
--</span>
say "Think of a number between $min and $max and I'll guess it!";
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> <span style="color: #000080;font-style:italic;">-- (spacing not (yet) great...)</span>
while $min <= $max {
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
my $guess = (($max + $min)/2).floor;
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">lbl</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">guess</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">toohigh</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">too_low</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">correct</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">newgame</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dlg</span>
given lc prompt "My guess is $guess. Is your number higher, lower or equal? " {
when /^e/ { say "I knew it!"; exit }
<span style="color: #004080;">integer</span> <span style="color: #000000;">Min</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">Max</span><span style="color: #0000FF;">=</span><span style="color: #000000;">100</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">Guess</span>
when /^h/ { $min = $guess + 1 }
<span style="color: #008080;">constant</span> <span style="color: #000000;">LTHINK</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Think of a number between %d and %d."</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">Min</span><span style="color: #0000FF;">,</span><span style="color: #000000;">Max</span><span style="color: #0000FF;">})</span>
when /^l/ { $max = $guess }
default { say "WHAT!?!?!" }
<span style="color: #008080;">procedure</span> <span style="color: #000000;">set_active</span><span style="color: #0000FF;">(</span><span style="color: #004080;">bool</span> <span style="color: #000000;">bActive</span><span style="color: #0000FF;">)</span>
}
<span style="color: #7060A8;">IupSetInt</span><span style="color: #0000FF;">({</span><span style="color: #000000;">toohigh</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">too_low</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">correct</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"ACTIVE"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bActive</span><span style="color: #0000FF;">)</span>
}
<span style="color: #7060A8;">IupSetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">newgame</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ACTIVE"</span><span style="color: #0000FF;">,</span><span style="color: #008080;">not</span> <span style="color: #000000;">bActive</span><span style="color: #0000FF;">)</span>
say "How can your number be both higher and lower than $max?!?!?";
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
}</lang>
 
<span style="color: #008080;">procedure</span> <span style="color: #000000;">set_guess</span><span style="color: #0000FF;">()</span>
You may execute this program with '<tt>perl6 program</tt>' or with '<tt>perl6 program min max</tt>'. Perl 6 creates a usage for us if we don't give the right parameters. It also parses the parameters for us and provides them via <tt>$min</tt> and <tt>$max</tt>. We use multi-subs to provide two MAIN subroutines so the user is able to choose between min and max parameters and no parameters at all, in which case min is set to 0 and max to 100.
<span style="color: #000000;">Guess</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">((</span><span style="color: #000000;">Max</span><span style="color: #0000FF;">+</span><span style="color: #000000;">Min</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">title</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"My guess is %d, is this too high, too low, or correct?"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">Guess</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">Max</span><span style="color: #0000FF;"><</span><span style="color: #000000;">Min</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">set_active</span><span style="color: #0000FF;">(</span><span style="color: #004600;">false</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">title</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"I think something is strange here..."</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">IupSetStrAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">title</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupRefresh</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">click_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000000;">ih</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">switch</span> <span style="color: #7060A8;">substitute</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">IupGetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ih</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"Too "</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">)[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">case</span> <span style="color: #008000;">'H'</span><span style="color: #0000FF;">:</span> <span style="color: #000000;">Max</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">Guess</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #000000;">set_guess</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">case</span> <span style="color: #008000;">'L'</span><span style="color: #0000FF;">:</span> <span style="color: #000000;">Min</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">Guess</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #000000;">set_guess</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">case</span> <span style="color: #008000;">'C'</span><span style="color: #0000FF;">:</span> <span style="color: #7060A8;">IupSetStrAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"I did it!"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">set_active</span><span style="color: #0000FF;">(</span><span style="color: #004600;">false</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">case</span> <span style="color: #008000;">'N'</span><span style="color: #0000FF;">:</span> <span style="color: #000000;">Min</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span> <span style="color: #000000;">Max</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">100</span> <span style="color: #000000;">set_guess</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">set_active</span><span style="color: #0000FF;">(</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">switch</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">lbl</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #000000;">LTHINK</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">guess</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">""</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">toohigh</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupButton</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Too High"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"click_cb"</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">too_low</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupButton</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Too Low"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"click_cb"</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">correct</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupButton</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Correct"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"click_cb"</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">newgame</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupButton</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"New Game"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"click_cb"</span><span style="color: #0000FF;">),</span> <span style="color: #008000;">"ACTIVE=NO"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">IupVbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">lbl</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">guess</span><span style="color: #0000FF;">,</span>
<span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">toohigh</span><span style="color: #0000FF;">,</span><span style="color: #000000;">too_low</span><span style="color: #0000FF;">,</span><span style="color: #000000;">correct</span><span style="color: #0000FF;">,</span><span style="color: #000000;">newgame</span><span style="color: #0000FF;">},</span>
<span style="color: #008000;">"GAP=10"</span><span style="color: #0000FF;">)},</span>
<span style="color: #008000;">`NMARGIN=15x15,GAP=10`</span><span style="color: #0000FF;">),</span>
<span style="color: #008000;">`MINSIZE=300x100,TITLE="Guess the number2"`</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">set_guess</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
 
=={{header|PicoLisp}}==
{{trans|PureBasic}}
<langsyntaxhighlight PicoLisplang="picolisp">(de guessTheNumber (Min Max)
(prinl "Think of a number between " Min " and " Max ".")
(prinl "On every guess of mine you should state whether my guess was")
Line 997 ⟶ 2,690:
("L" (setq Min Guess))
("=" (nil (prinl "I did it!")))
(T (prinl "I do not understand that...")) ) ) ) ) )</langsyntaxhighlight>
Output:
<pre>: (guessTheNumber 1 99)
Line 1,009 ⟶ 2,702:
My guess is 22,is this correct? =
I did it!</pre>
 
=={{header|Prolog}}==
<syntaxhighlight lang="prolog">min(1). max(10).
 
pick_number(Min, Max) :-
min(Min), max(Max),
format('Pick a number between ~d and ~d, and I will guess it...~nReady? (Enter anything when ready):', [Min, Max]),
read(_).
 
guess_number(Min, Max) :-
Guess is (Min + Max) // 2,
format('I guess ~d...~nAm I correct (c), too low (l), or too high (h)? ', [Guess]),
repeat,
read(Score),
( Score = l -> NewMin is Guess + 1, guess_number(NewMin, Max)
; Score = h -> NewMax is Guess - 1, guess_number(Min, NewMax)
; Score = c -> writeln('I am correct!')
; writeln('Invalid input'),
false
).
 
play :-
pick_number(Min, Max),
guess_number(Min, Max).</syntaxhighlight>
 
Example:
 
<syntaxhighlight lang="prolog">?- play.
Pick a number between 1 and 10, and I will guess it...
Ready? (Enter anything when ready):y.
I guess 5...
Am I correct (c), too low (l), or too high (h)? h.
I guess 2...
Am I correct (c), too low (l), or too high (h)? l.
I guess 3...
Am I correct (c), too low (l), or too high (h)? c.
I'm correct!
true</syntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">min=0
max=100
 
Line 1,034 ⟶ 2,765:
EndIf
ForEver
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">inclusive_range = mn, mx = (1, 10)
 
print('''\
Line 1,065 ⟶ 2,796:
break
print("\nThanks for keeping score.")</langsyntaxhighlight>
 
'''Sample Game-play'''
Line 1,079 ⟶ 2,810:
 
Thanks for keeping score.</pre>
 
===Obscure solution using bisect module===
 
Hacky solution using a fake list class and the <code>bisect</code> module from the standard library to do the binary search.
{{trans|Go}}
<langsyntaxhighlight lang="python">import bisect
try: input = raw_input
except: pass
Line 1,100 ⟶ 2,833:
""" % (LOWER, UPPER))
result = bisect.bisect_left(GuessNumberFakeList(), 0, LOWER, UPPER)
print("Your number is %d." % result)</langsyntaxhighlight>
 
;Sample output:
<pre>Instructions:
Think of integer number from 0 (inclusive) to 100 (exclusive) and
I will guess it. After each guess, I will ask you if it is less than
or equal to some number, and you will respond with "yes" or "no".
 
 
Is your number less than or equal to 50?no
 
Is your number less than or equal to 75?yes
 
Is your number less than or equal to 63?no
 
Is your number less than or equal to 69?no
 
Is your number less than or equal to 72?yes
 
Is your number less than or equal to 71?no
Your number is 72.</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery">
[ [ $ "lower higher equal" nest$ ]
constant ] is responses ( --> $ )
 
[ trim reverse
trim reverse
$ "" swap witheach
[ lower join ] ] is cleanup ( $ --> $ )
 
[ $ "Think of a number from 1 to"
$ " 100 and press enter." join
input drop
0 temp put
[] 100 times [ i 1+ join ]
[ dup size 0 = iff
[ say "Impossible!" cr 0 ]
done
dup size 2 / split behead
dup temp replace
say "I guess " echo say "." cr
$ "lower, higher or equal? "
input cleanup responses find
[ table
[ nip false ]
[ drop false ]
[ say "I guessed it!"
cr true ]
[ say "I do not understand."
temp share swap join join
cr false ] ]
do until ]
2drop temp release ] is play ( --> )</syntaxhighlight>
 
{{out}}
 
Playing in the Quackery shell. In the first game the player tries to confuse the computer by giving an impossible response.
 
<pre>/O> play
...
Think of a number from 1 to 100 and press enter.
I guess 50.
lower, higher or equal? lower
I guess 25.
lower, higher or equal? HiGhEr
I guess 37.
lower, higher or equal? none of the above
I do not understand.
I guess 37.
lower, higher or equal? lower
I guess 31.
lower, higher or equal? higher
I guess 34.
lower, higher or equal? higher
I guess 35.
lower, higher or equal? higher
I guess 36.
lower, higher or equal? higher
Impossible!
 
Stack empty.
 
/O> play
...
Think of a number from 1 to 100 and press enter.
I guess 50.
lower, higher or equal? equal
I guessed it!
 
Stack empty.
 
/O> </pre>
 
=={{header|R}}==
Can be fooled if you lie to it. For example, always reporting "h" for guessANumberPlayer(1, 5) will have it guess 0.
<syntaxhighlight lang="rsplus">guessANumberPlayer <- function(low, high)
{
boundryErrorCheck(low, high)
repeat
{
guess <- floor(mean(c(low, high)))
#Invalid inputs to this switch will simply cause the repeat loop to run again, breaking nothing.
switch(guessResult(guess),
l = low <- guess + 1,
h = high <- guess - 1,
c = return(paste0("Your number is ", guess, ".", " I win!")))
}
}
 
#Copied from my solution at https://rosettacode.org/wiki/Guess_the_number/With_feedback#R
boundryErrorCheck <- function(low, high)
{
if(!is.numeric(low) || as.integer(low) != low) stop("Lower bound must be an integer. Try again.")
if(!is.numeric(high) || as.integer(high) != high) stop("Upper bound must be an integer. Try again.")
if(high < low) stop("Upper bound must be strictly greater than lower bound. Try again.")
if(low == high) stop("This game is impossible to lose. Try again.")
invisible()
}
 
guessResult <- function(guess) readline(paste0("My guess is ", guess, ". If it is too low, submit l. If it is too high, h. Otherwise, c. "))</syntaxhighlight>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">#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))</syntaxhighlight>
 
Another way with loops and mutation
<syntaxhighlight lang="racket">#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!"))</syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
 
<syntaxhighlight lang="raku" line>multi sub MAIN() { MAIN(0, 100) }
multi sub MAIN($min is copy where ($min >= 0), $max is copy where ($max > $min)) {
say "Think of a number between $min and $max and I'll guess it!";
while $min <= $max {
my $guess = (($max + $min)/2).floor;
given lc prompt "My guess is $guess. Is your number higher, lower or equal? " {
when /^e/ { say "I knew it!"; exit }
when /^h/ { $min = $guess + 1 }
when /^l/ { $max = $guess }
default { say "WHAT!?!?!" }
}
}
say "How can your number be both higher and lower than $max?!?!?";
}</syntaxhighlight>
 
You may execute this program with '<tt>raku program</tt>' or with '<tt>raku program min max</tt>'. Raku creates a usage for us if we don't give the right parameters. It also parses the parameters for us and provides them via <tt>$min</tt> and <tt>$max</tt>. We use multi-subs to provide two MAIN subroutines so the user is able to choose between min and max parameters and no parameters at all, in which case min is set to 0 and max to 100.
 
=={{header|Red}}==
<syntaxhighlight lang="rebol">Red[]
 
lower: 1
upper: 100
print ["Please think of a number between" lower "and" upper]
 
forever [
guess: to-integer upper + lower / 2
print ["My guess is" guess]
until [
input: ask "Is your number (l)ower, (e)qual to, or (h)igher than my guess? "
find ["l" "e" "h"] input
]
if "e" = input [break]
either "l" = input [upper: guess] [lower: guess]
]
 
print ["I did it! Your number was" guess]</syntaxhighlight>
{{out}}
<pre>
Please think of a number between 1 and 100
My guess is 50
Is your number (l)ower, (e)qual to, or (h)igher than my guess? car
Is your number (l)ower, (e)qual to, or (h)igher than my guess? l
My guess is 25
Is your number (l)ower, (e)qual to, or (h)igher than my guess? h
My guess is 37
Is your number (l)ower, (e)qual to, or (h)igher than my guess? l
My guess is 31
Is your number (l)ower, (e)qual to, or (h)igher than my guess? h
My guess is 34
Is your number (l)ower, (e)qual to, or (h)igher than my guess? e
I did it! Your number was 34
</pre>
 
=={{header|REXX}}==
===with positive integers===
<lang rexx>
This version only handles positive integers up to the nine decimal digits, &nbsp; but the default HIGH is one thousand.
/*REXX program to play guess-the-number (with itself!). */
<syntaxhighlight lang="rexx">/*REXX program plays guess─the─number (with itself) with positive integers. */
parse arg low high seed . /*obtain optional arguments from the CL*/
if low=='' | low=="," then low= 1 /*Not specified? Then use the default.*/
if high=='' | high=="," then high= 1000 /* " " " " " " */
if datatype(seed, 'W') then call random ,,seed /*Useful seed? Then use a random seed.*/
?= random(low, high) /*generate random number from low->high*/
$= "──────── Try to guess my number (it's between " /*part of a prompt message.*/
g= /*nullify the first guess. */
do #=1; oldg= g /*save the guess for later comparison. */
if pos('high', info)\==0 then high= g /*test if the guess is too high. */
if pos('low' , info)\==0 then low = g /* " " " " " " low. */
say /*display a blank line before prompt. */
say $ low ' and ' high " inclusive):" /*issue the prompt message to terminal.*/
say /*display a blank line after prompt. */
g= (low + (high - low) / 2) / 1 /*calculate the next guess & normalize.*/
if g=oldg then g= g + 1 /*bump guess by one 'cause we're close.*/
say 'My guess is' g /*display computer's guess to the term.*/
if g=? then leave /*this guess is correct; leave & inform*/
if g>? then info= right(' Your guess is too high.', 60, "─")
else info= right(' Your guess is too low.' , 60, "─")
say info
end /*try*/
say /*stick a fork in it, we're all done. */
say 'Congratulations! You guessed the secret number in' # "tries."</syntaxhighlight>
'''output''' shown is from playing several games:
<pre style="height:70ex">
──────── Try to guess my number (it's between 1 and 1000 inclusive):
 
My guess is 500.5
parse arg low high . /*let them choose the range.*/
──────────────────────────────────── Your guess is too high.
if low=='' then low=1
if high=='' then high=1000
 
──────── Try to guess my number (it's between 1 and 500.5 inclusive):
?=random(low,high)
 
My guess is 250.75
say
───────────────────────────────────── Your guess is too low.
info="Try to guess my number (it's between" low 'and',
high" inclusive)."
 
──────── Try to guess my number (it's between 250.75 and 500.5 inclusive):
do j=1
say info
say
call guesser
 
My guess is 375.625
select
──────────────────────────────────── Your guess is too high.
when guess>? then info=right("It's too high.",40)
when guess<? then info=right("It's too low. ",40)
otherwise leave
end
 
──────── Try to guess my number (it's between 250.75 and 375.625 inclusive):
end
 
My guess is 313.1875
say
───────────────────────────────────── Your guess is too low.
say 'Congratulations! You guessed the secret number in' j "tries."
say
exit
 
──────── Try to guess my number (it's between 313.1875 and 375.625 inclusive):
 
My guess is 344.40625
guesser: upper info
──────────────────────────────────── Your guess is too high.
if \datatype(newlow ,'N') then newlow =low
if \datatype(newhigh,'N') then newhigh=high
oldGuess=guess
if pos('HIGH',info)\==0 then newhigh=guess
if pos('LOW' ,info)\==0 then newlow =guess
guess=newlow+(newhigh-newlow)%2
if guess==oldguess then guess=guess+1
say 'My guess is' guess
return
</lang>
Output shown is from playing several games:
<pre style="height:30ex;overflow:scroll">
 
──────── Try to guess my number (it's between 1 313.1875 and 1000 344.40625 inclusive).:
 
My guess is 500328.796875
───────────────────────────────────── Your guess is too low.
It's too low.
 
──────── Try to guess my number (it's between 328.796875 and 344.40625 inclusive):
My guess is 750
It's too low.
 
My guess is 875336.601563
──────────────────────────────────── Your guess is too high.
It's too high.
 
──────── Try to guess my number (it's between 328.796875 and 336.601563 inclusive):
My guess is 812
It's too low.
 
My guess is 843332.699219
──────────────────────────────────── Your guess is too high.
It's too high.
 
──────── Try to guess my number (it's between 328.796875 and 332.699219 inclusive):
My guess is 827
It's too high.
 
My guess is 819330.748047
──────────────────────────────────── Your guess is too high.
It's too low.
 
──────── Try to guess my number (it's between 328.796875 and 330.748047 inclusive):
My guess is 823
It's too low.
 
My guess is 825329.772461
───────────────────────────────────── Your guess is too low.
 
──────── Try to guess my number (it's between 329.772461 and 330.748047 inclusive):
Congratulations! You guessed the secret number in 9 tries.
 
My guess is 330.260254
_________________________________________________________________
──────────────────────────────────── Your guess is too high.
 
──────── Try to guess my number (it's between 329.772461 and 330.260254 inclusive):
 
My guess is 330.016358
Try to guess my number (it's between 1 and 1000 inclusive).
──────────────────────────────────── Your guess is too high.
 
──────── Try to guess my number (it's between 329.772461 and 330.016358 inclusive):
My guess is 500
It's too high.
 
My guess is 250329.89441
───────────────────────────────────── Your guess is too low.
It's too high.
 
──────── Try to guess my number (it's between 329.89441 and 330.016358 inclusive):
My guess is 125
It's too high.
 
My guess is 63329.955384
───────────────────────────────────── Your guess is too low.
It's too high.
 
──────── Try to guess my number (it's between 329.955384 and 330.016358 inclusive):
My guess is 32
It's too low.
 
My guess is 47329.985871
───────────────────────────────────── Your guess is too low.
It's too low.
 
──────── Try to guess my number (it's between 329.985871 and 330.016358 inclusive):
My guess is 55
It's too low.
 
My guess is 59330.001115
──────────────────────────────────── Your guess is too high.
It's too high.
 
──────── Try to guess my number (it's between 329.985871 and 330.001115 inclusive):
My guess is 57
It's too low.
 
My guess is 58329.993493
───────────────────────────────────── Your guess is too low.
 
──────── Try to guess my number (it's between 329.993493 and 330.001115 inclusive):
Congratulations! You guessed the secret number in 10 tries.
 
My guess is 329.997304
_________________________________________________________________
───────────────────────────────────── Your guess is too low.
 
──────── Try to guess my number (it's between 329.997304 and 330.001115 inclusive):
 
My guess is 329.99921
Try to guess my number (it's between 1 and 1000 inclusive).
───────────────────────────────────── Your guess is too low.
 
──────── Try to guess my number (it's between 329.99921 and 330.001115 inclusive):
My guess is 500
It's too high.
 
My guess is 250330.000163
──────────────────────────────────── Your guess is too high.
It's too low.
 
──────── Try to guess my number (it's between 329.99921 and 330.000163 inclusive):
My guess is 375
It's too high.
 
My guess is 312329.999687
───────────────────────────────────── Your guess is too low.
It's too low.
 
──────── Try to guess my number (it's between 329.999687 and 330.000163 inclusive):
My guess is 343
It's too low.
 
My guess is 359329.999925
───────────────────────────────────── Your guess is too low.
It's too high.
 
──────── Try to guess my number (it's between 329.999925 and 330.000163 inclusive):
My guess is 351
 
My guess is 330.000044
Congratulations! You guessed the secret number in 7 tries.
──────────────────────────────────── Your guess is too high.
 
──────── Try to guess my number (it's between 329.999925 and 330.000044 inclusive):
_________________________________________________________________
 
My guess is 329.999985
───────────────────────────────────── Your guess is too low.
 
──────── Try to guess my number (it's between 1 329.999985 and 1000 330.000044 inclusive).:
 
My guess is 500330.000015
──────────────────────────────────── Your guess is too high.
It's too low.
 
──────── Try to guess my number (it's between 329.999985 and 330.000015 inclusive):
My guess is 750
It's too high.
 
My guess is 625330
It's too low.
 
Congratulations! You guessed the secret number in 26 tries.
My guess is 687
</pre>
It's too high.
 
=== with positive numbers ===
My guess is 656
This version handles decimal fractions, &nbsp; the method used can generate numbers from zero to five fractional digits.
<syntaxhighlight lang="rexx">/*REXX program plays guess─the─number (with itself) with positive rational numbers. */
parse arg low high frac seed . /*obtain optional arguments from the CL*/
if low=='' | low=="," then low= 1 /*Not specified? Then use the default.*/
if high=='' | high=="," then high= 1000 /* " " " " " " */
if frac=='' | frac=="," then frac= 1 /* " " " " " " */
if datatype(seed, 'W') then call random ,,seed /*Useful seed? Then use a random seed.*/
fdigs= 10**frac /*compute the number of fractional digs*/
?= random(low, high) + random(0,fdigs) / fdigs /*Tougher game? It may have fractions.*/
$= "──────── Try to guess my number (it's between " /*part of a prompt message.*/
g= /*nullify the first guess. */
do #=1; oldg= g /*save the guess for later comparison. */
if pos('high', info)\==0 then high= g /*test if the guess is too high. */
if pos('low' , info)\==0 then low = g /* " " " " " " low. */
say /*display a blank line before prompt. */
say $ low ' and ' high " inclusive):" /*issue the prompt message to terminal.*/
say /*display a blank line after prompt. */
g= (low + (high - low) / 2) / 1 /*calculate the next guess & normalize.*/
if g=oldg then g= g + 1 /*bump guess by one 'cause we're close.*/
say 'My guess is' g /*display computer's guess to the term.*/
if g=? then leave /*this guess is correct; leave & inform*/
if g>? then info= right(' Your guess is too high.', 60, "─")
else info= right(' Your guess is too low.' , 60, "─")
say info
end /*try*/
say /*stick a fork in it, we're all done. */
say 'Congratulations! You guessed the secret number in' # "tries.""</syntaxhighlight>
'''output''' will generally be about ten times longer (that is, has ten times the guesses) as the previous REXX version.
<pre style="height:35ex">
──────── Try to guess my number (it's between 1 and 1000 inclusive):
 
My guess is 500.5
Congratulations! You guessed the secret number in 5 tries.
──────────────────────────────────── Your guess is too high.
 
──────── Try to guess my number (it's between 1 and 500.5 inclusive):
_________________________________________________________________
 
My guess is 250.75
───────────────────────────────────── Your guess is too low.
 
──────── Try to guess my number (it's between 1 250.75 and 1000 500.5 inclusive).:
 
My guess is 500375.625
──────────────────────────────────── Your guess is too high.
It's too high.
 
──────── Try to guess my number (it's between 250.75 and 375.625 inclusive):
My guess is 250
It's too high.
 
My guess is 125313.1875
───────────────────────────────────── Your guess is too low.
 
──────── Try to guess my number (it's between 313.1875 and 375.625 inclusive):
Congratulations! You guessed the secret number in 3 tries.
 
My guess is 344.40625
──────────────────────────────────── Your guess is too high.
 
──────── Try to guess my number (it's between 313.1875 and 344.40625 inclusive):
 
My guess is 328.796875
───────────────────────────────────── Your guess is too low.
 
──────── Try to guess my number (it's between 328.796875 and 344.40625 inclusive):
 
My guess is 336.601563
──────────────────────────────────── Your guess is too high.
 
──────── Try to guess my number (it's between 328.796875 and 336.601563 inclusive):
 
My guess is 332.699219
──────────────────────────────────── Your guess is too high.
 
──────── Try to guess my number (it's between 328.796875 and 332.699219 inclusive):
 
My guess is 330.748047
──────────────────────────────────── Your guess is too high.
 
──────── Try to guess my number (it's between 328.796875 and 330.748047 inclusive):
 
My guess is 329.772461
───────────────────────────────────── Your guess is too low.
 
──────── Try to guess my number (it's between 329.772461 and 330.748047 inclusive):
 
My guess is 330.260254
───────────────────────────────────── Your guess is too low.
 
──────── Try to guess my number (it's between 330.260254 and 330.748047 inclusive):
 
My guess is 330.504151
───────────────────────────────────── Your guess is too low.
 
──────── Try to guess my number (it's between 330.504151 and 330.748047 inclusive):
 
My guess is 330.626099
──────────────────────────────────── Your guess is too high.
 
──────── Try to guess my number (it's between 330.504151 and 330.626099 inclusive):
 
My guess is 330.565125
───────────────────────────────────── Your guess is too low.
 
──────── Try to guess my number (it's between 330.565125 and 330.626099 inclusive):
 
My guess is 330.595612
───────────────────────────────────── Your guess is too low.
 
──────── Try to guess my number (it's between 330.595612 and 330.626099 inclusive):
 
My guess is 330.610856
──────────────────────────────────── Your guess is too high.
 
──────── Try to guess my number (it's between 330.595612 and 330.610856 inclusive):
 
My guess is 330.603234
──────────────────────────────────── Your guess is too high.
 
──────── Try to guess my number (it's between 330.595612 and 330.603234 inclusive):
 
My guess is 330.599423
───────────────────────────────────── Your guess is too low.
 
──────── Try to guess my number (it's between 330.599423 and 330.603234 inclusive):
 
My guess is 330.601329
──────────────────────────────────── Your guess is too high.
 
──────── Try to guess my number (it's between 330.599423 and 330.601329 inclusive):
 
My guess is 330.600376
──────────────────────────────────── Your guess is too high.
 
──────── Try to guess my number (it's between 330.599423 and 330.600376 inclusive):
 
My guess is 330.5999
───────────────────────────────────── Your guess is too low.
 
──────── Try to guess my number (it's between 330.5999 and 330.600376 inclusive):
 
My guess is 330.600138
──────────────────────────────────── Your guess is too high.
 
──────── Try to guess my number (it's between 330.5999 and 330.600138 inclusive):
 
My guess is 330.600019
──────────────────────────────────── Your guess is too high.
 
──────── Try to guess my number (it's between 330.5999 and 330.600019 inclusive):
 
My guess is 330.59996
───────────────────────────────────── Your guess is too low.
 
──────── Try to guess my number (it's between 330.59996 and 330.600019 inclusive):
 
My guess is 330.59999
───────────────────────────────────── Your guess is too low.
 
──────── Try to guess my number (it's between 330.59999 and 330.600019 inclusive):
 
My guess is 330.600005
──────────────────────────────────── Your guess is too high.
 
──────── Try to guess my number (it's between 330.59999 and 330.600005 inclusive):
 
My guess is 330.599998
───────────────────────────────────── Your guess is too low.
 
──────── Try to guess my number (it's between 330.599998 and 330.600005 inclusive):
 
My guess is 330.600002
──────────────────────────────────── Your guess is too high.
 
──────── Try to guess my number (it's between 330.599998 and 330.600002 inclusive):
 
My guess is 330.6
 
Congratulations! You guessed the secret number in 29 tries.
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
min = 1
max = 100
see "think of a number between " + min + " and " + max + nl
see "i will try to guess your number." + nl
while true
guess =floor((min + max) / 2)
see "my guess is " + guess + nl
see "is it higher than, lower than or equal to your number " give answer
ans = left(answer,1)
switch ans
on "l" min = guess + 1
on "h" max = guess - 1
on "e" exit
other see "sorry, i didn't understand your answer." + nl
off
end
see "goodbye." + nl
</syntaxhighlight>
Output:
<pre>
think of a number between 1 and 100
i will try to guess your number.
my guess is 50
is it higher than, lower than or equal to your number l
my guess is 75
is it higher than, lower than or equal to your number h
my guess is 62
is it higher than, lower than or equal to your number h
my guess is 56
is it higher than, lower than or equal to your number l
my guess is 59
is it higher than, lower than or equal to your number l
my guess is 60
is it higher than, lower than or equal to your number e
goodbye.
</pre>
 
=={{header|Ruby}}==
Computer plays versus itself
<syntaxhighlight lang ="ruby">def play(low, high, turns = 1)
num = (low + (high - low) / 2
print "guessing #{num}\t"
case is_it?(num)
when 1
puts "too high"
play(low, num - 1, turns + 1)
when -1
puts "too low"
play(num + 1, high, turns + 1)
else
puts "found the number in #{turns} turns."
Line 1,301 ⟶ 3,453:
end
 
low, high = 1, 100
$number = rand(low .. high)
high = 100
$number = low + rand(high-low)
 
puts "guess a number between #{low} and #{high}"
play(low, high)</langsyntaxhighlight>
 
Example
Line 1,317 ⟶ 3,468:
guessing 29 too low
guessing 30 found the number in 7 turns.</pre>
 
Since Ruby 2.0 it can be done actually using a built-in binary search (output as above):
<syntaxhighlight lang="ruby">r = (1..100)
secret = rand(r)
turns = 0
puts "Guess a number between #{r.min} and #{r.max}"
r.bsearch do |guess| # bsearch works on ranges
print "Guessing #{guess} \t"
turns += 1
low_high = secret <=> guess # -1, 0, or 1
puts ["found the number in #{turns} turns", "too low", "too high"][low_high]
low_high
end
</syntaxhighlight>
 
=={{header|Rust}}==
{{works with|rustc|1.0.0-nightly}}
<syntaxhighlight lang="rust">use std::io::stdin;
 
const MIN: isize = 1;
const MAX: isize = 100;
 
fn main() {
loop {
let mut min = MIN;
let mut max = MAX;
let mut num_guesses = 1;
println!("Please think of a number between {} and {}", min, max);
loop {
let guess = (min + max) / 2;
println!("Is it {}?", guess);
println!("(type h if my guess is too high, l if too low, e if equal and q to quit)");
 
let mut line = String::new();
stdin().read_line(&mut line).unwrap();
match Some(line.chars().next().unwrap().to_uppercase().next().unwrap()) {
Some('H') => {
max = guess - 1;
num_guesses += 1;
},
Some('L')=> {
min = guess + 1;
num_guesses += 1;
},
Some('E') => {
if num_guesses == 1 {
println!("\n*** That was easy! Got it in one guess! ***\n");
} else {
println!("\n*** I knew it! Got it in only {} guesses! ***\n", num_guesses);
}
break;
},
Some('Q') => return,
_ => println!("Sorry, I didn't quite get that. Please try again.")
}
}
}
}</syntaxhighlight>
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">object GuessNumber extends App {
val n = 1 + scala.util.Random.nextInt(20)
 
println("Guess which number I've chosen in the range 1 to 20\n")
do println("Your guess, please: ")
while (io.StdIn.readInt() match {
case `n` => println("Correct, well guessed!"); false
case guess if (n + 1 to 20).contains(guess) => println("Your guess is higher than the chosen number, try again"); true
case guess if (1 until n).contains(guess) => println("Your guess is lower than the chosen number, try again"); true
case _ => println("Your guess is inappropriate, try again"); true
})
 
}</syntaxhighlight>
 
=={{header|Scheme}}==
{{works with|Guile}}
<langsyntaxhighlight lang="scheme">(define minimum 1) (define maximum 100)
(define maximum 100)
 
(display "Enter a number from ")(display minimum)
Line 1,337 ⟶ 3,561:
(if (string= input "l") (begin (display "OK...")
(set! minimum (+ guess 1)))))
(display "I was RIGHT!\n")</langsyntaxhighlight>
 
=={{header|Seed7}}==
The program reads the possible commands (l, h, c, q) as single keypresses from the
[http://seed7.sourceforge.net/libraries/keybd.htm#KEYBOARD KEYBOARD] with
[http://seed7.sourceforge.net/libraries/keybd.htm#getc%28in_console_keybd_file%29 getc].
It is also possible to quit the program with q.
The program recognices also a situation when there is only one possible number left
and the command is not c.
 
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
$ include "keybd.s7i";
 
const proc: main is func
local
var boolean: okay is FALSE;
var boolean: quit is FALSE;
var integer: low is 1;
var integer: high is 1000;
var integer: guess is 0;
var char: command is ' ';
begin
writeln("Choose a number between 1 and 1000.");
write("Press Enter and I will start to guess the number.");
readln;
repeat
guess := low + (high - low) div 2;
write("My guess is: " <& guess);
write(". How did I score (l=too low, h=too high, c=correct, q=quit)? ");
flush(OUT);
repeat
command := lower(getc(KEYBOARD));
until command in {'l', 'h', 'c', 'q'};
writeln(command);
case command of
when {'l'}: low := succ(guess);
when {'h'}: high := pred(guess);
when {'c'}: okay := TRUE;
when {'q'}: quit := TRUE;
end case;
until quit or okay or low > high;
if not quit then
writeln("So the number is: " <& guess);
if low > high then
writeln("Why did you cheat?");
end if;
end if;
writeln("It was nice to play with you.");
end func;</syntaxhighlight>
 
Example
<pre>
Choose a number between 1 and 1000.
Press Enter and I will start to guess the number.
My guess is: 500. How did I score (l=too low, h=too high, c=correct, q=quit)? h
My guess is: 250. How did I score (l=too low, h=too high, c=correct, q=quit)? l
My guess is: 375. How did I score (l=too low, h=too high, c=correct, q=quit)? h
My guess is: 312. How did I score (l=too low, h=too high, c=correct, q=quit)? l
My guess is: 343. How did I score (l=too low, h=too high, c=correct, q=quit)? l
My guess is: 359. How did I score (l=too low, h=too high, c=correct, q=quit)? l
My guess is: 367. How did I score (l=too low, h=too high, c=correct, q=quit)? h
My guess is: 363. How did I score (l=too low, h=too high, c=correct, q=quit)? l
My guess is: 365. How did I score (l=too low, h=too high, c=correct, q=quit)? c
So the number is: 365
It was nice to play with you.
</pre>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">var min = 1
var max = 99
var tries = 0
var guess = pick(min..max)
 
print <<"EOT".chomp
\n=>> Think of a number between #{min} and #{max} and I'll guess it!\n
Press <ENTER> when are you ready...
EOT
 
STDIN.readline
 
loop {
print <<-EOT.chomp
\n=>> My guess is: #{guess} Is your number higher, lower, or equal? (h/l/e)
>#{' '}
EOT
 
++tries
given (STDIN.readline) {
case (max <= min) {
say "\nI give up..."
break
}
when (/^h/i) {
min = guess+1
}
when (/^l/i) {
max = guess
}
when (/^e/i) {
say "\nI knew it! It took me only #{tries} tries."
break
}
default {
say "error: invalid score"
next
}
}
 
guess = ((min+max) // 2)
}</syntaxhighlight>
 
=={{header|Smalltalk}}==
 
{{works with|Pharo|1.4}}
 
Create a class like this:
 
<syntaxhighlight lang="smalltalk">Object subclass: #NumberGuesser
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Rosettacode'
</syntaxhighlight>
Enter these methods into it:
 
<syntaxhighlight lang="smalltalk">playBetween: low and: high
Transcript clear.
number := (low to: high) atRandom.
self playBetween: low and: high atTurn: 1.
playBetween: low and: high atTurn: turn
| guess |
guess := (low + ((high - low) / 2)) asInteger.
self showGuessing: guess atTurn: turn.
true caseOf: {
[number > guess] ->
[self showNumberBeing: #low. self playBetween: guess and: high atTurn: turn+1 ].
[number < guess] ->
[self showNumberBeing: #high. self playBetween: low and: guess atTurn: turn+1 ].
[true] ->
[self showNumberFoundAtTurnNr: turn ] }.
 
showGuessing: guess atTurn: turn
Transcript show: ('{1}. guessing: {2}' format: {turn asString. guess asString}).
showNumberBeing: comparisonToken
Transcript show: ' ==> too ', (comparisonToken asString); cr.
 
showNumberFoundAtTurnNr: turn
Transcript show: (' ==> found the number in {1} turn(s).' format: {turn asString}); cr.
</syntaxhighlight>
 
If you'd rather not use <code>caseOf:</code> you can write <code>playBetween:and:atTurn:</code> like this:
 
<syntaxhighlight lang="smalltalk">
playBetween: low and: high atTurn: turn
| guess |
guess := (low + ((high - low) / 2)) asInteger.
self showGuessing: guess atTurn: turn.
(guess = number)
ifTrue: [self showNumberFoundAtTurnNr: turn ]
ifFalse: [
(number > guess)
ifTrue: [self showNumberBeing: #low. self playBetween: guess and: high atTurn: turn+1 ]
ifFalse: [self showNumberBeing: #high. self playBetween: low and: guess atTurn: turn+1]].
</syntaxhighlight>
 
And evaluate this in a Workspace:
 
<syntaxhighlight lang="smalltalk">g := NumberGuesser new.
g playBetween: 1 and: 100.
</syntaxhighlight>
 
Sample output:
 
<pre>
1. guessing: 50 ==> too low
2. guessing: 75 ==> too low
3. guessing: 87 ==> too high
4. guessing: 81 ==> too low
5. guessing: 84 ==> too low
6. guessing: 85 ==> found the number in 6 turn(s).
</pre>
 
=={{header|Standard ML}}==
A clever solution that uses the built-in binary search functions with a virtual list.
{{works with|SML/NJ}}
{{trans|Go}}
<syntaxhighlight lang="sml">structure GuessNumberHelper : MONO_ARRAY = struct
type elem = order
type array = int * int
fun length (lo, hi) = hi - lo
fun sub ((lo, hi), i) =
let
val n = lo + i
in
print ("My guess is: " ^ Int.toString (lo+i) ^ ". Is it too high, too low, or correct? (H/L/C) ");
let
val str = valOf (TextIO.inputLine TextIO.stdIn)
in
case Char.toLower (String.sub (str, 0)) of
#"l" => GREATER
| #"h" => LESS
| #"c" => EQUAL
end
end
 
(* dummy implementations for not-needed functions *)
type vector = unit
val maxLen = Array.maxLen
fun update _ = raise Domain
fun array _ = raise Domain
fun fromList _ = raise Domain
fun tabulate _ = raise Domain
fun vector _ = raise Domain
fun copy _ = raise Domain
fun copyVec _ = raise Domain
fun appi _ = raise Domain
fun app _ = raise Domain
fun modifyi _ = raise Domain
fun modify _ = raise Domain
fun foldli _ = raise Domain
fun foldl _ = raise Domain
fun foldri _ = raise Domain
fun foldr _ = raise Domain
fun findi _ = raise Domain
fun find _ = raise Domain
fun exists _ = raise Domain
fun all _ = raise Domain
fun collate _ = raise Domain
end
 
structure GuessNumberBSearch = BSearchFn (GuessNumberHelper)
 
val lower = 0
val upper = 100;
 
print ("Instructions:\n" ^
"Think of integer number from " ^ Int.toString lower ^
" (inclusive) to " ^ Int.toString upper ^ " (exclusive) and\n" ^
"I will guess it. After each guess, you respond with L, H, or C depending\n" ^
"on if my guess was too low, too high, or correct.\n");
 
case GuessNumberBSearch.bsearch (fn (_, x) => x) ((), (lower, upper)) of
NONE => print "That is impossible.\n"
| SOME (result, _) => print ("Your number is " ^ Int.toString result ^ ".\n")</syntaxhighlight>
 
=={{header|Swift}}==
<syntaxhighlight lang="text">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
}
}</syntaxhighlight>
{{out}}
<pre>
Enter an integer between 1 and 100 for me to guess:
10
My guess is: 50
How was my guess? Enter "higher" if it was higher, "lower" if it was lower, and "correct" if I got it
lower
My guess is: 25
How was my guess? Enter "higher" if it was higher, "lower" if it was lower, and "correct" if I got it
lower
My guess is: 12
How was my guess? Enter "higher" if it was higher, "lower" if it was lower, and "correct" if I got it
lower
My guess is: 6
How was my guess? Enter "higher" if it was higher, "lower" if it was lower, and "correct" if I got it
higher
My guess is: 9
How was my guess? Enter "higher" if it was higher, "lower" if it was lower, and "correct" if I got it
higher
My guess is: 10
How was my guess? Enter "higher" if it was higher, "lower" if it was lower, and "correct" if I got it
correct
I did it!
Program ended with exit code: 0</pre>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">set from 1
set to 10
fconfigure stdout -buffering none
Line 1,361 ⟶ 3,905:
break
}
}</langsyntaxhighlight>
Sample run:
<pre>
Line 1,369 ⟶ 3,913:
Found it: 6
</pre>
 
=={{header|UNIX Shell}}==
{{works with|bash}}
<syntaxhighlight lang="bash">read -p "Lower bound: " lower
read -p "Upper bound: " upper
moves=0
PS3="> "
while :; do
((moves++))
guess=$(( lower + (upper-lower)/2 ))
echo "Is it $guess?"
select ans in "too small" "too big" "got it!"; do
case $ans in
"got it!") break 2 ;;
"too big") upper=$(( upper==guess ? upper-1 : guess )); break ;;
"too small") lower=$(( lower==guess ? lower+1 : guess )); break ;;
esac
done
((lower>upper)) && echo "you must be cheating!"
done
echo "I guessed it in $moves guesses"</syntaxhighlight>
 
=={{header|VBA}}==
 
<syntaxhighlight lang="vba">
Sub GuessNumberPlayer()
Dim iGuess As Integer, iLow As Integer, iHigh As Integer, iCount As Integer
Dim vSolved As Variant
On Error GoTo ErrHandler
MsgBox "Pick a number between 1 and 100. I will guess it!", vbInformation + vbOKOnly, "Rosetta Code | Guess the Number Player"
iCount = 0
iLow = 1
iHigh = 100
Do While Not vSolved = "Y"
iGuess = Application.WorksheetFunction.RandBetween(iLow, iHigh)
iCount = iCount + 1
CheckGuess:
vSolved = InputBox("My guess: " & iGuess & vbCr & vbCr & "Y = Yes, correct guess" & vbCr & _
"H = your number is higher" & vbCr & "L = your number is lower" & vbCr & "X = exit game", "Rosetta Code | Guess the Number Player | Guess " & iCount)
Select Case vSolved
Case "Y", "y": GoTo CorrectGuess
Case "X", "x": Exit Sub
Case "H", "h": iLow = iGuess + 1
Case "L", "l": iHigh = iGuess - 1
Case Else: GoTo CheckGuess
End Select
Loop
CorrectGuess:
MsgBox "I guessed number " & iGuess & " in just " & iCount & " attempts!", vbExclamation + vbOKOnly, "Rosetta Code | Guess the Number Player"
Exit Sub
ErrHandler:
MsgBox "Not possible. Were you cheating?!", vbCritical + vbOKOnly, "Rosetta Code | Guess the Number Player | ERROR!"
End Sub
</syntaxhighlight>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-str}}
<syntaxhighlight lang="wren">import "io" for Stdin, Stdout
import "./str" for Char
 
var hle
var lowest = 1
var highest = 20
var guess = 10
System.print("Please choose a number between 1 and 20 but don't tell me what it is yet\n")
 
while (true) {
System.print("My guess is %(guess)")
while (true) {
System.write("Is this higher/lower than or equal to your chosen number h/l/e : ")
Stdout.flush()
hle = Char.lower(Stdin.readLine())
if (hle == "l" && guess == highest) {
System.print("It can't be more than %(highest), try again")
hle = "i" // signifies invalid
} else if (hle == "h" && guess == lowest) {
System.print("It can't be less than %(lowest), try again")
hle = "i"
}
if ("hle".contains(hle)) break
}
if (hle == "e") {
System.print("Good, thanks for playing the game with me!")
break
}
if (hle == "h") {
if (highest > guess - 1) highest = guess - 1
} else {
if (lowest < guess + 1) lowest = guess + 1
}
guess = ((lowest + highest)/2).floor
}</syntaxhighlight>
 
{{out}}
Sample session (player chooses 12):
<pre>
Please choose a number between 1 and 20 but don't tell me what it is yet
 
My guess is 10
Is this higher/lower than or equal to your chosen number h/l/e : l
My guess is 15
Is this higher/lower than or equal to your chosen number h/l/e : h
My guess is 12
Is this higher/lower than or equal to your chosen number h/l/e : e
Good, thanks for playing the game with me!
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
int Hi, Lo, Guess;
[Text(0, "Think of a number between 1 and 100 then press a key.");
if ChIn(1) then [];
Lo:= 1; Hi:= 101;
loop [Guess:= (Lo+Hi)/2;
Text(0, "^M^JIs it "); IntOut(0, Guess);
Text(0, " (Y = yes, H = too high, L = too low)? ");
case ChIn(1) of
^L,^l: Lo:= Guess;
^H,^h: Hi:= Guess;
^Y,^y: quit
other ChOut(0, 7\bel\);
];
Text(0, "^M^JYippee!");
]</syntaxhighlight>
 
Example output:
<pre>
Think of a number between 1 and 100 then press a key.
Is it 51 (Y = yes, H = too high, L = too low)? H
Is it 26 (Y = yes, H = too high, L = too low)? H
Is it 13 (Y = yes, H = too high, L = too low)? L
Is it 19 (Y = yes, H = too high, L = too low)? H
Is it 16 (Y = yes, H = too high, L = too low)? L
Is it 17 (Y = yes, H = too high, L = too low)? Y
Yippee!
</pre>
 
=={{header|zkl}}==
Your basic binary search.
<syntaxhighlight lang="zkl">println("Pick a number between 0 and 100 and remember it.");
low,high,g := 0,100, 20;
while(True){
r:=ask("I guess %d; is that high, low or =? ".fmt(g)).strip().toLower();
if(r=="="){ println("Yea!"); break; }
if(r[0]=="h") high=g-1 else low=g+1;
if(low==high){ println("Yea! the number is ",low); break; }
if(low>high){ println("I'm confused!"); break; }
g=(low + high)/2;
}</syntaxhighlight>
{{out}}
<pre>
Pick a number between 0 and 100 and remember it.
I guess 20; is that high, low or =? l
I guess 60; is that high, low or =? h
I guess 40; is that high, low or =? h
I guess 30; is that high, low or =? h
I guess 25; is that high, low or =? l
I guess 27; is that high, low or =? h
Yea! the number is 26
</pre>
 
=={{header|ZX Spectrum Basic}}==
{{trans|BBC_BASIC}}
<syntaxhighlight lang="zxbasic">10 LET min=1: LET max=100
20 PRINT "Think of a number between ";min;" and ";max
30 PRINT "I will try to guess your number."
40 LET guess=INT ((min+max)/2)
50 PRINT "My guess is ";guess
60 INPUT "Is it higuer than, lower than or equal to your number? ";a$
65 LET a$=a$(1)
70 IF a$="L" OR a$="l" THEN LET min=guess+1: GO TO 40
80 IF a$="H" OR a$="h" THEN LET max=guess-1: GO TO 40
90 IF a$="E" OR a$="e" THEN PRINT "Goodbye.": STOP
100 PRINT "Sorry, I didn't understand your answer.": GO TO 60</syntaxhighlight>
 
{{omit from|GUISS}}
{{omit from|Lilypond}}
2,056

edits