Guess the number/With feedback: Difference between revisions

Content added Content deleted
(Add VTL-2)
m (syntax highlighting fixup automation)
Line 19: Line 19:
{{trans|Python}}
{{trans|Python}}


<lang 11l>V (target_min, target_max) = (1, 100)
<syntaxhighlight lang="11l">V (target_min, target_max) = (1, 100)


print("Guess my target number that is between #. and #. (inclusive).\n".format(target_min, target_max))
print("Guess my target number that is between #. and #. (inclusive).\n".format(target_min, target_max))
Line 41: Line 41:
I answer > target {print(‘ Too high.’)}
I answer > target {print(‘ Too high.’)}


print("\nThanks for playing.")</lang>
print("\nThanks for playing.")</syntaxhighlight>


{{out}}
{{out}}
Line 76: Line 76:


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC Main()
<syntaxhighlight lang="action!">PROC Main()
BYTE x,n,min=[1],max=[100]
BYTE x,n,min=[1],max=[100]


Line 94: Line 94:
FI
FI
OD
OD
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Guess_the_number_with_feedback.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Guess_the_number_with_feedback.png Screenshot from Atari 8-bit computer]
Line 109: Line 109:
=={{header|Ada}}==
=={{header|Ada}}==


<lang Ada>with Ada.Numerics.Discrete_Random;
<syntaxhighlight lang="ada">with Ada.Numerics.Discrete_Random;
with Ada.Text_IO;
with Ada.Text_IO;
procedure Guess_Number_Feedback is
procedure Guess_Number_Feedback is
Line 159: Line 159:
end loop;
end loop;
Guess_Number (Lower_Limit, Upper_Limit);
Guess_Number (Lower_Limit, Upper_Limit);
end Guess_Number_Feedback;</lang>
end Guess_Number_Feedback;</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<lang algol68># simple guess-the-number game #
<syntaxhighlight lang="algol68"># simple guess-the-number game #


main:(
main:(
Line 209: Line 209:
OD;
OD;
print( ( "That's correct!", newline ) )
print( ( "That's correct!", newline ) )
)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 235: Line 235:
=={{header|AppleScript}}==
=={{header|AppleScript}}==


<lang AppleScript>-- defining the range of the number to be guessed
<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 273: Line 273:
end try
end try
end repeat
end repeat
end run</lang>
end run</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>n: random 1 10
<syntaxhighlight lang="rebol">n: random 1 10
while ø [
while ø [
try? [
try? [
Line 288: Line 288:
]
]
else -> print "\tInvalid input!"
else -> print "\tInvalid input!"
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 305: Line 305:
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==


<lang AutoHotkey>MinNum = 1
<syntaxhighlight lang="autohotkey">MinNum = 1
MaxNum = 99999999999
MaxNum = 99999999999


Line 335: Line 335:
}
}
TotalTime := Round((A_TickCount - TotalTime) / 1000,1)
TotalTime := Round((A_TickCount - TotalTime) / 1000,1)
MsgBox, 64, Correct, The number %RandNum% was guessed in %Tries% tries, which took %TotalTime% seconds.</lang>
MsgBox, 64, Correct, The number %RandNum% was guessed in %Tries% tries, which took %TotalTime% seconds.</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f GUESS_THE_NUMBER_WITH_FEEDBACK.AWK
# syntax: GAWK -f GUESS_THE_NUMBER_WITH_FEEDBACK.AWK
BEGIN {
BEGIN {
Line 367: Line 367:
exit(0)
exit(0)
}
}
</syntaxhighlight>
</lang>


=={{header|BASIC}}==
=={{header|BASIC}}==


==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<lang ApplesoftBasic>100 L% = 1
<syntaxhighlight lang="applesoftbasic">100 L% = 1
110 U% = 10
110 U% = 10
120 N% = RND(1) * (U% - L% + 1) + L%
120 N% = RND(1) * (U% - L% + 1) + L%
Line 385: Line 385:
210 Q = G% = N%
210 Q = G% = N%
220 NEXT
220 NEXT
230 PRINT "THE GUESS WAS EQUAL TO THE TARGET."</lang>
230 PRINT "THE GUESS WAS EQUAL TO THE TARGET."</syntaxhighlight>


==={{header|BASIC256}}===
==={{header|BASIC256}}===
{{works with|BASIC256 }}
{{works with|BASIC256 }}
<lang basic256>
<syntaxhighlight lang="basic256">
Min = 5: Max = 15
Min = 5: Max = 15
chosen = int(rand*(Max-Min+1)) + Min
chosen = int(rand*(Max-Min+1)) + Min
Line 404: Line 404:
end if
end if
until guess = chosen
until guess = chosen
</syntaxhighlight>
</lang>
Output:(example)
Output:(example)
<pre>
<pre>
Line 417: Line 417:


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 PROGRAM "Guess.bas"
<syntaxhighlight lang="is-basic">100 PROGRAM "Guess.bas"
110 RANDOMIZE
110 RANDOMIZE
120 LET UP=10:LET LO=1 ! Limits
120 LET UP=10:LET LO=1 ! Limits
Line 433: Line 433:
240 PRINT "Well guessed! Numner of tips:";COUNT
240 PRINT "Well guessed! Numner of tips:";COUNT
250 END SELECT
250 END SELECT
260 LOOP UNTIL NR=GU</lang>
260 LOOP UNTIL NR=GU</syntaxhighlight>


==={{header|QB64}}===
==={{header|QB64}}===
Note that <code>INPUT</code> only allows the user to type things that can fit in the variable it's storing to. Since we're storing to a byte, we don't have to worry about the user typing any non-numbers.
Note that <code>INPUT</code> only allows the user to type things that can fit in the variable it's storing to. Since we're storing to a byte, we don't have to worry about the user typing any non-numbers.
<lang qbasic>DIM secretNumber AS _BYTE ' the secret number
<syntaxhighlight lang="qbasic">DIM secretNumber AS _BYTE ' the secret number
DIM guess AS _BYTE ' the player's guess
DIM guess AS _BYTE ' the player's guess


Line 456: Line 456:
END SELECT
END SELECT
LOOP UNTIL guess%% = secretNumber%%
LOOP UNTIL guess%% = secretNumber%%
PRINT "You won!"; secretNumber%%; "was the secret number!"</lang>
PRINT "You won!"; secretNumber%%; "was the secret number!"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 477: Line 477:


=={{header|Batch File}}==
=={{header|Batch File}}==
<lang dos>@echo off
<syntaxhighlight lang="dos">@echo off


:A
:A
Line 493: Line 493:
echo You won! The number was %number%
echo You won! The number was %number%
pause>nul
pause>nul
goto A</lang>
goto A</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic> Min% = 1
<syntaxhighlight lang="bbcbasic"> Min% = 1
Max% = 10
Max% = 10
chosen% = RND(Max%-Min%+1) + Min% - 1
chosen% = RND(Max%-Min%+1) + Min% - 1
Line 514: Line 514:
ENDCASE
ENDCASE
UNTIL FALSE
UNTIL FALSE
END</lang>
END</syntaxhighlight>


=={{header|BCPL}}==
=={{header|BCPL}}==
<lang bcpl>get "libhdr"
<syntaxhighlight lang="bcpl">get "libhdr"
static $( randstate = ? $)
static $( randstate = ? $)


Line 559: Line 559:
wrch('*N')
wrch('*N')
play(min, max, rand(min, max))
play(min, max, rand(min, max))
$)</lang>
$)</syntaxhighlight>
{{out}}
{{out}}
<pre>Guess the number
<pre>Guess the number
Line 587: Line 587:
The number range is hardcoded at the start of the program (<tt>1:"d"</tt> being 1 to 100), but can easily be changed.
The number range is hardcoded at the start of the program (<tt>1:"d"</tt> being 1 to 100), but can easily be changed.


<lang befunge>1:"d">>048*"neewteb rebmun a sseuG">:#,_$\:.\"d na",,\,,:.55+,\-88+0v
<syntaxhighlight lang="befunge">1:"d">>048*"neewteb rebmun a sseuG">:#,_$\:.\"d na",,\,,:.55+,\-88+0v
<*2\_$\1+%+48*">",,#v>#+:&#>#5-:!_0`00p0"hgih"00g>_0"wol"00g!>_48vv1?
<*2\_$\1+%+48*">",,#v>#+:&#>#5-:!_0`00p0"hgih"00g>_0"wol"00g!>_48vv1?
\1-:^v"d correctly!"<^,,\,+55,". >"$_,#!>#:<"Your guess was too"*<>+>
\1-:^v"d correctly!"<^,,\,+55,". >"$_,#!>#:<"Your guess was too"*<>+>
:#,_@>"ess" >"eug uoY"></lang>
:#,_@>"ess" >"eug uoY"></syntaxhighlight>


{{out}}
{{out}}
Line 604: Line 604:


=={{header|Brat}}==
=={{header|Brat}}==
<lang brat>number = random 10
<syntaxhighlight lang="brat">number = random 10


p "Guess a number between 1 and 10."
p "Guess a number between 1 and 10."
Line 620: Line 620:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdlib.h>
<syntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
#include <time.h>
#include <time.h>
Line 647: Line 647:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


Demonstration:
Demonstration:
Line 666: Line 666:


=={{header|C sharp}}==
=={{header|C sharp}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;


class Program
class Program
Line 705: Line 705:
}
}
}
}
</syntaxhighlight>
</lang>
Output:
Output:
<pre>The number is between 1 and 10. Make a guess: 1
<pre>The number is between 1 and 10. Make a guess: 1
Line 724: Line 724:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <cstdlib>
#include <cstdlib>
#include <ctime>
#include <ctime>
Line 751: Line 751:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>Enter lower limit: 1
<pre>Enter lower limit: 1
Line 771: Line 771:


=={{header|Caché ObjectScript}}==
=={{header|Caché ObjectScript}}==
<lang Caché ObjectScript>GUESSNUM
<syntaxhighlight lang="caché objectscript">GUESSNUM
; get a random number between 1 and 100
; get a random number between 1 and 100
set target = ($random(100) + 1) ; $r(100) gives 0-99
set target = ($random(100) + 1) ; $r(100) gives 0-99
Line 799: Line 799:
write !!,"You guessed the number in "_tries_" attempts."
write !!,"You guessed the number in "_tries_" attempts."
quit</lang>
quit</syntaxhighlight>


{{out}}<pre>SAMPLES>do ^GUESSNUM^
{{out}}<pre>SAMPLES>do ^GUESSNUM^
Line 824: Line 824:
In you module.ceylon file put import ceylon.random "1.3.1";
In you module.ceylon file put import ceylon.random "1.3.1";


<lang ceylon>import ceylon.random {
<syntaxhighlight lang="ceylon">import ceylon.random {
DefaultRandom
DefaultRandom
}
}
Line 860: Line 860:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(defn guess-run []
<syntaxhighlight lang="clojure">(defn guess-run []
(let [start 1
(let [start 1
end 100
end 100
Line 878: Line 878:
:else true)
:else true)
(println "Correct")
(println "Correct")
(recur (inc i)))))))</lang>
(recur (inc i)))))))</syntaxhighlight>


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>read_number = proc (prompt: string) returns (int)
<syntaxhighlight lang="clu">read_number = proc (prompt: string) returns (int)
po: stream := stream$primary_output()
po: stream := stream$primary_output()
pi: stream := stream$primary_input()
pi: stream := stream$primary_input()
Line 936: Line 936:
secret: int := min + random$next(max - min + 1)
secret: int := min + random$next(max - min + 1)
play_game(min, max, secret)
play_game(min, max, secret)
end start_up</lang>
end start_up</syntaxhighlight>
{{out}}
{{out}}
<pre>Guess the number
<pre>Guess the number
Line 959: Line 959:


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. Guess-With-Feedback.
PROGRAM-ID. Guess-With-Feedback.


Line 988: Line 988:
GOBACK
GOBACK
.</lang>
.</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun guess-the-number-feedback (&optional (min 1) (max 100))
<syntaxhighlight lang="lisp">(defun guess-the-number-feedback (&optional (min 1) (max 100))
(let ((num-guesses 0)
(let ((num-guesses 0)
(num (+ (random (1+ (- max min))) min))
(num (+ (random (1+ (- max min))) min))
Line 1,007: Line 1,007:
(= guess num)))
(= guess num)))
(format t "You got the number correct on the ~:r guess!~%" num-guesses)))
(format t "You got the number correct on the ~:r guess!~%" num-guesses)))
</syntaxhighlight>
</lang>
Output:
Output:
<pre>CL-USER> (guess-the-number-feedback 1 1024)
<pre>CL-USER> (guess-the-number-feedback 1 1024)
Line 1,032: Line 1,032:
=={{header|Crystal}}==
=={{header|Crystal}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang ruby>number = rand(1..10)
<syntaxhighlight lang="ruby">number = rand(1..10)


puts "Guess the number between 1 and 10"
puts "Guess the number between 1 and 10"
Line 1,050: Line 1,050:
puts "Please enter an integer."
puts "Please enter an integer."
end
end
end</lang>
end</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
{{trans|Python}}
{{trans|Python}}
<lang d>import std.stdio, std.random, std.typecons, std.conv, std.string,
<syntaxhighlight lang="d">import std.stdio, std.random, std.typecons, std.conv, std.string,
std.range;
std.range;


Line 1,084: Line 1,084:
writeln(answer < target ? " Too low." : " Too high.");
writeln(answer < target ? " Too low." : " Too high.");
}
}
}</lang>
}</syntaxhighlight>
Sample game:
Sample game:
<pre>Guess my target number that is between 1 and 100 (inclusive).
<pre>Guess my target number that is between 1 and 100 (inclusive).
Line 1,108: Line 1,108:


=={{header|DCL}}==
=={{header|DCL}}==
<lang DCL>$ rnd = f$extract( 21, 2, f$time() )
<syntaxhighlight lang="dcl">$ rnd = f$extract( 21, 2, f$time() )
$ count = 0
$ count = 0
$ loop:
$ loop:
Line 1,122: Line 1,122:
$ if guess .gt. rnd then $ write sys$output "too large"
$ if guess .gt. rnd then $ write sys$output "too large"
$ if guess .ne. rnd then $ goto loop
$ if guess .ne. rnd then $ goto loop
$ write sys$output "it only took you ", count, " guesses"</lang>
$ write sys$output "it only took you ", count, " guesses"</syntaxhighlight>
{{out}}
{{out}}
<pre>$ @guess
<pre>$ @guess
Line 1,144: Line 1,144:
=={{header|Delphi}}==
=={{header|Delphi}}==


<lang Delphi>program GuessTheNumber;
<syntaxhighlight lang="delphi">program GuessTheNumber;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 1,229: Line 1,229:


end.
end.
</syntaxhighlight>
</lang>


=={{header|EasyLang}}==
=={{header|EasyLang}}==
<lang>print "Guess a number between 1 and 100!"
<syntaxhighlight lang="text">print "Guess a number between 1 and 100!"
n = random 100 + 1
n = random 100 + 1
repeat
repeat
Line 1,246: Line 1,246:
until g = n
until g = n
.
.
print " is correct"</lang>
print " is correct"</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang lisp>
<syntaxhighlight lang="lisp">
;;(read <default-value> <prompt>) prompts the user with a default value using the browser dialog box.
;;(read <default-value> <prompt>) prompts the user with a default value using the browser dialog box.
;; we play sounds to make this look like an arcade game
;; we play sounds to make this look like an arcade game
Line 1,267: Line 1,267:
(play-sound 'ok )
(play-sound 'ok )
" 🔮 Well played!! 🍒 🍇 🍓")
" 🔮 Well played!! 🍒 🍇 🍓")
</syntaxhighlight>
</lang>


=={{header|Ela}}==
=={{header|Ela}}==


<lang ela>open string datetime random core monad io
<syntaxhighlight lang="ela">open string datetime random core monad io


guess () = do
guess () = do
Line 1,306: Line 1,306:
ask ()
ask ()


guess () ::: IO</lang>
guess () ::: IO</syntaxhighlight>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x :
ELENA 4.x :
<lang elena>import extensions;
<syntaxhighlight lang="elena">import extensions;
public program()
public program()
Line 1,335: Line 1,335:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,349: Line 1,349:
=={{header|Elixir}}==
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
{{works with|Elixir|1.2}}
<lang elixir>defmodule GuessingGame do
<syntaxhighlight lang="elixir">defmodule GuessingGame do
def play(lower, upper) do
def play(lower, upper) do
play(lower, upper, Enum.random(lower .. upper))
play(lower, upper, Enum.random(lower .. upper))
Line 1,368: Line 1,368:
end
end
GuessingGame.play(1, 100)</lang>
GuessingGame.play(1, 100)</syntaxhighlight>


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<lang Lisp>(let* ((min 1)
<syntaxhighlight lang="lisp">(let* ((min 1)
(max 100)
(max 100)
(number (+ (random (1+ (- max min))) min))
(number (+ (random (1+ (- max min))) min))
Line 1,385: Line 1,385:
((= guess number)
((= guess number)
(setq done t)
(setq done t)
(message "Well guessed!")))))</lang>
(message "Well guessed!")))))</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>% Implemented by Arjun Sunel
<syntaxhighlight lang="erlang">% Implemented by Arjun Sunel
-module(guess_number).
-module(guess_number).
-export([main/0]).
-export([main/0]).
Line 1,415: Line 1,415:
guess(N)
guess(N)
end.
end.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>1> c(guess_number).
<pre>1> c(guess_number).
Line 1,435: Line 1,435:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>include get.e
<syntaxhighlight lang="euphoria">include get.e


constant lower_limit = 0, upper_limit = 100
constant lower_limit = 0, upper_limit = 100
Line 1,453: Line 1,453:
puts(1,"You guessed to low.\nTry again: ")
puts(1,"You guessed to low.\nTry again: ")
end if
end if
end while</lang>
end while</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>
<syntaxhighlight lang="fsharp">
open System
open System


Line 1,487: Line 1,487:
0
0
</syntaxhighlight>
</lang>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING:
<syntaxhighlight lang="factor">USING:
formatting
formatting
fry
fry
Line 1,515: Line 1,515:
[ unparse "Number in range %s, your guess?\n" printf flush ]
[ unparse "Number in range %s, your guess?\n" printf flush ]
[ random '[ _ game-step ] loop ]
[ random '[ _ game-step ] loop ]
bi ;</lang>
bi ;</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==


<lang fantom>
<syntaxhighlight lang="fantom">
class Main
class Main
{
{
Line 1,556: Line 1,556:
}
}
}
}
</syntaxhighlight>
</lang>


Sample game:
Sample game:
Line 1,584: Line 1,584:


=={{header|FOCAL}}==
=={{header|FOCAL}}==
<lang FOCAL>01.01 S T=0
<syntaxhighlight lang="focal">01.01 S T=0
01.02 A "LOWER LIMIT",L
01.02 A "LOWER LIMIT",L
01.03 A "UPPER LIMIT",H
01.03 A "UPPER LIMIT",H
Line 1,598: Line 1,598:
01.16 T "TOO LOW!",!;G 1.1
01.16 T "TOO LOW!",!;G 1.1
01.17 T "CORRECT! GUESSES",%4,T,!;Q
01.17 T "CORRECT! GUESSES",%4,T,!;Q
01.18 T "TOO HIGH!",!;G 1.1</lang>
01.18 T "TOO HIGH!",!;G 1.1</syntaxhighlight>


{{out}}
{{out}}
Line 1,621: Line 1,621:
=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
{{works with|Fortran|95 and later}}
<lang fortran>program Guess_a_number
<syntaxhighlight lang="fortran">program Guess_a_number
implicit none
implicit none
Line 1,647: Line 1,647:
end if
end if
end do
end do
end program</lang>
end program</syntaxhighlight>
Output
Output
<pre>I have chosen a number bewteen 1 and 100 and you have to try to guess it.
<pre>I have chosen a number bewteen 1 and 100 and you have to try to guess it.
Line 1,665: Line 1,665:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Randomize
Randomize
Line 1,686: Line 1,686:
End If
End If
Loop
Loop
End</lang>
End</syntaxhighlight>


Sample input/output
Sample input/output
Line 1,702: Line 1,702:


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>// Guess a Number with feedback.
<syntaxhighlight lang="frink">// Guess a Number with feedback.
target = random[1,100] // Min and max are both inclusive for the random function
target = random[1,100] // Min and max are both inclusive for the random function
guess = 0
guess = 0
Line 1,722: Line 1,722:
println["$guess is correct! Well guessed!"]
println["$guess is correct! Well guessed!"]
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
Including an example with a non-integer entered.
Including an example with a non-integer entered.
Line 1,735: Line 1,735:


=={{header|Genie}}==
=={{header|Genie}}==
<lang genie>[indent=4]
<syntaxhighlight lang="genie">[indent=4]
/*
/*
Number guessing with feedback, in Genie
Number guessing with feedback, in Genie
Line 1,785: Line 1,785:
init
init
var game = new NumberGuessing(1, 100)
var game = new NumberGuessing(1, 100)
game.start()</lang>
game.start()</syntaxhighlight>


{{out}}
{{out}}
Line 1,823: Line 1,823:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,851: Line 1,851:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
Based on the Java implementation
Based on the Java implementation
<lang groovy>
<syntaxhighlight lang="groovy">
def rand = new Random() // java.util.Random
def rand = new Random() // java.util.Random
def range = 1..100 // Range (inclusive)
def range = 1..100 // Range (inclusive)
Line 1,876: Line 1,876:
}
}
}
}
</syntaxhighlight>
</lang>
Example:
Example:
<lang>
<syntaxhighlight lang="text">
The number is in 1..100
The number is in 1..100
Guess the number: ghfvkghj
Guess the number: ghfvkghj
Line 1,894: Line 1,894:
Guess the number: 92
Guess the number: 92
Your guess is spot on!
Your guess is spot on!
</syntaxhighlight>
</lang>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>
<syntaxhighlight lang="haskell">
import Control.Monad
import Control.Monad
import System.Random
import System.Random
Line 1,921: Line 1,921:
putStrLn "Try to guess my secret number between 1 and 100."
putStrLn "Try to guess my secret number between 1 and 100."
ask `until_` answerIs ans
ask `until_` answerIs ans
</syntaxhighlight>
</lang>


=={{header|HolyC}}==
=={{header|HolyC}}==
<lang holyc>U8 n, *g;
<syntaxhighlight lang="holyc">U8 n, *g;
U8 min = 1, max = 100;
U8 min = 1, max = 100;


Line 1,943: Line 1,943:
if (Str2I64(g) > n)
if (Str2I64(g) > n)
Print("Your guess was too high.\nTry again: ");
Print("Your guess was too high.\nTry again: ");
}</lang>
}</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==


<syntaxhighlight lang="icon">
<lang Icon>
procedure main()
procedure main()
smallest := 5
smallest := 5
Line 1,968: Line 1,968:
}
}
end
end
</syntaxhighlight>
</lang>


Output:
Output:
Line 1,986: Line 1,986:


=={{header|J}}==
=={{header|J}}==
<lang j>require 'misc'
<syntaxhighlight lang="j">require 'misc'
game=: verb define
game=: verb define
assert. y -: 1 >. <.{.y
assert. y -: 1 >. <.{.y
Line 1,996: Line 1,996:
smoutput (*x-n){::'You win.';'Too high.';'Too low.'
smoutput (*x-n){::'You win.';'Too high.';'Too low.'
end.
end.
)</lang>
)</syntaxhighlight>


Note: in computational contexts, J programmers typically avoid loops. However, in contexts which involve progressive input and output and where event handlers are too powerful (too complicated), loops are probably best practice.
Note: in computational contexts, J programmers typically avoid loops. However, in contexts which involve progressive input and output and where event handlers are too powerful (too complicated), loops are probably best practice.
Line 2,002: Line 2,002:
Example use:
Example use:


<lang> game 100
<syntaxhighlight lang="text"> game 100
Guess my integer, which is bounded by 1 and 100
Guess my integer, which is bounded by 1 and 100
Guess: 64
Guess: 64
Line 2,013: Line 2,013:
Too low.
Too low.
Guess: 44
Guess: 44
You win.</lang>
You win.</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang Java>import java.util.Random;
<syntaxhighlight lang="java">import java.util.Random;
import java.util.Scanner;
import java.util.Scanner;
public class Main
public class Main
Line 2,043: Line 2,043:
} while (guessedNumber != randomNumber);
} while (guessedNumber != randomNumber);
}
}
}</lang>
}</syntaxhighlight>
Demonstration:
Demonstration:
<pre>The number is between 1 and 100.
<pre>The number is between 1 and 100.
Line 2,060: Line 2,060:


=={{header|JavaScript}}==
=={{header|JavaScript}}==
<lang html4strict><p>Pick a number between 1 and 100.</p>
<syntaxhighlight lang="html4strict"><p>Pick a number between 1 and 100.</p>
<form id="guessNumber">
<form id="guessNumber">
<input type="text" name="guess">
<input type="text" name="guess">
Line 2,066: Line 2,066:
</form>
</form>
<p id="output"></p>
<p id="output"></p>
<script type="text/javascript"></lang>
<script type="text/javascript"></syntaxhighlight>
<lang javascript>var number = Math.ceil(Math.random() * 100);
<syntaxhighlight lang="javascript">var number = Math.ceil(Math.random() * 100);
function verify() {
function verify() {
Line 2,087: Line 2,087:
}
}


document.getElementById('guessNumber').onsubmit = verify;</lang>
document.getElementById('guessNumber').onsubmit = verify;</syntaxhighlight>
<lang html4strict></script></lang>
<syntaxhighlight lang="html4strict"></script></syntaxhighlight>


=== Spidermonkey Version ===
=== Spidermonkey Version ===
<lang javascript>#!/usr/bin/env js
<syntaxhighlight lang="javascript">#!/usr/bin/env js


function main() {
function main() {
Line 2,135: Line 2,135:


main();
main();
</syntaxhighlight>
</lang>


Example session:
Example session:
Line 2,155: Line 2,155:
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}


<lang julia>function guesswithfeedback(n::Integer)
<syntaxhighlight lang="julia">function guesswithfeedback(n::Integer)
number = rand(1:n)
number = rand(1:n)
print("I choose a number between 1 and $n\nYour guess? ")
print("I choose a number between 1 and $n\nYour guess? ")
Line 2,169: Line 2,169:
end
end


guesswithfeedback(10)</lang>
guesswithfeedback(10)</syntaxhighlight>


{{out}}
{{out}}
Line 2,181: Line 2,181:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang kotlin>import kotlin.random.Random
<syntaxhighlight lang="kotlin">import kotlin.random.Random


fun main() {
fun main() {
Line 2,196: Line 2,196:
}
}
}
}
}</lang>
}</syntaxhighlight>
Sample inout/output
Sample inout/output
{{out}}
{{out}}
Line 2,213: Line 2,213:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
<lang Scheme>
{def game
{def game


Line 2,235: Line 2,235:


{game {pow 2 32}} // 2**32 = 4294967296
{game {pow 2 32}} // 2**32 = 4294967296
</syntaxhighlight>
</lang>


Sample inout/output
Sample inout/output
Line 2,276: Line 2,276:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>#!/usr/bin/lasso9
<syntaxhighlight lang="lasso">#!/usr/bin/lasso9


local(
local(
Line 2,308: Line 2,308:
#status = true
#status = true
}
}
}</lang>
}</syntaxhighlight>


With range value 8 and 73. Correct number 13
With range value 8 and 73. Correct number 13
Line 2,324: Line 2,324:


=={{header|LFE}}==
=={{header|LFE}}==
<lang lisp>
<syntaxhighlight lang="lisp">
(defmodule guessing-game
(defmodule guessing-game
(export (main 0)))
(export (main 0)))
Line 2,346: Line 2,346:
(: random uniform 10)
(: random uniform 10)
(get-player-guess)))
(get-player-guess)))
</syntaxhighlight>
</lang>


From the LFE REPL (assuming the above code was saved in the file "guessing-game.lfe"):
From the LFE REPL (assuming the above code was saved in the file "guessing-game.lfe"):


<lang lisp>
<syntaxhighlight lang="lisp">
> (slurp '"guessing-game.lfe")
> (slurp '"guessing-game.lfe")
#(ok guessing-game)
#(ok guessing-game)
Line 2,365: Line 2,365:
ok
ok
>
>
</syntaxhighlight>
</lang>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
[start]
[start]
target = int( rnd( 1) * 100) +1
target = int( rnd( 1) * 100) +1
Line 2,385: Line 2,385:
if c >target then print " Your guess was too high."
if c >target then print " Your guess was too high."
wend
wend
</syntaxhighlight>
</lang>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
<lang LiveCode>command guessTheNumber lowN highN
<syntaxhighlight lang="livecode">command guessTheNumber lowN highN
local tNumber, tguess, tmin, tmax
local tNumber, tguess, tmin, tmax
if lowN is empty or lowN < 1 then
if lowN is empty or lowN < 1 then
Line 2,416: Line 2,416:
end if
end if
end repeat
end repeat
end guessTheNumber</lang>
end guessTheNumber</syntaxhighlight>
Test
Test
<lang LiveCode>command testGuessNumber
<syntaxhighlight lang="livecode">command testGuessNumber
guessTheNumber --defaults to 1-10
guessTheNumber --defaults to 1-10
guessTheNumber 9,12
guessTheNumber 9,12
end testGuessNumber</lang>
end testGuessNumber</syntaxhighlight>


=={{header|Locomotive Basic}}==
=={{header|Locomotive Basic}}==


<lang locobasic>10 CLS:RANDOMIZE TIME
<syntaxhighlight lang="locobasic">10 CLS:RANDOMIZE TIME
20 PRINT "Please specify lower and upper limits":guess=0
20 PRINT "Please specify lower and upper limits":guess=0
30 INPUT " (must be positive integers) :", first, last
30 INPUT " (must be positive integers) :", first, last
Line 2,437: Line 2,437:
110 INPUT "That's correct! Another game (y/n)? ", yn$
110 INPUT "That's correct! Another game (y/n)? ", yn$
120 IF yn$="y" THEN 20
120 IF yn$="y" THEN 20
</syntaxhighlight>
</lang>


Output:
Output:
Line 2,445: Line 2,445:
=={{header|Logo}}==
=={{header|Logo}}==
{{trans|UNIX Shell}}
{{trans|UNIX Shell}}
<lang logo>to guess [:max 100]
<syntaxhighlight lang="logo">to guess [:max 100]
local "number
local "number
make "number random :max
make "number random :max
Line 2,470: Line 2,470:
]
]
end
end
</syntaxhighlight>
</lang>


Sample run:<pre>? guess
Sample run:<pre>? guess
Line 2,487: Line 2,487:
=={{header|Lua}}==
=={{header|Lua}}==


<lang Lua>math.randomseed(os.time())
<syntaxhighlight lang="lua">math.randomseed(os.time())
me_win=false
me_win=false
my_number=math.random(1,10)
my_number=math.random(1,10)
Line 2,509: Line 2,509:
end
end
end
end
</syntaxhighlight>
</lang>


<pre>
<pre>
Line 2,527: Line 2,527:
=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
{{trans|BASIC256}}
{{trans|BASIC256}}
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module GuessNumber {
Module GuessNumber {
Read Min, Max
Read Min, Max
Line 2,555: Line 2,555:
}
}
GuessNumber 5, 15
GuessNumber 5, 15
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,561: Line 2,561:


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>GuessANumber := proc(low, high)
<syntaxhighlight lang="maple">GuessANumber := proc(low, high)
local number, input;
local number, input;
randomize():
randomize():
Line 2,577: Line 2,577:
end if;
end if;
end do:
end do:
end proc:</lang>
end proc:</syntaxhighlight>
<lang Maple>GuessANumber(2,5);</lang>
<syntaxhighlight lang="maple">GuessANumber(2,5);</syntaxhighlight>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang mathematica>guessnumber[min_, max_] :=
<syntaxhighlight lang="mathematica">guessnumber[min_, max_] :=
Module[{number = RandomInteger[{min, max}], guess},
Module[{number = RandomInteger[{min, max}], guess},
While[guess =!= number,
While[guess =!= number,
Line 2,590: Line 2,590:
ToString@max <> "."]]];
ToString@max <> "."]]];
CreateDialog[{"Well guessed!", DefaultButton[]}]];
CreateDialog[{"Well guessed!", DefaultButton[]}]];
guessnumber[1, 10]</lang>
guessnumber[1, 10]</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
{{untested|Octave}}
{{untested|Octave}}
Tested in MATLAB. Untested in Octave.
Tested in MATLAB. Untested in Octave.
<lang MATLAB>function guess_a_number(low, high)
<syntaxhighlight lang="matlab">function guess_a_number(low, high)


if nargin < 1 || ~isnumeric(low) || length(low) > 1 || isnan(low)
if nargin < 1 || ~isnumeric(low) || length(low) > 1 || isnan(low)
Line 2,620: Line 2,620:
gs = '';
gs = '';
end
end
end</lang>
end</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
<lang MAXScript>
Range = [1,100]
Range = [1,100]
randomNumber = (random Range.x Range.y) as integer
randomNumber = (random Range.x Range.y) as integer
Line 2,639: Line 2,639:
)
)
)
)
</syntaxhighlight>
</lang>


Output:
Output:
<syntaxhighlight lang="maxscript">
<lang MAXSCRIPT>
Enter a number between 1 and 100: 5
Enter a number between 1 and 100: 5
Too low!
Too low!
Line 2,656: Line 2,656:
Well guessed!
Well guessed!
OK
OK
</syntaxhighlight>
</lang>


=={{header|Mirah}}==
=={{header|Mirah}}==
<lang mirah>def getInput:int
<syntaxhighlight lang="mirah">def getInput:int
s = System.console.readLine()
s = System.console.readLine()
Integer.parseInt(s)
Integer.parseInt(s)
Line 2,684: Line 2,684:
puts "Please enter an integer."
puts "Please enter an integer."
end
end
end</lang>
end</syntaxhighlight>


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE guessf;
<syntaxhighlight lang="modula2">MODULE guessf;


IMPORT InOut, Random, NumConv, Strings;
IMPORT InOut, Random, NumConv, Strings;
Line 2,726: Line 2,726:
InOut.WriteString ("Thank you for playing; have a nice day!");
InOut.WriteString ("Thank you for playing; have a nice day!");
InOut.WriteLn
InOut.WriteLn
END guessf.</lang>
END guessf.</syntaxhighlight>
<pre>I have chosen a number below 1000; please try to guess it.
<pre>I have chosen a number below 1000; please try to guess it.
Enter your guess : 500
Enter your guess : 500
Line 2,741: Line 2,741:


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang Nanoquery>import Nanoquery.Util
<syntaxhighlight lang="nanoquery">import Nanoquery.Util


random = new(Random)
random = new(Random)
Line 2,777: Line 2,777:
end
end


println "\nThanks for playing."</lang>
println "\nThanks for playing."</syntaxhighlight>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>using System;
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using System.Console;


Line 2,806: Line 2,806:
} while (guess != secret)
} while (guess != secret)
}
}
}</lang>
}</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 2,871: Line 2,871:


return
return
</syntaxhighlight>
</lang>


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP>; guess-number-feedback.lsp
<syntaxhighlight lang="newlisp">; guess-number-feedback.lsp
; oofoe 2012-01-19
; oofoe 2012-01-19
; http://rosettacode.org/wiki/Guess_the_number/With_feedback
; http://rosettacode.org/wiki/Guess_the_number/With_feedback
Line 2,901: Line 2,901:
(println "\nWell guessed! Congratulations!")
(println "\nWell guessed! Congratulations!")


(exit)</lang>
(exit)</syntaxhighlight>


Sample output:
Sample output:
Line 2,919: Line 2,919:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import random, strutils
<syntaxhighlight lang="nim">import random, strutils


randomize()
randomize()
Line 2,941: Line 2,941:
else: echo " Ye-Haw!!"
else: echo " Ye-Haw!!"


echo "Thanks for playing."</lang>
echo "Thanks for playing."</syntaxhighlight>


=={{header|NS-HUBASIC}}==
=={{header|NS-HUBASIC}}==
<lang NS-HUBASIC>10 NUMBER=RND(10)+1
<syntaxhighlight lang="ns-hubasic">10 NUMBER=RND(10)+1
20 INPUT "I'M THINKING OF A NUMBER BETWEEN 1 AND 10. WHAT IS IT? ",GUESS
20 INPUT "I'M THINKING OF A NUMBER BETWEEN 1 AND 10. WHAT IS IT? ",GUESS
30 IF GUESS>NUMBER THEN PRINT "MY NUMBER IS LOWER THAN THAT.": GOTO 20
30 IF GUESS>NUMBER THEN PRINT "MY NUMBER IS LOWER THAN THAT.": GOTO 20
40 IF GUESS<NUMBER THEN PRINT "MY NUMBER IS HIGHER THAN THAT.": GOTO 20
40 IF GUESS<NUMBER THEN PRINT "MY NUMBER IS HIGHER THAN THAT.": GOTO 20
50 PRINT "THAT'S THE CORRECT NUMBER."</lang>
50 PRINT "THAT'S THE CORRECT NUMBER."</syntaxhighlight>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>use IO;
<syntaxhighlight lang="objeck">use IO;


bundle Default {
bundle Default {
Line 2,985: Line 2,985:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>let rec _read_int() =
<syntaxhighlight lang="ocaml">let rec _read_int() =
try read_int()
try read_int()
with _ ->
with _ ->
Line 3,023: Line 3,023:
loop ()
loop ()
in
in
loop ()</lang>
loop ()</syntaxhighlight>


Playing the game:
Playing the game:
Line 3,056: Line 3,056:


=={{header|Octave}}==
=={{header|Octave}}==
<lang Octave>function guess_a_number(low,high)
<syntaxhighlight lang="octave">function guess_a_number(low,high)
% Guess a number (with feedback)
% Guess a number (with feedback)
% http://rosettacode.org/wiki/Guess_the_number/With_feedback
% http://rosettacode.org/wiki/Guess_the_number/With_feedback
Line 3,082: Line 3,082:
end
end
end
end
disp('Well guessed!')</lang>
disp('Well guessed!')</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>import: console
<syntaxhighlight lang="oforth">import: console


: guessNumber(a, b)
: guessNumber(a, b)
Line 3,096: Line 3,096:
g n == ifTrue: [ "You found it !" .cr return ]
g n == ifTrue: [ "You found it !" .cr return ]
g n < ifTrue: [ "Less" ] else: [ "Greater" ] . "than the target" .cr
g n < ifTrue: [ "Less" ] else: [ "Greater" ] . "than the target" .cr
again ;</lang>
again ;</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
<syntaxhighlight lang="ol">
<lang ol>
(import (otus random!))
(import (otus random!))


Line 3,126: Line 3,126:
((= guess number)
((= guess number)
(print "Well guessed!")))))
(print "Well guessed!")))))
</syntaxhighlight>
</lang>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
Line 3,136: Line 3,136:
entering ? shows the number we are looking for
entering ? shows the number we are looking for
This program should, of course, also work with all other Rexxes
This program should, of course, also work with all other Rexxes
<syntaxhighlight lang="oorexx">
<lang ooRexx>
/*REXX program that plays the guessing (the number) game. */
/*REXX program that plays the guessing (the number) game. */
low=1 /*lower range for the guessing game.*/
low=1 /*lower range for the guessing game.*/
Line 3,193: Line 3,193:


ser: say; say '*** error ! ***'; say arg(1); say; return
ser: say; say '*** error ! ***'; say arg(1); say; return
</syntaxhighlight>
</lang>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>guess_the_number(N=10)={
<syntaxhighlight lang="parigp">guess_the_number(N=10)={
a=random(N);
a=random(N);
print("guess the number between 0 and "N);
print("guess the number between 0 and "N);
Line 3,210: Line 3,210:
);
);
print("You guessed it correctly")
print("You guessed it correctly")
};</lang>
};</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 3,216: Line 3,216:


=={{header|Perl}}==
=={{header|Perl}}==
<lang Perl>sub prompt {
<syntaxhighlight lang="perl">sub prompt {
my $prompt = shift;
my $prompt = shift;
while (1) {
while (1) {
Line 3,234: Line 3,234:
while ($_ = $tgt <=> prompt "Your guess");
while ($_ = $tgt <=> prompt "Your guess");


print "Correct! You guessed it after $tries tries.\n";</lang>
print "Correct! You guessed it after $tries tries.\n";</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Guess_the_number3.exw
-- demo\rosetta\Guess_the_number3.exw
Line 3,275: Line 3,275:
<span style="color: #7060A8;">IupClose</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;">if</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>
<syntaxhighlight lang="php">
<?php
<?php


Line 3,329: Line 3,329:
</body>
</body>
</html>
</html>
</syntaxhighlight>
</lang>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
{{trans|PureBasic}}
{{trans|PureBasic}}
<lang PicoLisp>(de guessTheNumber ()
<syntaxhighlight lang="picolisp">(de guessTheNumber ()
(use (Low High Guess)
(use (Low High Guess)
(until
(until
Line 3,351: Line 3,351:
"Your guess is too "
"Your guess is too "
(if (> Number Guess) "low" "high")
(if (> Number Guess) "low" "high")
"." ) ) ) ) )</lang>
"." ) ) ) ) )</syntaxhighlight>
Output:
Output:
<pre>: (guessTheNumber)
<pre>: (guessTheNumber)
Line 3,364: Line 3,364:


=={{header|Plain English}}==
=={{header|Plain English}}==
<lang plainenglish>The low number is 1.
<syntaxhighlight lang="plainenglish">The low number is 1.


The high number is 100.
The high number is 100.
Line 3,391: Line 3,391:
Convert the string to the number.
Convert the string to the number.
If the number is less than the low number, write " Guess can't be lower than " then the low number then "." on the console; repeat.
If the number is less than the low number, write " Guess can't be lower than " then the low number then "." on the console; repeat.
If the number is greater than the high number, write " Guess can't be higher than " then the high number then "." on the console; repeat.</lang>
If the number is greater than the high number, write " Guess can't be higher than " then the high number then "." on the console; repeat.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,419: Line 3,419:


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Get-Guess
function Get-Guess
{
{
Line 3,465: Line 3,465:


Write-Host ("The number was {0} and it took {1} guesses to find it." -f $answer.Number, $answer.Guesses.Count)
Write-Host ("The number was {0} and it took {1} guesses to find it." -f $answer.Number, $answer.Guesses.Count)
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,490: Line 3,490:
{{works with|SWI-Prolog|6}}
{{works with|SWI-Prolog|6}}


<lang prolog>main :-
<syntaxhighlight lang="prolog">main :-
play_guess_number.
play_guess_number.


Line 3,526: Line 3,526:
; Guess > N -> writeln('Your guess is too high.')
; Guess > N -> writeln('Your guess is too high.')
; Guess =:= N -> writeln("Correct!")
; Guess =:= N -> writeln("Correct!")
).</lang>
).</syntaxhighlight>




Input in the standard Prolog top level is terminated with a `.`: E.g.,
Input in the standard Prolog top level is terminated with a `.`: E.g.,


<lang prolog>?- main.
<syntaxhighlight lang="prolog">?- main.
Guess an integer between 1 and 10.
Guess an integer between 1 and 10.
Guess the number: a.
Guess the number: a.
Invalid input.
Invalid input.
Guess the number: 3.
Guess the number: 3.
Your guess is too low.</lang>
Your guess is too low.</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>OpenConsole()
<syntaxhighlight lang="purebasic">OpenConsole()


Repeat
Repeat
Line 3,558: Line 3,558:
PrintN("Your guess is to high.")
PrintN("Your guess is to high.")
EndIf
EndIf
ForEver</lang>
ForEver</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<lang python>import random
<syntaxhighlight lang="python">import random


inclusive_range = (1, 100)
inclusive_range = (1, 100)
Line 3,586: Line 3,586:
if answer > target: print(" Too high.")
if answer > target: print(" Too high.")


print("\nThanks for playing.")</lang>
print("\nThanks for playing.")</syntaxhighlight>


'''Sample Game'''
'''Sample Game'''
Line 3,623: Line 3,623:
=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> [ say "Guess the number (1-100 inclusive.)"
<syntaxhighlight lang="quackery"> [ say "Guess the number (1-100 inclusive.)"
cr cr
cr cr
100 random 1+
100 random 1+
Line 3,641: Line 3,641:
say "Well done! "
say "Well done! "
echo say " is correct. " cr
echo say " is correct. " cr
drop ] is guess-the-number ( --> )</lang>
drop ] is guess-the-number ( --> )</syntaxhighlight>


{{out}}
{{out}}
Line 3,675: Line 3,675:
This solution works on the assumption that the number to be found is an integer and also assumes that the upper and lower bounds are distinct integers used inclusively. For example, this means that low=4 and high=5 should be a solvable case, but low=high=4 will throw an error. See [[Talk:Guess the number/With feedback|Talk page]] entry dated 1st June 2020.
This solution works on the assumption that the number to be found is an integer and also assumes that the upper and lower bounds are distinct integers used inclusively. For example, this means that low=4 and high=5 should be a solvable case, but low=high=4 will throw an error. See [[Talk:Guess the number/With feedback|Talk page]] entry dated 1st June 2020.


<lang rsplus>guessANumber <- function(low, high)
<syntaxhighlight lang="rsplus">guessANumber <- function(low, high)
{
{
boundryErrorCheck(low, high)
boundryErrorCheck(low, high)
Line 3,707: Line 3,707:
while(!is.numeric(guess) || as.integer(guess) != guess){guess <- type.convert(readline("That wasn't an integer! Try again "))}
while(!is.numeric(guess) || as.integer(guess) != guess){guess <- type.convert(readline("That wasn't an integer! Try again "))}
as.integer(guess)
as.integer(guess)
}</lang>
}</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<lang Racket>#lang racket
<syntaxhighlight lang="racket">#lang racket


(define (guess-number min max)
(define (guess-number min max)
Line 3,728: Line 3,728:


(guess-number 1 100)
(guess-number 1 100)
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)


<lang perl6>my $maxnum = prompt("Hello, please give me an upper boundary: ");
<syntaxhighlight lang="raku" line>my $maxnum = prompt("Hello, please give me an upper boundary: ");
until 0 < $maxnum < Inf {
until 0 < $maxnum < Inf {
say "Oops! The upper boundary should be > 0 and not Inf";
say "Oops! The upper boundary should be > 0 and not Inf";
Line 3,755: Line 3,755:
}
}
}
}
say "Great you guessed right after $count attempts!";</lang>
say "Great you guessed right after $count attempts!";</syntaxhighlight>


<pre>Hello, please give me an upper boundary: 10
<pre>Hello, please give me an upper boundary: 10
Line 3,767: Line 3,767:


=={{header|Retro}}==
=={{header|Retro}}==
<lang Retro>: high|low ( gn-g$ )
<syntaxhighlight lang="retro">: high|low ( gn-g$ )
over > [ "high" ] [ "low" ] if ;
over > [ "high" ] [ "low" ] if ;


Line 3,782: Line 3,782:
think [ getToken toNumber checkGuess ] while
think [ getToken toNumber checkGuess ] while
"You got it!\n" puts ;
"You got it!\n" puts ;
</syntaxhighlight>
</lang>


=={{header|REXX}}==
=={{header|REXX}}==
To make the program more engaging, randomized words for the hint are used.
To make the program more engaging, randomized words for the hint are used.
<lang rexx>/*REXX program plays guess the number game with a human; the computer picks the number*/
<syntaxhighlight lang="rexx">/*REXX program plays guess the number game with a human; the computer picks the number*/
low= 1 /*the lower range for the guessing game*/
low= 1 /*the lower range for the guessing game*/
high= 100 /* " upper " " " " " */
high= 100 /* " upper " " " " " */
Line 3,820: Line 3,820:
/*stick a fork in it, we're all done. */
/*stick a fork in it, we're all done. */
if try==1 then say 'Gadzooks!!! You guessed the number right away!'
if try==1 then say 'Gadzooks!!! You guessed the number right away!'
else say 'Congratulations!, you guessed the number in ' try " tries."</lang>
else say 'Congratulations!, you guessed the number in ' try " tries."</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>fr = 1 t0 = 10
<syntaxhighlight lang="ring">fr = 1 t0 = 10
while true
while true
see "Hey There,
see "Hey There,
Line 3,853: Line 3,853:
d = random(e)
d = random(e)
if d >= s return d ok
if d >= s return d ok
end</lang>
end</syntaxhighlight>


=={{header|Ruby}}==
=={{header|Ruby}}==
{{trans|Mirah}}
{{trans|Mirah}}
<lang ruby>number = rand(1..10)
<syntaxhighlight lang="ruby">number = rand(1..10)


puts "Guess the number between 1 and 10"
puts "Guess the number between 1 and 10"
Line 3,875: Line 3,875:
puts "Please enter an integer."
puts "Please enter an integer."
end
end
end</lang>
end</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
{{libheader|rand}}
{{libheader|rand}}
<lang rust>use rand::Rng;
<syntaxhighlight lang="rust">use rand::Rng;
use std::cmp::Ordering;
use std::cmp::Ordering;
use std::io;
use std::io;
Line 3,916: Line 3,916:
}
}
}
}
}</lang>
}</syntaxhighlight>
<pre>I have chosen my number between 1 and 100. Guess the number!
<pre>I have chosen my number between 1 and 100. Guess the number!
Please input your guess.
Please input your guess.
Line 3,952: Line 3,952:


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>import java.util.Random
<syntaxhighlight lang="scala">import java.util.Random
import java.util.Scanner
import java.util.Scanner


Line 3,968: Line 3,968:
else if (guessedNumber < randomNumber) println("Your guess is too low!")
else if (guessedNumber < randomNumber) println("Your guess is too low!")
else println("You got it!")
else println("You got it!")
} while (guessedNumber != randomNumber)</lang>
} while (guessedNumber != randomNumber)</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
{{works with|Chicken Scheme}}
{{works with|Chicken Scheme}}
{{works with|Guile}}
{{works with|Guile}}
<lang scheme>(define maximum 5)
<syntaxhighlight lang="scheme">(define maximum 5)
(define minimum -5)
(define minimum -5)
(define number (+ (random (- (+ maximum 1) minimum)) minimum))
(define number (+ (random (- (+ maximum 1) minimum)) minimum))
Line 3,990: Line 3,990:
(if (< guess number)
(if (< guess number)
(display "Too low!\n> ")))))
(display "Too low!\n> ")))))
(display "Correct!\n")</lang>
(display "Correct!\n")</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
const integer: lower_limit is 0;
const integer: lower_limit is 0;
Line 4,019: Line 4,019:
writeln("You gave up!");
writeln("You gave up!");
end if;
end if;
end func;</lang>
end func;</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang ruby>var number = rand(1..10);
<syntaxhighlight lang="ruby">var number = rand(1..10);
say "Guess the number between 1 and 10";
say "Guess the number between 1 and 10";


Line 4,032: Line 4,032:
default { say "Too high" }
default { say "Too high" }
}
}
}</lang>
}</syntaxhighlight>


=={{header|Small Basic}}==
=={{header|Small Basic}}==
<lang Small Basic>number=Math.GetRandomNumber(10)
<syntaxhighlight lang="small basic">number=Math.GetRandomNumber(10)
TextWindow.WriteLine("I just thought of a number between 1 and 10. What is it?")
TextWindow.WriteLine("I just thought of a number between 1 and 10. What is it?")
While guess<>number
While guess<>number
Line 4,046: Line 4,046:
EndIf
EndIf
EndWhile
EndWhile
TextWindow.WriteLine("You win!")</lang>
TextWindow.WriteLine("You win!")</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
Line 4,056: Line 4,056:
To play: run "GuessingGame playFrom: 1 to: 100" on a Workspace (Tools -> Workspace)
To play: run "GuessingGame playFrom: 1 to: 100" on a Workspace (Tools -> Workspace)


<syntaxhighlight lang="smalltalk">
<lang Smalltalk>
'From Pharo7.0.3 of 12 April 2019 [Build information: Pharo-7.0.3+build.158.sha.0903ade8a6c96633f07e0a7f1baa9a5d48cfdf55 (64 Bit)] on 30 October 2019 at 4:24:17.115807 pm'!
'From Pharo7.0.3 of 12 April 2019 [Build information: Pharo-7.0.3+build.158.sha.0903ade8a6c96633f07e0a7f1baa9a5d48cfdf55 (64 Bit)] on 30 October 2019 at 4:24:17.115807 pm'!
Object subclass: #GuessingGame
Object subclass: #GuessingGame
Line 4,154: Line 4,154:
play! !
play! !


</syntaxhighlight>
</lang>


=={{header|Sparkling}}==
=={{header|Sparkling}}==
<lang sparkling>printf("Lower bound: ");
<syntaxhighlight lang="sparkling">printf("Lower bound: ");
let lowerBound = toint(getline());
let lowerBound = toint(getline());


Line 4,183: Line 4,183:
break;
break;
}
}
}</lang>
}</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang Swift>import Cocoa
<syntaxhighlight lang="swift">import Cocoa


var found = false
var found = false
Line 4,208: Line 4,208:
println("Good try but the number is less than that!")
println("Good try but the number is less than that!")
}
}
}</lang>
}</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>set from 1
<syntaxhighlight lang="tcl">set from 1
set to 10
set to 10
set target [expr {int(rand()*($to-$from+1) + $from)}]
set target [expr {int(rand()*($to-$from+1) + $from)}]
Line 4,230: Line 4,230:
break
break
}
}
}</lang>
}</syntaxhighlight>
Sample output:
Sample output:
<pre>
<pre>
Line 4,251: Line 4,251:


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
PRINT "Find the luckynumber (7 tries)!"
PRINT "Find the luckynumber (7 tries)!"
Line 4,272: Line 4,272:
IF (round==7) PRINT/ERROR "You've lost: luckynumber was: ",luckynumber
IF (round==7) PRINT/ERROR "You've lost: luckynumber was: ",luckynumber
ENDLOOP
ENDLOOP
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 4,299: Line 4,299:
{{works with|Public Domain Korn SHell}}
{{works with|Public Domain Korn SHell}}
{{works with|Z SHell}}
{{works with|Z SHell}}
<lang sh>function guess {
<syntaxhighlight lang="sh">function guess {
[[ -n $BASH_VERSION ]] && shopt -s extglob
[[ -n $BASH_VERSION ]] && shopt -s extglob
[[ -n $ZSH_VERSION ]] && set -o KSH_GLOB
[[ -n $ZSH_VERSION ]] && set -o KSH_GLOB
Line 4,324: Line 4,324:
fi
fi
done
done
}</lang>
}</syntaxhighlight>


Sample run:
Sample run:
Line 4,343: Line 4,343:
=={{header|Ursa}}==
=={{header|Ursa}}==
{{trans|Python}}
{{trans|Python}}
<lang ursa>decl int high low
<syntaxhighlight lang="ursa">decl int high low
set low 0
set low 0
set high 100
set high 100
Line 4,372: Line 4,372:
end while
end while


out endl "Thanks for playing." endl console</lang>
out endl "Thanks for playing." endl console</syntaxhighlight>


=={{header|Vala}}==
=={{header|Vala}}==
<lang vala>
<syntaxhighlight lang="vala">
void main(){
void main(){
const int from = 1;
const int from = 1;
Line 4,407: Line 4,407:
}//while
}//while
} // main
} // main
</syntaxhighlight>
</lang>


Shorter but no error checking
Shorter but no error checking
<lang vala>int main() {
<syntaxhighlight lang="vala">int main() {
int guess, x = Random.int_range(1, 10);
int guess, x = Random.int_range(1, 10);
stdout.printf("Make a guess (1-10): ");
stdout.printf("Make a guess (1-10): ");
Line 4,418: Line 4,418:
stdout.printf("Got it!\n");
stdout.printf("Got it!\n");
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|VBA Excel}}==
=={{header|VBA Excel}}==
The Application.InputBox display a message when input is inappropriate.
The Application.InputBox display a message when input is inappropriate.
<lang vb>Sub GuessTheNumberWithFeedback()
<syntaxhighlight lang="vb">Sub GuessTheNumberWithFeedback()
Dim Nbc&, Nbp&, m&, n&, c&
Dim Nbc&, Nbp&, m&, n&, c&


Line 4,439: Line 4,439:
Loop
Loop
MsgBox "Well guessed!" & vbCrLf & "You find : " & Nbc & " in " & c & " guesses!"
MsgBox "Well guessed!" & vbCrLf & "You find : " & Nbc & " in " & c & " guesses!"
End Sub</lang>
End Sub</syntaxhighlight>


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Dim max,min,secretnum,numtries,usernum
Dim max,min,secretnum,numtries,usernum
max=100
max=100
Line 4,469: Line 4,469:
End If
End If
Loop
Loop
</syntaxhighlight>
</lang>


=={{header|Vlang}}==
=={{header|Vlang}}==
{{trans|go}}
{{trans|go}}
<lang vlang>import rand.seed
<syntaxhighlight lang="vlang">import rand.seed
import rand
import rand
import os
import os
Line 4,496: Line 4,496:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|VTL-2}}==
=={{header|VTL-2}}==
<lang VTL2>10 ?="Minimum? ";
<syntaxhighlight lang="vtl2">10 ?="Minimum? ";
20 L=?
20 L=?
30 ?="Maximum? ";
30 ?="Maximum? ";
Line 4,522: Line 4,522:
220 ?="Correct!"
220 ?="Correct!"
230 ?="Tries: ";
230 ?="Tries: ";
240 ?=T</lang>
240 ?=T</syntaxhighlight>
{{out}}
{{out}}
<pre>Minimum? 10
<pre>Minimum? 10
Line 4,541: Line 4,541:


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>import "io" for Stdin, Stdout
<syntaxhighlight lang="ecmascript">import "io" for Stdin, Stdout
import "random" for Random
import "random" for Random


Line 4,561: Line 4,561:
break
break
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 4,586: Line 4,586:


=={{header|XLISP}}==
=={{header|XLISP}}==
<lang lisp>(defun guessing-game (a b)
<syntaxhighlight lang="lisp">(defun guessing-game (a b)
; minimum and maximum, to be supplied by the user
; minimum and maximum, to be supplied by the user
(defun prompt ()
(defun prompt ()
Line 4,611: Line 4,611:
(display ". Try to guess it!")
(display ". Try to guess it!")
(newline)
(newline)
(prompt))</lang>
(prompt))</syntaxhighlight>
{{out}}
{{out}}
<pre>[1] (guessing-game 19 36)
<pre>[1] (guessing-game 19 36)
Line 4,633: Line 4,633:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes;
<syntaxhighlight lang="xpl0">include c:\cxpl\codes;
int Lo, Hi, C, Guess, Number;
int Lo, Hi, C, Guess, Number;


Line 4,656: Line 4,656:
CrLf(0);
CrLf(0);
until Guess = Number;
until Guess = Number;
]</lang>
]</syntaxhighlight>


Example output:
Example output:
Line 4,674: Line 4,674:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>r:=(0).random(10)+1;
<syntaxhighlight lang="zkl">r:=(0).random(10)+1;
while(1){
while(1){
n:=ask("Num between 1 & 10: ");
n:=ask("Num between 1 & 10: ");
Line 4,680: Line 4,680:
if(n==r){ println("Well guessed!"); break; }
if(n==r){ println("Well guessed!"); break; }
println((n<r) and "small" or "big");
println((n<r) and "small" or "big");
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,697: Line 4,697:
=={{header|Zoomscript}}==
=={{header|Zoomscript}}==
For typing:
For typing:
<lang Zoomscript>var randnum
<syntaxhighlight lang="zoomscript">var randnum
var guess
var guess
randnum & random 1 10
randnum & random 1 10
Line 4,713: Line 4,713:
endif
endif
endwhile
endwhile
print "Correct number. You win!"</lang>
print "Correct number. You win!"</syntaxhighlight>


For importing:
For importing:
Line 4,720: Line 4,720:


=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
<lang zxbasic>ZX Spectrum Basic has no [[:Category:Conditional loops|conditional loop]] constructs, so we have to emulate them here using IF and GO TO.
<syntaxhighlight lang="zxbasic">ZX Spectrum Basic has no [[:Category:Conditional loops|conditional loop]] constructs, so we have to emulate them here using IF and GO TO.
1 LET n=INT (RND*10)+1
1 LET n=INT (RND*10)+1
2 INPUT "Guess a number that is between 1 and 10: ",g: IF g=n THEN PRINT "That's my number!": STOP
2 INPUT "Guess a number that is between 1 and 10: ",g: IF g=n THEN PRINT "That's my number!": STOP
3 IF g<n THEN PRINT "That guess is too low!": GO TO 2
3 IF g<n THEN PRINT "That guess is too low!": GO TO 2
4 IF g>n THEN PRINT "That guess is too high!": GO TO 2</lang>
4 IF g>n THEN PRINT "That guess is too high!": GO TO 2</syntaxhighlight>