Guess the number/With feedback (player): Difference between revisions
Content added Content deleted
Drkameleon (talk | contribs) (Added Arturo implementation) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 16: | Line 16: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">V (target_min, target_max) = (1, 10) |
||
V (mn, mx) = (target_min, target_max) |
V (mn, mx) = (target_min, target_max) |
||
Line 44: | Line 44: | ||
L.break |
L.break |
||
print("\nThanks for keeping score.")</ |
print("\nThanks for keeping score.")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 62: | Line 62: | ||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang="action!">PROC Main() |
||
BYTE n,min=[1],max=[100] |
BYTE n,min=[1],max=[100] |
||
CHAR c |
CHAR c |
||
Line 86: | Line 86: | ||
FI |
FI |
||
OD |
OD |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Guess_the_number_with_feedback_(player).png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Guess_the_number_with_feedback_(player).png Screenshot from Atari 8-bit computer] |
||
Line 108: | Line 108: | ||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO; |
||
procedure Guess_Number_Player is |
procedure Guess_Number_Player is |
||
procedure Guess_Number (Lower_Limit : Integer; Upper_Limit : Integer) is |
procedure Guess_Number (Lower_Limit : Integer; Upper_Limit : Integer) is |
||
Line 143: | Line 143: | ||
end loop; |
end loop; |
||
Guess_Number (Lower_Limit, Upper_Limit); |
Guess_Number (Lower_Limit, Upper_Limit); |
||
end Guess_Number_Player;</ |
end Guess_Number_Player;</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}} |
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}} |
||
< |
<syntaxhighlight lang="algol68">BEGIN |
||
INT lower := 1; |
INT lower := 1; |
||
INT upper := 100; |
INT upper := 100; |
||
Line 172: | Line 172: | ||
FI |
FI |
||
DO SKIP OD |
DO SKIP OD |
||
END</ |
END</syntaxhighlight> |
||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
< |
<syntaxhighlight lang="applescript">-- defining the range of the number to be guessed |
||
property minLimit : 1 |
property minLimit : 1 |
||
property maxLimit : 100 |
property maxLimit : 100 |
||
Line 206: | Line 206: | ||
end if |
end if |
||
end repeat |
end repeat |
||
end run</ |
end run</syntaxhighlight> |
||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">print {: |
||
Think of a number between 1 and 10 and wait for me to guess it. |
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 |
On every guess of mine you should state whether the guess was |
||
Line 245: | Line 245: | ||
] |
] |
||
print "" |
print "" |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 278: | Line 278: | ||
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. |
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"> |
|||
<lang AsciiDots> |
|||
/. |
/. |
||
*$"Think of a number from 1 to 127" |
*$"Think of a number from 1 to 127" |
||
Line 291: | Line 291: | ||
|#a_$01#\ /2#\ | @ \*--{=}-/\-/ | |
|#a_$01#\ /2#\ | @ \*--{=}-/\-/ | |
||
\-------*{/}@*-*---*-----------------------------------/ |
\-------*{/}@*-*---*-----------------------------------/ |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
Line 297: | Line 297: | ||
Works with the AutoHotkey entry at: [[Guess the number/With feedback]] |
Works with the AutoHotkey entry at: [[Guess the number/With feedback]] |
||
< |
<syntaxhighlight lang="autohotkey">MaxGuesses = 50 |
||
GetParams(LowerBound,UpperBound) |
GetParams(LowerBound,UpperBound) |
||
Line 350: | Line 350: | ||
Else |
Else |
||
Return, "Too High" |
Return, "Too High" |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
< |
<syntaxhighlight lang="dos"> |
||
@echo off |
@echo off |
||
Line 384: | Line 384: | ||
echo Guesses: %attempts% |
echo Guesses: %attempts% |
||
pause>nul |
pause>nul |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 399: | Line 399: | ||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
< |
<syntaxhighlight lang="basic">10 DEFINT A-Z |
||
20 INPUT "Lower limit? ",L |
20 INPUT "Lower limit? ",L |
||
30 INPUT "Upper limit? ",H |
30 INPUT "Upper limit? ",H |
||
Line 410: | Line 410: | ||
90 L=(H-L)\2+L: GOTO 40 |
90 L=(H-L)\2+L: GOTO 40 |
||
100 H=(H-L)\2+L: GOTO 40 |
100 H=(H-L)\2+L: GOTO 40 |
||
110 PRINT "It took";T;"tries."</ |
110 PRINT "It took";T;"tries."</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Lower limit? 1 |
<pre>Lower limit? 1 |
||
Line 429: | Line 429: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
< |
<syntaxhighlight lang="bbcbasic"> min% = 1 |
||
max% = 100 |
max% = 100 |
||
PRINT "Think of a number between "; min% " and " ;max% |
PRINT "Think of a number between "; min% " and " ;max% |
||
Line 445: | Line 445: | ||
UNTIL FALSE |
UNTIL FALSE |
||
PRINT "Goodbye." |
PRINT "Goodbye." |
||
END</ |
END</syntaxhighlight> |
||
=={{header|BCPL}}== |
=={{header|BCPL}}== |
||
< |
<syntaxhighlight lang="bcpl">get "libhdr" |
||
let reads(s) = valof |
let reads(s) = valof |
||
Line 497: | Line 497: | ||
writes("Upper bound? ") ; max := readn() |
writes("Upper bound? ") ; max := readn() |
||
writef("It took %N attempts.*N", guess(min, max, 1)) |
writef("It took %N attempts.*N", guess(min, max, 1)) |
||
$)</ |
$)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Lower bound? 1 |
<pre>Lower bound? 1 |
||
Line 510: | Line 510: | ||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
int main(){ |
int main(){ |
||
Line 539: | Line 539: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
Demonstration (number is 57): |
Demonstration (number is 57): |
||
Line 556: | Line 556: | ||
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. |
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|Java}} |
{{trans|Java}} |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
#include <ctype.h> |
#include <ctype.h> |
||
Line 607: | Line 607: | ||
printf("Your number is %d.\n", (int)(result - ZERO)); |
printf("Your number is %d.\n", (int)(result - ZERO)); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp}}== |
=={{header|C sharp}}== |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using System.Collections.Generic; |
using System.Collections.Generic; |
||
using System.Linq; |
using System.Linq; |
||
Line 742: | Line 742: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C++}}== |
=={{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. |
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}} |
{{trans|Go}} |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <algorithm> |
#include <algorithm> |
||
#include <string> |
#include <string> |
||
Line 797: | Line 797: | ||
std::cout << "Your number is " << answer << ".\n"; |
std::cout << "Your number is " << answer << ".\n"; |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Ceylon}}== |
=={{header|Ceylon}}== |
||
< |
<syntaxhighlight lang="ceylon">shared void run() { |
||
while(true) { |
while(true) { |
||
variable value low = 1; |
variable value low = 1; |
||
Line 838: | Line 838: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="clojure">(require '[clojure.string :as str]) |
||
(defn guess-game [low high] |
(defn guess-game [low high] |
||
Line 855: | Line 855: | ||
\c (println "Huzzah!") |
\c (println "Huzzah!") |
||
(do (println "Invalid input.") |
(do (println "Invalid input.") |
||
(recur guess step)))))</ |
(recur guess step)))))</syntaxhighlight> |
||
Output |
Output |
||
<pre>user=> (guess-game 1 100) |
<pre>user=> (guess-game 1 100) |
||
Line 875: | Line 875: | ||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
An imperative solution using LOOP: |
An imperative solution using LOOP: |
||
<syntaxhighlight lang="lisp"> |
|||
<lang Lisp> |
|||
(defun guess-the-number (&optional (max 1000) (min 0)) |
(defun guess-the-number (&optional (max 1000) (min 0)) |
||
(flet ((get-feedback (guess) |
(flet ((get-feedback (guess) |
||
Line 892: | Line 892: | ||
else do (setf max guess) |
else do (setf max guess) |
||
finally (write-line "I got it!")))) |
finally (write-line "I got it!")))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
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): |
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"> |
|||
<lang Lisp> |
|||
(defun guess-the-number (&optional (max 1000) (min 0)) |
(defun guess-the-number (&optional (max 1000) (min 0)) |
||
(labels ((guess-loop (min max) |
(labels ((guess-loop (min max) |
||
Line 909: | Line 909: | ||
(format t "Think of a number between ~a and ~a.~%" min max) |
(format t "Think of a number between ~a and ~a.~%" min max) |
||
(guess-loop min max))) |
(guess-loop min max))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.string; |
||
void main() { |
void main() { |
||
Line 954: | Line 954: | ||
} |
} |
||
writeln("\nThanks for keeping score."); |
writeln("\nThanks for keeping score."); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Think of a number between 1 and 10 and wait for me to guess it. |
<pre>Think of a number between 1 and 10 and wait for me to guess it. |
||
Line 970: | Line 970: | ||
{{libheader| system.console}} |
{{libheader| system.console}} |
||
Thanks JensBorrisholt for System.Console [https://github.com/JensBorrisholt/DelphiConsole/tree/master/Console]. |
Thanks JensBorrisholt for System.Console [https://github.com/JensBorrisholt/DelphiConsole/tree/master/Console]. |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
program Guess_the_number; |
program Guess_the_number; |
||
Line 1,131: | Line 1,131: | ||
readln; |
readln; |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
{{works with|Elixir|1.2}} |
{{works with|Elixir|1.2}} |
||
< |
<syntaxhighlight lang="elixir">defmodule Game do |
||
def guess(a..b) do |
def guess(a..b) do |
||
x = Enum.random(a..b) |
x = Enum.random(a..b) |
||
Line 1,153: | Line 1,153: | ||
end |
end |
||
end |
end |
||
Game.guess(1..100)</ |
Game.guess(1..100)</syntaxhighlight> |
||
{{out|sample}} |
{{out|sample}} |
||
Line 1,166: | Line 1,166: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang="erlang">% Implemented by Arjun Sunel |
||
-module(guess_game). |
-module(guess_game). |
||
-export([main/0]). |
-export([main/0]). |
||
Line 1,194: | Line 1,194: | ||
guess(K,U,N) |
guess(K,U,N) |
||
end |
end |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Player 1 : Guess my number between 1 and and 100 until you get it right. |
<pre>Player 1 : Guess my number between 1 and and 100 until you get it right. |
||
Line 1,211: | Line 1,211: | ||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
{{trans|PureBasic}} |
{{trans|PureBasic}} |
||
< |
<syntaxhighlight lang="euphoria">include get.e |
||
include wildcard.e |
include wildcard.e |
||
Line 1,241: | Line 1,241: | ||
puts(1,"I do not understand that...\n") |
puts(1,"I do not understand that...\n") |
||
end if |
end if |
||
end while</ |
end while</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{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. |
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 ( -- ) |
: instruct ( -- ) |
||
Line 1,260: | Line 1,260: | ||
"I did it. Your number was %d!\n" printf ; |
"I did it. Your number was %d!\n" printf ; |
||
instruct play-game gloat</ |
instruct play-game gloat</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,278: | Line 1,278: | ||
=={{header|Fantom}}== |
=={{header|Fantom}}== |
||
< |
<syntaxhighlight lang="fantom"> |
||
class Main |
class Main |
||
{ |
{ |
||
Line 1,315: | Line 1,315: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Example: |
Example: |
||
Line 1,350: | Line 1,350: | ||
=={{header|FOCAL}}== |
=={{header|FOCAL}}== |
||
< |
<syntaxhighlight lang="focal">01.10 A "LOWER LIMIT",L |
||
01.15 A "UPPER LIMIT",H |
01.15 A "UPPER LIMIT",H |
||
01.20 S T=0 |
01.20 S T=0 |
||
Line 1,365: | Line 1,365: | ||
01.70 S H=G;G 1.3 |
01.70 S H=G;G 1.3 |
||
01.75 T "ATTEMPTS",T,! |
01.75 T "ATTEMPTS",T,! |
||
01.80 Q</ |
01.80 Q</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>LOWER LIMIT:1 |
<pre>LOWER LIMIT:1 |
||
Line 1,385: | Line 1,385: | ||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|Fortran|95 and later}} |
{{works with|Fortran|95 and later}} |
||
< |
<syntaxhighlight lang="fortran">program Guess_a_number_Player |
||
implicit none |
implicit none |
||
Line 1,422: | Line 1,422: | ||
end select |
end select |
||
end do |
end do |
||
end program</ |
end program</syntaxhighlight> |
||
Output |
Output |
||
<pre>Think of a number between 1 and 100 and I will try to guess it. |
<pre>Think of a number between 1 and 100 and I will try to guess it. |
||
Line 1,438: | Line 1,438: | ||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
Dim hle As String |
Dim hle As String |
||
Line 1,469: | Line 1,469: | ||
guess = (lowest + highest)\2 |
guess = (lowest + highest)\2 |
||
Loop |
Loop |
||
End</ |
End</syntaxhighlight> |
||
Sample input/output |
Sample input/output |
||
Line 1,489: | Line 1,489: | ||
=={{header|Go}}== |
=={{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] |
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] |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 1,510: | Line 1,510: | ||
}) |
}) |
||
fmt.Printf("Your number is %d.\n", lower+answer) |
fmt.Printf("Your number is %d.\n", lower+answer) |
||
}</ |
}</syntaxhighlight> |
||
Manual solution: |
Manual solution: |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 1,550: | Line 1,550: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
Explicit version with arbitrary range: |
Explicit version with arbitrary range: |
||
<syntaxhighlight lang="haskell"> |
|||
<lang Haskell> |
|||
main :: IO () |
main :: IO () |
||
main = do |
main = do |
||
Line 1,579: | Line 1,579: | ||
"h" -> loop guess to |
"h" -> loop guess to |
||
(_) -> putStrLn "Invalid answer." >> loop from to |
(_) -> putStrLn "Invalid answer." >> loop from to |
||
</syntaxhighlight> |
|||
</lang> |
|||
Short version with set limits: |
Short version with set limits: |
||
<syntaxhighlight lang="haskell"> |
|||
<lang Haskell> |
|||
main = f 0 100 |
main = f 0 100 |
||
where f x y = let g = div (x + y) 2 in |
where f x y = let g = div (x + y) 2 in |
||
Line 1,590: | Line 1,590: | ||
"h" -> f g y |
"h" -> f g y |
||
"c" -> putStrLn "Yay!" |
"c" -> putStrLn "Yay!" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
{{trans|Fantom}} |
{{trans|Fantom}} |
||
<syntaxhighlight lang="icon"> |
|||
<lang Icon> |
|||
procedure main () |
procedure main () |
||
lower_limit := 1 |
lower_limit := 1 |
||
Line 1,625: | Line 1,625: | ||
} |
} |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|IS-BASIC}}== |
=={{header|IS-BASIC}}== |
||
< |
<syntaxhighlight lang="is-basic">100 PROGRAM "GuessIt.bas" |
||
110 LET N=100 |
110 LET N=100 |
||
120 TEXT 80 |
120 TEXT 80 |
||
Line 1,653: | Line 1,653: | ||
330 LOOP UNTIL K$>="0" AND K$<="3" |
330 LOOP UNTIL K$>="0" AND K$<="3" |
||
340 LET QUESTION=VAL(K$) |
340 LET QUESTION=VAL(K$) |
||
350 END DEF</ |
350 END DEF</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
< |
<syntaxhighlight lang="j">require 'misc' |
||
guess=:3 :0 |
guess=:3 :0 |
||
'lo hi'=.y |
'lo hi'=.y |
||
Line 1,671: | Line 1,671: | ||
end. |
end. |
||
end. |
end. |
||
)</ |
)</syntaxhighlight> |
||
Example session: |
Example session: |
||
<lang> guess 1 100 |
<syntaxhighlight lang="text"> guess 1 100 |
||
guessing a number between 1 and 100 |
guessing a number between 1 and 100 |
||
is it 86? hi |
is it 86? hi |
||
Line 1,694: | Line 1,694: | ||
guessing a number between 49 and 50 |
guessing a number between 49 and 50 |
||
is it 49? lo |
is it 49? lo |
||
50</ |
50</syntaxhighlight> |
||
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.) |
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 1,701: | Line 1,701: | ||
A clever solution that uses the built-in binary search functions with a virtual list. |
A clever solution that uses the built-in binary search functions with a virtual list. |
||
{{trans|Go}} |
{{trans|Go}} |
||
< |
<syntaxhighlight lang="java5">import java.util.AbstractList; |
||
import java.util.Collections; |
import java.util.Collections; |
||
import java.util.Scanner; |
import java.util.Scanner; |
||
Line 1,736: | Line 1,736: | ||
System.out.printf("Your number is %d.\n", result); |
System.out.printf("Your number is %d.\n", result); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
Line 1,745: | Line 1,745: | ||
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. |
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; |
var DONE = RIGHT = 0, HIGH = 1, LOW = -1; |
||
Line 1,798: | Line 1,798: | ||
main(); |
main(); |
||
</syntaxhighlight> |
|||
</lang> |
|||
An example session: |
An example session: |
||
Line 1,830: | Line 1,830: | ||
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. |
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 |
lower = 0 |
||
input = readline() |
input = readline() |
||
Line 1,877: | Line 1,877: | ||
end |
end |
||
println("\nI win after ", attempts, attempts == 1 ? " attempt." : " attempts.")</ |
println("\nI win after ", attempts, attempts == 1 ? " attempt." : " attempts.")</syntaxhighlight> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
< |
<syntaxhighlight lang="scala">// version 1.0.5-2 |
||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
Line 1,915: | Line 1,915: | ||
guess = (lowest + highest) / 2 |
guess = (lowest + highest) / 2 |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Sample input/output: |
Sample input/output: |
||
{{out}} |
{{out}} |
||
Line 1,934: | Line 1,934: | ||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<syntaxhighlight lang="lasso">#!/usr/bin/lasso9 |
||
local( |
local( |
||
Line 1,983: | Line 1,983: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Examples: |
Examples: |
||
Line 2,018: | Line 2,018: | ||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
< |
<syntaxhighlight lang="lb">mini=0 |
||
maxi=100 |
maxi=100 |
||
Line 2,047: | Line 2,047: | ||
end select |
end select |
||
wend |
wend |
||
print "Thanks for playing." </ |
print "Thanks for playing." </syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
<lang>function wait(waittime)--wait function is used so that app will not quit immediately |
<syntaxhighlight lang="text">function wait(waittime)--wait function is used so that app will not quit immediately |
||
local timer = os.time() |
local timer = os.time() |
||
repeat until os.time() == timer + waittime |
repeat until os.time() == timer + waittime |
||
Line 2,085: | Line 2,085: | ||
end |
end |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
<lang>guessnumber[min0_, max0_] := |
<syntaxhighlight lang="text">guessnumber[min0_, max0_] := |
||
DynamicModule[{min = min0, max = max0, guess, correct = False}, |
DynamicModule[{min = min0, max = max0, guess, correct = False}, |
||
guess[] := Round@Mean@{min, max}; |
guess[] := Round@Mean@{min, max}; |
||
Line 2,096: | Line 2,096: | ||
Button["too low", min = guess[]], |
Button["too low", min = guess[]], |
||
Button["correct", correct = True]}}]]; |
Button["correct", correct = True]}}]]; |
||
guessnumber[1, 100]</ |
guessnumber[1, 100]</syntaxhighlight> |
||
=={{header|MATLAB}}== |
=={{header|MATLAB}}== |
||
< |
<syntaxhighlight lang="matlab">function GuessNumberFeedbackPlayer |
||
lowVal = input('Lower limit: '); |
lowVal = input('Lower limit: '); |
||
Line 2,128: | Line 2,128: | ||
end |
end |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Lower limit: 0 |
<pre>Lower limit: 0 |
||
Line 2,151: | Line 2,151: | ||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
< |
<syntaxhighlight lang="maxscript">inclusiveRange = [1,100] |
||
lowRange = inclusiveRange.x |
lowRange = inclusiveRange.x |
||
maxRange = inclusiveRange.y |
maxRange = inclusiveRange.y |
||
Line 2,176: | Line 2,176: | ||
default: (format "\nI don't understand your input.") |
default: (format "\nI don't understand your input.") |
||
) |
) |
||
)</ |
)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<syntaxhighlight lang="maxscript"> |
|||
<lang MAXScript> |
|||
OK |
OK |
||
Think of a number between 1 and 100 and I will try to guess it. |
Think of a number between 1 and 100 and I will try to guess it. |
||
Line 2,200: | Line 2,200: | ||
Yay. I guessed your number after 6 tries. |
Yay. I guessed your number after 6 tries. |
||
OK |
OK |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Modula-2}}== |
=={{header|Modula-2}}== |
||
< |
<syntaxhighlight lang="modula2">MODULE raden; |
||
IMPORT InOut; |
IMPORT InOut; |
||
Line 2,238: | Line 2,238: | ||
InOut.WriteString ("Thanks for letting me play with you."); |
InOut.WriteString ("Thanks for letting me play with you."); |
||
InOut.WriteLn |
InOut.WriteLn |
||
END raden.</ |
END raden.</syntaxhighlight>Example:<pre>raden |
||
Choose a number between 0 and 1000. |
Choose a number between 0 and 1000. |
||
Line 2,255: | Line 2,255: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">import strutils |
||
let oRange = 1..10 |
let oRange = 1..10 |
||
Line 2,283: | Line 2,283: | ||
break |
break |
||
echo "Thanks for keeping score."</ |
echo "Thanks for keeping score."</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>Think of a number between 1 and 10 and wait for me to guess it. |
<pre>Think of a number between 1 and 10 and wait for me to guess it. |
||
Line 2,296: | Line 2,296: | ||
=={{header|NS-HUBASIC}}== |
=={{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 |
20 ISVALID=0 |
||
30 GUESS=5 |
30 GUESS=5 |
||
Line 2,305: | Line 2,305: | ||
80 IF ANSWER$="EQUAL TO" THEN PRINT "OH YES! I GUESSED CORRECTLY!":END |
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." |
90 IF ISVALID=0 THEN PRINT "SORRY";", BUT THAT ANSWER IS INVALID." |
||
100 GOTO 40</ |
100 GOTO 40</syntaxhighlight> |
||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
A clever solution that uses the built-in binary search functions with a virtual list. |
A clever solution that uses the built-in binary search functions with a virtual list. |
||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h> |
||
@interface GuessNumberFakeArray : NSArray { |
@interface GuessNumberFakeArray : NSArray { |
||
Line 2,366: | Line 2,366: | ||
} |
} |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<syntaxhighlight lang="parigp"> |
||
guessnumber2(b)={ |
guessnumber2(b)={ |
||
my(c=0,d=b,a=0); |
my(c=0,d=b,a=0); |
||
Line 2,393: | Line 2,393: | ||
); |
); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
< |
<syntaxhighlight lang="pascal">Program GuessIt(input, output); |
||
var |
var |
||
Line 2,427: | Line 2,427: | ||
writeln ('So the number is: ', guess:4); |
writeln ('So the number is: ', guess:4); |
||
writeln ('It was nice to play with you.'); |
writeln ('It was nice to play with you.'); |
||
end.</ |
end.</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>:> ./GuessTheNumberPlayerFeedback |
<pre>:> ./GuessTheNumberPlayerFeedback |
||
Line 2,446: | Line 2,446: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">#!/usr/bin/perl |
||
my $min = 1; |
my $min = 1; |
||
Line 2,481: | Line 2,481: | ||
} while(1); |
} while(1); |
||
}</ |
}</syntaxhighlight> |
||
<pre>=>> Think of a number between 1 and 99 and I'll guess it! |
<pre>=>> Think of a number between 1 and 99 and I'll guess it! |
||
Line 2,504: | Line 2,504: | ||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #000080;font-style:italic;">-- |
<span style="color: #000080;font-style:italic;">-- |
||
-- demo\rosetta\Guess_the_number2.exw |
-- demo\rosetta\Guess_the_number2.exw |
||
Line 2,566: | Line 2,566: | ||
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span> |
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
{{trans|PureBasic}} |
{{trans|PureBasic}} |
||
< |
<syntaxhighlight lang="picolisp">(de guessTheNumber (Min Max) |
||
(prinl "Think of a number between " Min " and " Max ".") |
(prinl "Think of a number between " Min " and " Max ".") |
||
(prinl "On every guess of mine you should state whether my guess was") |
(prinl "On every guess of mine you should state whether my guess was") |
||
Line 2,588: | Line 2,588: | ||
("L" (setq Min Guess)) |
("L" (setq Min Guess)) |
||
("=" (nil (prinl "I did it!"))) |
("=" (nil (prinl "I did it!"))) |
||
(T (prinl "I do not understand that...")) ) ) ) ) )</ |
(T (prinl "I do not understand that...")) ) ) ) ) )</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>: (guessTheNumber 1 99) |
<pre>: (guessTheNumber 1 99) |
||
Line 2,602: | Line 2,602: | ||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
< |
<syntaxhighlight lang="prolog">min(1). max(10). |
||
pick_number(Min, Max) :- |
pick_number(Min, Max) :- |
||
Line 2,623: | Line 2,623: | ||
play :- |
play :- |
||
pick_number(Min, Max), |
pick_number(Min, Max), |
||
guess_number(Min, Max).</ |
guess_number(Min, Max).</syntaxhighlight> |
||
Example: |
Example: |
||
< |
<syntaxhighlight lang="prolog">?- play. |
||
Pick a number between 1 and 10, and I will guess it... |
Pick a number between 1 and 10, and I will guess it... |
||
Ready? (Enter anything when ready):y. |
Ready? (Enter anything when ready):y. |
||
Line 2,637: | Line 2,637: | ||
Am I correct (c), too low (l), or too high (h)? c. |
Am I correct (c), too low (l), or too high (h)? c. |
||
I'm correct! |
I'm correct! |
||
true</ |
true</syntaxhighlight> |
||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">min=0 |
||
max=100 |
max=100 |
||
Line 2,663: | Line 2,663: | ||
EndIf |
EndIf |
||
ForEver |
ForEver |
||
EndIf</ |
EndIf</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">inclusive_range = mn, mx = (1, 10) |
||
print('''\ |
print('''\ |
||
Line 2,694: | Line 2,694: | ||
break |
break |
||
print("\nThanks for keeping score.")</ |
print("\nThanks for keeping score.")</syntaxhighlight> |
||
'''Sample Game-play''' |
'''Sample Game-play''' |
||
Line 2,713: | Line 2,713: | ||
Hacky solution using a fake list class and the <code>bisect</code> module from the standard library to do the binary search. |
Hacky solution using a fake list class and the <code>bisect</code> module from the standard library to do the binary search. |
||
{{trans|Go}} |
{{trans|Go}} |
||
< |
<syntaxhighlight lang="python">import bisect |
||
try: input = raw_input |
try: input = raw_input |
||
except: pass |
except: pass |
||
Line 2,731: | Line 2,731: | ||
""" % (LOWER, UPPER)) |
""" % (LOWER, UPPER)) |
||
result = bisect.bisect_left(GuessNumberFakeList(), 0, LOWER, UPPER) |
result = bisect.bisect_left(GuessNumberFakeList(), 0, LOWER, UPPER) |
||
print("Your number is %d." % result)</ |
print("Your number is %d." % result)</syntaxhighlight> |
||
;Sample output: |
;Sample output: |
||
Line 2,755: | Line 2,755: | ||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
<syntaxhighlight lang="quackery"> |
|||
<lang Quackery> |
|||
[ [ $ "lower higher equal" nest$ ] |
[ [ $ "lower higher equal" nest$ ] |
||
constant ] is responses ( --> $ ) |
constant ] is responses ( --> $ ) |
||
Line 2,786: | Line 2,786: | ||
cr false ] ] |
cr false ] ] |
||
do until ] |
do until ] |
||
2drop temp release ] is play ( --> )</ |
2drop temp release ] is play ( --> )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,829: | Line 2,829: | ||
=={{header|R}}== |
=={{header|R}}== |
||
Can be fooled if you lie to it. For example, always reporting "h" for guessANumberPlayer(1, 5) will have it guess 0. |
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) |
boundryErrorCheck(low, high) |
||
Line 2,853: | Line 2,853: | ||
} |
} |
||
guessResult <- function(guess) readline(paste0("My guess is ", guess, ". If it is too low, submit l. If it is too high, h. Otherwise, c. "))</ |
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}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket">#lang racket |
||
(define (guess low high) |
(define (guess low high) |
||
Line 2,877: | Line 2,877: | ||
(printf "Think of a number between ~a and ~a. |
(printf "Think of a number between ~a and ~a. |
||
Use (h)igh, (l)ow and (c)orrect to guide me.\n" low high) |
Use (h)igh, (l)ow and (c)orrect to guide me.\n" low high) |
||
(guess-loop low high))</ |
(guess-loop low high))</syntaxhighlight> |
||
Another way with loops and mutation |
Another way with loops and mutation |
||
< |
<syntaxhighlight lang="racket">#lang racket |
||
(define (guess minimum maximum) |
(define (guess minimum maximum) |
||
(printf "Think of a number from ~a to ~a, use (h)igh, (l)ow and (c)orrect." minimum maximum) |
(printf "Think of a number from ~a to ~a, use (h)igh, (l)ow and (c)orrect." minimum maximum) |
||
Line 2,895: | Line 2,895: | ||
(begin (display "OK...") |
(begin (display "OK...") |
||
(set! minimum (add1 guess))))) |
(set! minimum (add1 guess))))) |
||
(displayln "I was RIGHT!"))</ |
(displayln "I was RIGHT!"))</syntaxhighlight> |
||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(formerly Perl 6) |
||
<lang |
<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)) { |
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!"; |
say "Think of a number between $min and $max and I'll guess it!"; |
||
Line 2,913: | Line 2,913: | ||
} |
} |
||
say "How can your number be both higher and lower than $max?!?!?"; |
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. |
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}}== |
=={{header|Red}}== |
||
< |
<syntaxhighlight lang="rebol">Red[] |
||
lower: 1 |
lower: 1 |
||
Line 2,935: | Line 2,935: | ||
] |
] |
||
print ["I did it! Your number was" guess]</ |
print ["I did it! Your number was" guess]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,956: | Line 2,956: | ||
===with positive integers=== |
===with positive integers=== |
||
This version only handles positive integers up to the nine decimal digits, but the default HIGH is one thousand. |
This version only handles positive integers up to the nine decimal digits, but the default HIGH is one thousand. |
||
< |
<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*/ |
parse arg low high seed . /*obtain optional arguments from the CL*/ |
||
if low=='' | low=="," then low= 1 /*Not specified? Then use the default.*/ |
if low=='' | low=="," then low= 1 /*Not specified? Then use the default.*/ |
||
Line 2,979: | Line 2,979: | ||
end /*try*/ |
end /*try*/ |
||
say /*stick a fork in it, we're all done. */ |
say /*stick a fork in it, we're all done. */ |
||
say 'Congratulations! You guessed the secret number in' # "tries."</ |
say 'Congratulations! You guessed the secret number in' # "tries."</syntaxhighlight> |
||
'''output''' shown is from playing several games: |
'''output''' shown is from playing several games: |
||
<pre style="height:70ex"> |
<pre style="height:70ex"> |
||
Line 3,116: | Line 3,116: | ||
=== with positive numbers === |
=== with positive numbers === |
||
This version handles decimal fractions, the method used can generate numbers from zero to five fractional digits. |
This version handles decimal fractions, 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*/ |
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 low=='' | low=="," then low= 1 /*Not specified? Then use the default.*/ |
||
Line 3,141: | Line 3,141: | ||
end /*try*/ |
end /*try*/ |
||
say /*stick a fork in it, we're all done. */ |
say /*stick a fork in it, we're all done. */ |
||
say 'Congratulations! You guessed the secret number in' # "tries.""</ |
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. |
'''output''' will generally be about ten times longer (that is, has ten times the guesses) as the previous REXX version. |
||
<pre style="height:35ex"> |
<pre style="height:35ex"> |
||
Line 3,292: | Line 3,292: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
min = 1 |
min = 1 |
||
max = 100 |
max = 100 |
||
Line 3,310: | Line 3,310: | ||
end |
end |
||
see "goodbye." + nl |
see "goodbye." + nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 3,332: | Line 3,332: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
Computer plays versus itself |
Computer plays versus itself |
||
< |
<syntaxhighlight lang="ruby">def play(low, high, turns=1) |
||
num = (low + high) / 2 |
num = (low + high) / 2 |
||
print "guessing #{num}\t" |
print "guessing #{num}\t" |
||
Line 3,355: | Line 3,355: | ||
puts "guess a number between #{low} and #{high}" |
puts "guess a number between #{low} and #{high}" |
||
play(low, high)</ |
play(low, high)</syntaxhighlight> |
||
Example |
Example |
||
Line 3,368: | Line 3,368: | ||
Since Ruby 2.0 it can be done actually using a built-in binary search (output as above): |
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) |
secret = rand(r) |
||
turns = 0 |
turns = 0 |
||
Line 3,380: | Line 3,380: | ||
low_high |
low_high |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
{{works with|rustc|1.0.0-nightly}} |
{{works with|rustc|1.0.0-nightly}} |
||
< |
<syntaxhighlight lang="rust">use std::io::stdin; |
||
const MIN: isize = 1; |
const MIN: isize = 1; |
||
Line 3,424: | Line 3,424: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">object GuessNumber extends App { |
||
val n = 1 + scala.util.Random.nextInt(20) |
val n = 1 + scala.util.Random.nextInt(20) |
||
Line 3,439: | Line 3,439: | ||
}) |
}) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
{{works with|Guile}} |
{{works with|Guile}} |
||
< |
<syntaxhighlight lang="scheme">(define minimum 1) (define maximum 100) |
||
(display "Enter a number from ")(display minimum) |
(display "Enter a number from ")(display minimum) |
||
Line 3,459: | Line 3,459: | ||
(if (string= input "l") (begin (display "OK...") |
(if (string= input "l") (begin (display "OK...") |
||
(set! minimum (+ guess 1))))) |
(set! minimum (+ guess 1))))) |
||
(display "I was RIGHT!\n")</ |
(display "I was RIGHT!\n")</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
Line 3,469: | Line 3,469: | ||
and the command is not c. |
and the command is not c. |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
$ include "keybd.s7i"; |
$ include "keybd.s7i"; |
||
Line 3,507: | Line 3,507: | ||
end if; |
end if; |
||
writeln("It was nice to play with you."); |
writeln("It was nice to play with you."); |
||
end func;</ |
end func;</syntaxhighlight> |
||
Example |
Example |
||
Line 3,527: | Line 3,527: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">var min = 1 |
||
var max = 99 |
var max = 99 |
||
var tries = 0 |
var tries = 0 |
||
Line 3,568: | Line 3,568: | ||
guess = ((min+max) // 2) |
guess = ((min+max) // 2) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
Line 3,576: | Line 3,576: | ||
Create a class like this: |
Create a class like this: |
||
< |
<syntaxhighlight lang="smalltalk">Object subclass: #NumberGuesser |
||
instanceVariableNames: '' |
instanceVariableNames: '' |
||
classVariableNames: '' |
classVariableNames: '' |
||
poolDictionaries: '' |
poolDictionaries: '' |
||
category: 'Rosettacode' |
category: 'Rosettacode' |
||
</syntaxhighlight> |
|||
</lang> |
|||
Enter these methods into it: |
Enter these methods into it: |
||
< |
<syntaxhighlight lang="smalltalk">playBetween: low and: high |
||
Transcript clear. |
Transcript clear. |
||
number := (low to: high) atRandom. |
number := (low to: high) atRandom. |
||
Line 3,610: | Line 3,610: | ||
showNumberFoundAtTurnNr: turn |
showNumberFoundAtTurnNr: turn |
||
Transcript show: (' ==> found the number in {1} turn(s).' format: {turn asString}); cr. |
Transcript show: (' ==> found the number in {1} turn(s).' format: {turn asString}); cr. |
||
</syntaxhighlight> |
|||
</lang> |
|||
If you'd rather not use <code>caseOf:</code> you can write <code>playBetween:and:atTurn:</code> like this: |
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 |
playBetween: low and: high atTurn: turn |
||
| guess | |
| guess | |
||
Line 3,625: | Line 3,625: | ||
ifTrue: [self showNumberBeing: #low. self playBetween: guess and: high atTurn: turn+1 ] |
ifTrue: [self showNumberBeing: #low. self playBetween: guess and: high atTurn: turn+1 ] |
||
ifFalse: [self showNumberBeing: #high. self playBetween: low and: guess atTurn: turn+1]]. |
ifFalse: [self showNumberBeing: #high. self playBetween: low and: guess atTurn: turn+1]]. |
||
</syntaxhighlight> |
|||
</lang> |
|||
And evaluate this in a Workspace: |
And evaluate this in a Workspace: |
||
< |
<syntaxhighlight lang="smalltalk">g := NumberGuesser new. |
||
g playBetween: 1 and: 100. |
g playBetween: 1 and: 100. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Sample output: |
Sample output: |
||
Line 3,648: | Line 3,648: | ||
{{works with|SML/NJ}} |
{{works with|SML/NJ}} |
||
{{trans|Go}} |
{{trans|Go}} |
||
< |
<syntaxhighlight lang="sml">structure GuessNumberHelper : MONO_ARRAY = struct |
||
type elem = order |
type elem = order |
||
type array = int * int |
type array = int * int |
||
Line 3,705: | Line 3,705: | ||
case GuessNumberBSearch.bsearch (fn (_, x) => x) ((), (lower, upper)) of |
case GuessNumberBSearch.bsearch (fn (_, x) => x) ((), (lower, upper)) of |
||
NONE => print "That is impossible.\n" |
NONE => print "That is impossible.\n" |
||
| SOME (result, _) => print ("Your number is " ^ Int.toString result ^ ".\n")</ |
| SOME (result, _) => print ("Your number is " ^ Int.toString result ^ ".\n")</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
<lang>import Cocoa |
<syntaxhighlight lang="text">import Cocoa |
||
var found = false |
var found = false |
||
Line 3,755: | Line 3,755: | ||
high = lastGuess |
high = lastGuess |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,782: | Line 3,782: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">set from 1 |
||
set to 10 |
set to 10 |
||
fconfigure stdout -buffering none |
fconfigure stdout -buffering none |
||
Line 3,803: | Line 3,803: | ||
break |
break |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Sample run: |
Sample run: |
||
<pre> |
<pre> |
||
Line 3,814: | Line 3,814: | ||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
{{works with|bash}} |
{{works with|bash}} |
||
< |
<syntaxhighlight lang="bash">read -p "Lower bound: " lower |
||
read -p "Upper bound: " upper |
read -p "Upper bound: " upper |
||
moves=0 |
moves=0 |
||
Line 3,831: | Line 3,831: | ||
((lower>upper)) && echo "you must be cheating!" |
((lower>upper)) && echo "you must be cheating!" |
||
done |
done |
||
echo "I guessed it in $moves guesses"</ |
echo "I guessed it in $moves guesses"</syntaxhighlight> |
||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
< |
<syntaxhighlight lang="vba"> |
||
Sub GuessNumberPlayer() |
Sub GuessNumberPlayer() |
||
Dim iGuess As Integer, iLow As Integer, iHigh As Integer, iCount As Integer |
Dim iGuess As Integer, iLow As Integer, iHigh As Integer, iCount As Integer |
||
Line 3,864: | Line 3,864: | ||
MsgBox "Not possible. Were you cheating?!", vbCritical + vbOKOnly, "Rosetta Code | Guess the Number Player | ERROR!" |
MsgBox "Not possible. Were you cheating?!", vbCritical + vbOKOnly, "Rosetta Code | Guess the Number Player | ERROR!" |
||
End Sub |
End Sub |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
{{trans|Kotlin}} |
{{trans|Kotlin}} |
||
{{libheader|Wren-str}} |
{{libheader|Wren-str}} |
||
< |
<syntaxhighlight lang="ecmascript">import "io" for Stdin, Stdout |
||
import "/str" for Char |
import "/str" for Char |
||
Line 3,903: | Line 3,903: | ||
} |
} |
||
guess = ((lowest + highest)/2).floor |
guess = ((lowest + highest)/2).floor |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,920: | Line 3,920: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations |
||
int Hi, Lo, Guess; |
int Hi, Lo, Guess; |
||
[Text(0, "Think of a number between 1 and 100 then press a key."); |
[Text(0, "Think of a number between 1 and 100 then press a key."); |
||
Line 3,935: | Line 3,935: | ||
]; |
]; |
||
Text(0, "^M^JYippee!"); |
Text(0, "^M^JYippee!"); |
||
]</ |
]</syntaxhighlight> |
||
Example output: |
Example output: |
||
Line 3,951: | Line 3,951: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
Your basic binary search. |
Your basic binary search. |
||
< |
<syntaxhighlight lang="zkl">println("Pick a number between 0 and 100 and remember it."); |
||
low,high,g := 0,100, 20; |
low,high,g := 0,100, 20; |
||
while(True){ |
while(True){ |
||
Line 3,960: | Line 3,960: | ||
if(low>high){ println("I'm confused!"); break; } |
if(low>high){ println("I'm confused!"); break; } |
||
g=(low + high)/2; |
g=(low + high)/2; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,975: | Line 3,975: | ||
=={{header|ZX Spectrum Basic}}== |
=={{header|ZX Spectrum Basic}}== |
||
{{trans|BBC_BASIC}} |
{{trans|BBC_BASIC}} |
||
< |
<syntaxhighlight lang="zxbasic">10 LET min=1: LET max=100 |
||
20 PRINT "Think of a number between ";min;" and ";max |
20 PRINT "Think of a number between ";min;" and ";max |
||
30 PRINT "I will try to guess your number." |
30 PRINT "I will try to guess your number." |
||
Line 3,985: | Line 3,985: | ||
80 IF a$="H" OR a$="h" THEN LET max=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 |
90 IF a$="E" OR a$="e" THEN PRINT "Goodbye.": STOP |
||
100 PRINT "Sorry, I didn't understand your answer.": GO TO 60</ |
100 PRINT "Sorry, I didn't understand your answer.": GO TO 60</syntaxhighlight> |
||
{{omit from|GUISS}} |
{{omit from|GUISS}} |