Guess the number: Difference between revisions
→{{header|langur}}
Langurmonkey (talk | contribs) |
|||
(15 intermediate revisions by 10 users not shown) | |||
Line 22:
=={{header|11l}}==
{{trans|Python}}
<
V g = Int(input(‘Guess a number that's between 1 and 10: ’))
L t != g
g = Int(input(‘Guess again! ’))
print(‘That's right!’)</
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program guessNumber.s */
Line 137:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
=={{header|ABAP}}==
<
DATA prng TYPE REF TO cl_abap_random_int.
Line 165:
cl_demo_output=>display( |Well Done| ).
</syntaxhighlight>
=={{header|Action!}}==
<
BYTE x,n,min=[1],max=[10]
Line 182:
FI
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Guess_the_number.png Screenshot from Atari 8-bit computer]
Line 200:
=={{header|Ada}}==
<
with Ada.Text_IO;
procedure Guess_Number is
Line 291:
New_Line;
end main;</
=={{header|Aime}}==
<
integer n;
text s;
Line 314:
}
o_text("You have won!\n");</
=={{header|ALGOL 68}}==
Line 321:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
<
(
INT n;
Line 339:
break:
puts("You have won! ")
)</
Sample output:
<pre>
Line 356:
=={{header|AppleScript}}==
<
-- define the number to be guessed
set numberToGuess to (random number from 1 to 10)
Line 380:
end if
end repeat
end run</
Or, constraining mutation, and abstracting a little to an '''until(predicate, function, value)''' pattern
<
on run
Line 459:
end tell
return v
end |until|</
=={{header|Arturo}}==
<
while [notEqual? to :integer input "Guess the number: " n] [
Line 468:
]
print "Well guessed!"</
{{out}}
Line 484:
=={{header|AutoHotkey}}==
<
msgbox I am thinking of a number between 1 and 10.
Line 498:
Msgbox Try again.
}
</syntaxhighlight>
=={{header|AutoIt}}==
<
$irnd = Random(1, 10, 1)
$iinput = -1
Line 508:
WEnd
MsgBox(0, "Success", "Well guessed!")
</syntaxhighlight>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f GUESS_THE_NUMBER.AWK
BEGIN {
Line 531:
exit(0)
}
</syntaxhighlight>
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<
20 PRINT "A NUMBER FROM 1 ";
30 PRINT "TO 10 HAS BEEN ";
Line 544:
70 Q = G% = N%
80 NEXT
90 PRINT "WELL GUESSED!"</
==={{header|Commodore BASIC}}===
Line 550:
For the most part, identical to the Applesoft BASIC example above, except that Commodore BASIC evaluates TRUE as a value of -1 instead of 1.
<
20 print chr$(147);chr$(14)
30 print "I have chosen a number from 1 to 10."
Line 558:
70 q = g% = n%
80 next
90 print "WELL GUESSED!"</
{{out}}
Line 573:
==={{header|IS-BASIC}}===
<
110 RANDOMIZE
120 LET N=RND(10)+1
Line 579:
140 INPUT PROMPT "Guess a number that's between 1-10: ":G
150 LOOP UNTIL N=G
160 PRINT "Well guessed!"</
==={{header|QBasic}}, Gives Hints===
<
GOSUB initialize
GOSUB guessing
Line 618:
STOP
END IF
WEND</
===
A more polished version of this program in QBasic/QB/VB-DOS
<
' OPTION EXPLICIT ' Remove remark for VB-DOS/PDS 7.1
'dIM
Line 672:
END FUNCTION
</syntaxhighlight>
==={{header|QB64}}===
The following is a modification of the above polished version in QBasic with explanations of differences.
<
'although it could be placed anywhere prior to the Rnd() function being called.
Line 719:
Print
Print "End of the program. Thanks for playing."
End</
===QB64 Alternative Version, Gives Hints===
Single-line "Guess the Number" program QBasic QB64 from Russia
<syntaxhighlight lang="qbasic">
1 IF Russia = 0 THEN Russia = 2222: RANDOMIZE TIMER: num = INT(RND * 100) + 1: GOTO 1 ELSE IF Russia <> 0 THEN INPUT n: IF n < num THEN PRINT "MORE": GOTO 1 ELSE IF n > num THEN PRINT "less": GOTO 1 ELSE IF n = num THEN PRINT "da": END ELSE GOTO 1 'DANILIN Russia 9-9-2019 guessnum.bas
</syntaxhighlight>
The multi-line equivalent of the above.
<
1 If c% = 0 Then
c% = 1
Line 754 ⟶ 745:
End
End If
End If</
===QB64 Expanded Range, Auto-Interactive===
<b>Note:</b> This is off-task, as there is no user interaction.<br/><br/>
<syntaxhighlight lang="qbasic">
h1=0: h2=10^
human = Int(Rnd*h2) 'human DANILIN
comp = Int(Rnd*h2) 'comp
Line 776 ⟶ 767:
Print " win by "; t; " steps": f=1
End If: End If: End If: t = t + 1
Wend: End</
{{out}}
<pre>1 40 11 MORE
Line 786 ⟶ 777:
7 40 39 MORE
8 40 40 win by 8 steps</pre>
==={{header|ZX Spectrum Basic}}===
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">10 LET n=INT (RND*10)+1
20 INPUT "Guess a number that's between 1 and 10: ",g
30 IF g=n THEN PRINT "That's my number!": STOP
40 PRINT "Guess again!"
50 GO TO 20</syntaxhighlight>
=={{header|BASIC256}}==
<
print "I am thinking of a number from 1 to 10"
do
Line 796 ⟶ 795:
endif
until g = n
print "Yea! You guessed my number."</
=={{header|Batch File}}==
At the line set /a answer=%random%%%(10-1+1)+1, if you want to change the minimum and maximum numbers, change all number ones (not counting the one that is in 10) to your desired chosen number and for the maximum, which is 10, do the same, but for maximum (eg. the minimum could be 123 and the maximum could be 321, etc.).<
set /a answer=%random%%%(10-1+1)+1
set /p guess=Pick a number between 1 and 10:
Line 805 ⟶ 804:
if %guess%==%answer% (echo Well guessed!
pause) else (set /p guess=Nope, guess again:
goto loop)</
=={{header|BBC BASIC}}==
<
REPEAT
INPUT "Guess a number between 1 and 10: " guess%
Line 817 ⟶ 816:
PRINT "Sorry, try again"
ENDIF
UNTIL FALSE</
=={{header|Befunge}}==
Line 823 ⟶ 822:
{{works with|Fungus|0.28}}
{{works with|CCBI|2.1}}
<
> v ,,,,,,<
v?v ,
Line 840 ⟶ 839:
+>,,,,,,,,,,,,,,,,^
>>>>>>>>>v^"guessthenumber!"+19<
RNG unit > 22p ^</
=={{header|Bracmat}}==
The value is generated by the <code>clk</code> function, which returns a (probably) non-integral rational number. The <code>den</code> function retrieves the denominators of this number. The rational number, multiplied by its denominator, becomes an natural number.
<
= mynumber
. clk$:?mynumber
Line 855 ⟶ 854:
)
& GuessTheNumber$
);</
=={{header|Brat}}==
<
p "Guess a number between 1 and 10."
Line 866 ⟶ 865:
{ p "Well guessed!"; true }
{ p "Guess again!" }
}</
=={{header|C}}==
<
#include <stdio.h>
#include <time.h>
Line 899 ⟶ 898:
puts("That's not my number. Try another guess:");
}
}</
=={{header|C sharp}}==
<
class GuessTheNumberGame
Line 920 ⟶ 919:
Console.WriteLine("Congrats!! You guessed right!");
}
};</
===Expanded Range, Auto-Interactive===
<b>Note:</b> This is off-task, as there is no user interaction.<br/><br/>
Program from Russia guesses 1 out of a billion<br/>
https://rextester.com/DYVZM84267
<syntaxhighlight lang="csharp">using System; using System.Text; //daMilliard.cs
namespace DANILIN
{ class Program
{ static void Main(string[] args)
{ Random rand = new Random();int t=0;
int h2=100000000; int h1=0; int f=0;
int comp = rand.Next(h2);
int human = rand.Next(h2);
while (f<1)
{ Console.WriteLine();Console.Write(t);
Console.Write(" ");Console.Write(comp);
Console.Write(" ");Console.Write(human);
if(comp < human)
{ Console.Write(" MORE");
int a=comp; comp=(comp+h2)/2; h1=a; }
else if(comp > human)
{ Console.Write(" less");
int a=comp; comp=(h1+comp)/2; h2=a;}
else {Console.Write(" win by ");
Console.Write(t); Console.Write(" steps");f=1;}
t++; }}}}</syntaxhighlight>
{{out}}
<pre>1 40 11 MORE
2 40 55 less
3 40 33 MORE
4 40 44 less
5 40 38 MORE
6 40 41 less
7 40 39 MORE
8 40 40 win by 8 steps</pre>
=={{header|C++}}==
<
#include <cstdlib>
#include <ctime>
Line 946 ⟶ 986:
}
</syntaxhighlight>
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
(def target (inc (rand-int 10))
Line 960 ⟶ 1,000:
(println "Try again")
(recur (inc n))))))
</syntaxhighlight>
=={{header|COBOL}}==
<
PROGRAM-ID. Guess-The-Number.
Line 987 ⟶ 1,027:
GOBACK
.</
=={{header|CoffeeScript}}==
<
guess = prompt "Guess the number. (1-10)"
while parseInt(guess) isnt num
guess = prompt "YOU LOSE! Guess again. (1-10)"
alert "Well guessed!"</
{{works_with|node.js}}
<
# This shows how to do simple REPL-like I/O in node.js.
readline = require "readline"
Line 1,018 ⟶ 1,058:
guess()
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(format t "Try to guess a number from 1 to ~a!~%Guess? " max)
(loop with num = (1+ (random max))
Line 1,030 ⟶ 1,070:
(force-output)
finally (format t "Well guessed! You took ~a ~:*~[~;try~:;tries~].~%" num-guesses)))
</syntaxhighlight>
Output:
<pre>CL-USER> (guess-the-number 10)
Line 1,045 ⟶ 1,085:
=={{header|Crystal}}==
{{trans|Ruby}}
<
puts "Guess the number: 1..10"
until gets.to_s.to_i == n; puts "Wrong! Guess again: " end
puts "Well guessed!"</
=={{header|D}}==
<syntaxhighlight lang="d">
void main() {
immutable num = uniform(1, 10).text;
Line 1,059 ⟶ 1,099:
writeln("Yep, you guessed my ", num);
}</
{{out}}
<pre>What's next guess (1 - 9)? 1
Line 1,068 ⟶ 1,108:
=={{header|Dart}}==
{{Trans|Kotlin}}
<
import 'dart:io';
Line 1,076 ⟶ 1,116:
do { stdout.write(" Your guess : "); } while (n != stdin.readLineSync());
print("\nWell guessed!");
}</
=={{header|DCL}}==
<
$ number = f$extract( f$length( time ) - 1, 1, time ) + 1
$ loop:
$ inquire guess "enter a guess (integer 1-10) "
$ if guess .nes. number then $ goto loop
$ write sys$output "Well guessed!"</
{{out}}
<pre>$ @guess_the_number
Line 1,095 ⟶ 1,135:
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 1,114 ⟶ 1,154:
Writeln('Congratulations' ) ;
end.
</syntaxhighlight>
=={{header|Déjà Vu}}==
<
while true:
Line 1,124 ⟶ 1,164:
return
else:
!print "Nope, try again."</
=={{header|EasyLang}}==
<syntaxhighlight>
n = randint 10
write "Guess a number between 1 and 10: "
repeat
Line 1,136 ⟶ 1,177:
write "try again: "
.
print " is correct. Well guessed!"
</syntaxhighlight>
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
class
APPLICATION
Line 1,166 ⟶ 1,208:
end
</syntaxhighlight>
The code above is simplified if we create a RANDOMIZER, which simplifies reuse (e.g. the code in RANDOMIZER does not have to be recreated for each need of a random number).
<syntaxhighlight lang="eiffel">
class
RANDOMIZER
Line 1,211 ⟶ 1,253:
end
</syntaxhighlight>
{{out}}
<pre>
Line 1,227 ⟶ 1,269:
=={{header|Elena}}==
ELENA
<
public program()
{
int randomNumber := randomGenerator.
console.printLine("I'm thinking of a number between 1 and 10. Can you guess it?");
bool numberCorrect := false;
Line 1,249 ⟶ 1,291:
}
}
}</
{{out}}
<pre>
Line 1,263 ⟶ 1,305:
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
<
def play do
play(Enum.random(1..10))
Line 1,283 ⟶ 1,325:
end
GuessingGame.play</
=={{header|Emacs Lisp}}==
<
(while (not (= (read-number "Guess the number ") number))
(message "Wrong, try again."))
(message "Well guessed! %d" number))</
=={{header|Erlang}}==
<
-module(guess_the_number).
-export([main/0]).
Line 1,310 ⟶ 1,352:
guess(N)
end.
</syntaxhighlight>
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM GUESS_NUMBER
Line 1,343 ⟶ 1,385:
END WHILE
END PROGRAM
</syntaxhighlight>
Note: Adapted from Qbasic version.
=={{header|Euphoria}}==
{{trans|ZX_Spectrum_Basic}}
<
integer n,g
Line 1,364 ⟶ 1,406:
end while
puts(1,"Well done! You guessed it.")</
=={{header|Factor}}==
<
USING: io random math math.parser kernel formatting ;
IN: guess-the-number
Line 1,389 ⟶ 1,431:
gen-number play-game
"Yes, the number was %d!\n" printf ;
</syntaxhighlight>
=={{header|Fantom}}==
<
class Main
{
Line 1,414 ⟶ 1,456:
}
}
</syntaxhighlight>
=={{header|Forth}}==
<syntaxhighlight lang="forth">
\ tested with GForth 0.7.0
: RND ( -- n) TIME&DATE 2DROP 2DROP DROP 10 MOD ; \ crude random number
Line 1,429 ⟶ 1,471:
CR ." Yes it was " .
CR ." Good guess!" ;
</syntaxhighlight>
=={{header|Fortran}}==
<
implicit none
Line 1,467 ⟶ 1,509:
end program guess_the_number
</syntaxhighlight>
=={{header|FreeBASIC}}==
<
Randomize
Line 1,483 ⟶ 1,525:
End
End If
Loop</
{{out}}
Line 1,500 ⟶ 1,542:
=={{header|Frink}}==
<
target = random[1,10] // Min and max are both inclusive for the random function
guess = 0
Line 1,513 ⟶ 1,555:
guess == target ? println["$guess is correct. Well guessed!"] : println["$guess is not correct. Guess again!"]
}
</syntaxhighlight>
{{out}}
Including an example with a non-integer entered.
Line 1,525 ⟶ 1,567:
7 is correct. Well guessed!
</pre>
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
void local fn BuildWindow
window 1, @"Guess the number (1-10)", (0,0,480,270), NSWindowStyleMaskTitled
textfield 1,,, (220,124,40,21)
ControlSetAlignment( 1, NSTextAlignmentCenter )
WindowMakeFirstResponder( 1, 1 )
AppSetProperty( @"Number", @(rnd(10)) )
end fn
void local fn DoDialog( ev as long, tag as long )
select ( ev )
case _btnClick
select ( tag )
case 1
if ( fn ControlIntegerValue( 1 ) == fn NumberIntegerValue( fn AppProperty( @"Number" ) ) )
alert 1,, @"Well guessed!",, @"Exit"
end
else
textfield 1,, @""
alert 1,, @"Wrong number!",, @"Try again"
end if
end select
end select
end fn
fn BuildWindow
on dialog fn DoDialog
HandleEvents
</syntaxhighlight>
=={{header|Gambas}}==
<
Dim byGuess, byGos As Byte
Dim byNo As Byte = Rand(1, 10)
Line 1,541 ⟶ 1,616:
Me.Close
End</
=={{header|GML}}==
<
n = irandom_range(1,10);
show_message("I'm thinking of a number from 1 to 10");
Line 1,552 ⟶ 1,627:
g = get_integer("I'm sorry "+g+" is not my number, try again. Please enter guess", 1);
}
show_message("Well guessed!");</
=={{header|Go}}==
<
import (
Line 1,577 ⟶ 1,652:
}
}
}</
=={{header|Groovy}}==
<
def random = new Random()
def keyboard = new Scanner(System.in)
Line 1,591 ⟶ 1,666:
}
println "Hurray! You guessed correctly!"
</syntaxhighlight>
=={{header|GW-BASIC}}==
<
20 PRINT "Guess the number between 1 and 10."
30 WHILE N<>G
40 INPUT "Your guess? ",G
50 WEND
60 PRINT "That's correct!"</
=={{header|Haskell}}==
<
import Control.Monad
import System.Random
Line 1,619 ⟶ 1,694:
putStrLn "Try to guess my secret number between 1 and 10."
ask `until_` answerIs ans
</syntaxhighlight>
Simple version:
<
import System.Random
Line 1,634 ⟶ 1,709:
then putStrLn "You got it!"
else putStrLn "Nope. Guess again." >> gameloop r
</syntaxhighlight>
=={{header|HolyC}}==
<
n = 1 + RandU16 % 10;
Line 1,654 ⟶ 1,729:
Print("That's not my number. Try another guess:\n");
}</
=={{header|Icon}} and {{header|Unicon}}==
Line 1,660 ⟶ 1,735:
This solution works in both languages.
<
n := ?10
repeat {
Line 1,667 ⟶ 1,742:
}
write("Well guessed!")
end</
=={{header|J}}==
<
game=: verb define
n=: 1 + ?10
Line 1,679 ⟶ 1,754:
smoutput (guess=n){::'no.';'Well guessed!'
end.
)</
Example session:
<syntaxhighlight lang="text"> game''
Guess my integer, which is bounded by 1 and 10
Guess: 1
no.
Guess: 2
Well guessed!</
=={{header|Java}}==
{{works with|Java|6+}}
<
public static void main(String[] args) throws NumberFormatException{
int n = (int)(Math.random() * 10 + 1);
Line 1,701 ⟶ 1,776:
System.out.println("Well guessed!");
}
}</
For pre-Java 6, use a <code>Scanner</code> or <code>BufferedReader</code> for input instead of <code>System.console()</code> (see [[Input loop#Java]]).
=={{header|JavaScript}}==
<
function guessNumber() {
// Get a random integer from 1 to 10 inclusive
Line 1,717 ⟶ 1,792:
}
guessNumber();</
Requires a host environment that supports <code>prompt</code> and <code>alert</code> such as a browser.
Line 1,725 ⟶ 1,800:
jq currently does not have a built-in random number generator, so a suitable PRNG for this task is defined below. Once `rand(n)` has been defined, the task can be accomplished as follows:
<syntaxhighlight lang="jq">
{prompt: "Please enter your guess:", random: (1+rand(9)) }
| ( (while( .guess != .random; .guess = (input|tonumber) ) | .prompt),
"Well done!"</
'''Invocation'''
Line 1,737 ⟶ 1,812:
'''PRNG'''
<
# as rand() from the Microsoft C Runtime.
# Input: [ count, state, random ]
Line 1,751 ⟶ 1,826:
# A random integer in [0 ... (n-1)]:
def rand(n): n * (rand_Microsoft($seed|tonumber) / 32768) | trunc;</
=={{header|Jsish}}==
From Javascript entry.
<
// Get a random integer from 1 to 10 inclusive
var num = Math.ceil(Math.random() * 10);
Line 1,788 ⟶ 1,863:
The number was 2 it took 3 tries
=!EXPECTEND!=
*/</
{{out}}
Line 1,797 ⟶ 1,872:
{{works with|Julia|0.6}}
<
number = dec(rand(1:10))
print("Guess my number! ")
Line 1,806 ⟶ 1,881:
end
guess()</
{{out}}
Line 1,822 ⟶ 1,897:
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 1,829 ⟶ 1,904:
do { print(" Your guess : ") } while (n != readLine())
println("\nWell guessed!")
}</
Sample input/output:
{{out}}
Line 1,845 ⟶ 1,920:
=={{header|langur}}==
<
val .n =
for {
val .guess = read ">> ", RE/^0*(?:[1-9]|10)(?:\.0+)?$/, "bad data\n", 7,
if .guess ==
writeln "too much bad data"
break
Line 1,859 ⟶ 1,934:
}
writeln "not it"
}</
{{out}}
Line 1,877 ⟶ 1,952:
===Command Line===
The following example works when Lasso is called from a command line
<
number = integer_random(10, 1),
status = false,
Line 1,904 ⟶ 1,979:
}
}</
===Web form===
The following example is a web page form
<
local(
Line 1,948 ⟶ 2,023:
[/if]
</body>
</html></
=={{header|LFE}}==
<
(defmodule guessing-game
(export (main 0)))
Line 1,972 ⟶ 2,047:
(: random uniform 10)
(get-player-guess)))
</syntaxhighlight>
From the LFE REPL (assuming the above code was saved in the file "guessing-game.lfe"):
<
> (slurp '"guessing-game.lfe")
#(ok guessing-game)
Line 1,984 ⟶ 2,059:
Well-guessed!!
ok
</syntaxhighlight>
=={{header|Liberty BASIC}}==
<
input "Guess the number I'm thinking of between 1 and 10. "; guess
while guess <> number
input "Incorrect! Try again! "; guess
wend
print "Congratulations, well guessed! The number was "; number;"."</
=={{header|LiveCode}}==
<
local tNumber, tguess
put random(10) into tNumber
Line 2,009 ⟶ 2,084:
end if
end repeat
end guessTheNumber</
=={{header|Locomotive Basic}}==
<
20 PRINT "Guess the number between 1 and 10."
30 WHILE num<>guess
40 INPUT "Your guess? ", guess
50 WEND
60 PRINT "That's correct!"</
=={{header|LOLCODE}}==
There is no native support for random numbers. This solution uses a simple linear congruential generator to simulate them, with the lamentable restriction that the user must first be prompted for a seed.
<
VISIBLE "SEED ME, FEMUR! "!
Line 2,044 ⟶ 2,119:
IM OUTTA YR guesser
KTHXBYE</
=={{header|Lua}}==
<
n = math.random( 1, 10 )
Line 2,060 ⟶ 2,135:
print "Guess again: "
end
until x == n</
=={{header|M2000 Interpreter}}==
A copy from QBASIC, write blocks { } where needed, We use GOSUB and GOTO in a Module.
<syntaxhighlight lang="m2000 interpreter">
Module QBASIC_Based {
supervisor:
Line 2,108 ⟶ 2,183:
}
QBASIC_Based
</syntaxhighlight>
=={{header|Maple}}==
<
local number;
randomize():
Line 2,121 ⟶ 2,196:
end do:
printf("Well guessed! The answer was %d.\n", number);
end proc:</
<syntaxhighlight lang
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
While[guess =!= number, guess = Input["Guess my number"]];
Print["Well guessed!"]</
=={{header|MATLAB}}==
<
[guess, status] = str2num(input('Guess a number between 1 and 10: ','s'));
Line 2,136 ⟶ 2,211:
[guess, status] = str2num(input('Guess again: ','s'));
end
disp('Well guessed!')</
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
rand = random 1 10
clearListener()
Line 2,148 ⟶ 2,223:
format "\nChoose another value\n"
)
</syntaxhighlight>
=={{header|Mercury}}==
Mercury does have a 'time' module in its standard library, but it offers an abstract type instead of the seconds-since-the-epoch we want to seed the RNG with. So this is also an example of how easy it is to call out to C. (It's just as easy to call out to C#, Java, and Erlang.) Also, rather than parse the input, this solution prepares the random number to match the typed input. This isn't a weakness of Mercury, just the author's desire to cheat a bit.
<
:- interface.
:- import_module io.
Line 2,185 ⟶ 2,260:
:- pragma foreign_proc("C", time(Int::out, _IO0::di, _IO1::uo),
[will_not_call_mercury, promise_pure],
"Int = time(NULL);").</
=={{header|min}}==
{{works with|min|0.19.6}}
<
9 random succ
Line 2,197 ⟶ 2,272:
("Your guess" ask int over ==) 'pop ("Wrong." puts!) () linrec
"Well guessed!" puts!</
=={{header|MiniScript}}==
<
while true
x = val(input("Your guess?"))
Line 2,207 ⟶ 2,282:
break
end if
end while</
=={{header|MIPS Assembly}}==
<
# WRITTEN: August 26, 2016 (at midnight...)
Line 2,267 ⟶ 2,342:
syscall
jr $ra
</syntaxhighlight>
=={{header|Nanoquery}}==
{{trans|Ursa}}
<
target = random.getInt(9) + 1
guess = 0
Line 2,280 ⟶ 2,355:
end
println "That's right!"</
=={{header|Nemerle}}==
<
using System.Console;
Line 2,302 ⟶ 2,377:
WriteLine("Well guessed!");
}
}</
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols nobinary
Line 2,328 ⟶ 2,403:
return
</syntaxhighlight>
=={{header|NewLISP}}==
<
; oofoe 2012-01-19
; http://rosettacode.org/wiki/Guess_the_number
Line 2,343 ⟶ 2,418:
(println "Well guessed! Congratulations!")
(exit)</
Sample output:
Line 2,356 ⟶ 2,431:
=={{header|Nim}}==
<
randomize()
Line 2,368 ⟶ 2,443:
guess = parseInt(readLine(stdin))
echo "Well guessed!"</
=={{header|NS-HUBASIC}}==
<
20 INPUT "I'M THINKING OF A NUMBER BETWEEN 1 AND 10. WHAT IS IT? ",GUESS
30 IF GUESS<>NUMBER THEN PRINT "INCORRECT GUESS. TRY AGAIN.": GOTO 20
40 PRINT "CORRECT NUMBER."</
=={{header|Oberon-2}}==
Works with oo2c Version 2
<
MODULE GuessTheNumber;
IMPORT
Line 2,403 ⟶ 2,478:
Do;
END GuessTheNumber.
</syntaxhighlight>
=={{header|Objeck}}==
<
use IO;
Line 2,436 ⟶ 2,511:
}
}
</syntaxhighlight>
=={{header|Objective-C}}==
<
#import <Foundation/Foundation.h>
Line 2,480 ⟶ 2,555:
return 0;
}
</syntaxhighlight>
=={{header|OCaml}}==
<
let () =
Line 2,500 ⟶ 2,575:
print_endline "The guess was wrong! Please try again!"
done;
print_endline "Well guessed!"</
=={{header|Oforth}}==
<
: guess
10 rand doWhile: [ "Guess :" . System.Console askln asInteger over <> ]
drop "Well guessed!" . ;</
=={{header|Ol}}==
<syntaxhighlight lang="ol">
(import (otus random!))
Line 2,520 ⟶ 2,595:
(print "Well guessed!")
(loop)))
</syntaxhighlight>
=={{header|PARI/GP}}==
<
=={{header|Pascal}}==
<
var
Line 2,545 ⟶ 2,620:
writeln ('You made an excellent guess. Thank you and have a nice day.');
end.
</syntaxhighlight>
=={{header|Perl}}==
<
do { print "Guess a number between 1 and 10: " } until <> == $number;
print "You got it!\n";</
=={{header|Phix}}==
<!--<
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Guess_the_number.exw
Line 2,592 ⟶ 2,667:
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</
=={{header|PHP}}==
<
<?php
Line 2,643 ⟶ 2,718:
</body>
</html>
</syntaxhighlight>
=={{header|Picat}}==
<
N = random(1,10),
do print("Guess a number: ")
while (read_int() != N),
println("Well guessed!").</
{{trans|Prolog}}
<
N = random(1, 10),
repeat,
Line 2,659 ⟶ 2,734:
N = read_int(),
println("Well guessed!"),
!.</
=={{header|PicoLisp}}==
<
(let Number (rand 1 9)
(loop
Line 2,668 ⟶ 2,743:
(T (= Number (read))
(prinl "Well guessed!") )
(prinl "Sorry, this was wrong") ) ) )</
=={{header|Plain English}}==
<
Start up.
Play guess the number.
Line 2,685 ⟶ 2,760:
If the number is the secret number, break.
Repeat.
Write "Well guessed!" to the console.</
=={{header|PlainTeX}}==
This code should be compiled with etex features in console mode (for example "pdftex <name of the file>"):
<
\edef\tagetnumber{\number\numexpr1+\pdfuniformdeviate9}%
\message{^^JI'm thinking of a number between 1 and 10, try to guess it!}%
Line 2,703 ⟶ 2,778:
\ifnotguessed
\repeat
\bye</
=={{header|PowerShell}}==
Provides a function that analyzes the provided number by its call. The second script block is important and needed inside the script so the function will be called.
<
{
$Number = Get-Random -min 1 -max 11
Line 2,718 ⟶ 2,793:
While ($Number -ne $Guess)
Write-Host "Well done! You successfully guessed the number $Guess."
}</
<
GuessNumber $myNumber</
=={{header|ProDOS}}==
Uses math module:
<syntaxhighlight lang="prodos">:a
editvar /modify /value=-random-= <10
editvar /newvar /value=-random- /title=a
editvar /newvar /value=b /userinput=1 /title=Guess a number:
if -b- /hasvalue=-a- printline You guessed correctly! else printline Your guess was wrong & goto :a</
=={{header|Prolog}}==
{{works with|SWI-Prolog|6}}
<
random_between(1, 10, N),
repeat,
Line 2,739 ⟶ 2,814:
read(N),
writeln('Well guessed!'),
!.</
Example:
<
Guess the number: 1.
Guess the number: 2.
Guess the number: 3.
Well guessed!
true.</
=={{header|PureBasic}}==
<
Define TheNumber=Random(9)+1
Line 2,763 ⟶ 2,838:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
=={{header|Python}}==
<
t,g=random.randint(1,10),0
g=int(input("Guess a number that's between 1 and 10: "))
while t!=g:g=int(input("Guess again! "))
print("That's right!")</
===Expanded Range, Auto-Interactive===
<b>Note:</b> This is off-task, as there is no user interaction.<br/><br/>
Program from Russia guesses 1 out of a billion<br/>
https://rextester.com/GWJFOO4393
<syntaxhighlight lang="python">
import random #milliard.py
h1 = 0; h2 = 10**16; t = 0; f=0
Line 2,799 ⟶ 2,875:
print('win by', t, 'steps')
f=1
t=t+1</
{{out}}
<pre>1 40 11 MORE
Line 2,812 ⟶ 2,888:
=={{header|QB64}}==
''CBTJD'': 2020/04/13
<
CLS
RANDOMIZE TIMER
Line 2,822 ⟶ 2,898:
LOOP UNTIL n = num
INPUT "Well guessed! Go again"; a$
IF LEFT$(LCASE$(a$), 1) = "y" THEN GOTO START</
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
'Task
'Plus features: 1) AI gives suggestions about your guess
' 2) AI controls wrong input by user (numbers outer 1 and 10).
' 3) player can choose to replay the game
Randomize Timer
Dim As Integer Done, Guess, Number
Done = 1
Guess = 0
While Done
Cls
Number = Rnd * 10 + 1
Do While Number <> Guess
Cls
Locate 2, 1
Input "What number have I thought? (1-10)", Guess
If Guess > 0 And Guess < 11 Then
If Guess = Number Then
Locate 4, 1: Print "Well done, you win!"; Space$(20)
Exit Do
ElseIf Guess > Number Then
Locate 4, 1: Print "Too high, try lower"; Space$(20)
ElseIf Guess < Number Then
Locate 4, 1: Print "Too low, try higher"; Space$(20)
End If
Else
Print "Wrong input data! Try again"; Space$(20)
End If
_Delay 1
If Done = 11 Then Exit Do Else Done = Done + 1
Loop
If Done = 11 Then
Locate 4, 1: Print "Ah ah ah, I win and you loose!"; Space$(20)
Else
Locate 4, 1: Print " Sigh, you win!"; Space$(20)
End If
Locate 6, 1: Input "Another play? 1 = yes, others values = no ", Done
If Done <> 1 Then Done = 0
Wend
End
</syntaxhighlight>
=={{header|Quackery}}==
<
10 random 1+ number$
say 'I chose a number between 1 and 10.' cr
Line 2,832 ⟶ 2,953:
done
again ]
drop say 'Well guessed!'</
A sample output of exceptionally bad guessing:
{{out}}
Line 2,851 ⟶ 2,972:
=={{header|R}}==
<
print("Guess a number between 1 and 10 until you get it right.")
n <- sample(10, 1)
Line 2,858 ⟶ 2,979:
}
print("You got it!")
}</
=={{header|Racket}}==
<
(define (guess-number)
(define number (add1 (random 10)))
Line 2,868 ⟶ 2,989:
(if (equal? guess number)
(display "Well guessed!\n")
(loop))))</
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
repeat {} until prompt("Guess a number: ") == $number;
say "Guessed right!";</
=={{header|RapidQ}}==
<syntaxhighlight lang="vb">
RANDOMIZE
number = rnd(10) + 1
Line 2,888 ⟶ 3,009:
print "You guessed right, well done !"
input "Press enter to quit";a$
</syntaxhighlight>
=={{header|Rascal}}==
<
import vis::Figure;
import util::Math;
Line 2,905 ⟶ 3,026:
button("Start over", void(){random = arbInt(10);}) ]));
render(figure);
}</
Output:
Line 2,912 ⟶ 3,033:
=={{header|Red}}==
<
Red []
#include %environment/console/CLI/input.red
Line 2,922 ⟶ 3,043:
]
print "Well guessed!"
</syntaxhighlight>
=={{header|Retro}}==
<
over = [ drop 0 ] [ "Sorry, try again!\n" puts -1 ] if ;
Line 2,936 ⟶ 3,057:
think [ getToken toNumber checkGuess ] while
"You got it!\n" puts ;
</syntaxhighlight>
=={{header|REXX}}==
===version 1===
<small>(Note: most REXXes won't accept that first statement, the shebang/sha-bang/hashbang/pound-bang/hash-exclam/hash-pling.)</small>
<
/*REXX program to play: Guess the number */
Line 2,957 ⟶ 3,078:
say "Well done! You guessed it!"
</syntaxhighlight>
===version 2===
<
?= random(1, 10) /*generate a low random integer. */
say 'Try to guess my number between 1 ──► 10 (inclusive).' /*the directive to be used.*/
Line 2,968 ⟶ 3,089:
pull g /*obtain a guess from user.*/
end /*j*/
say 'Well guessed!' /*stick a fork in it, we're all done. */</
=={{header|Ring}}==
<
### Bert Mariani
Line 2,998 ⟶ 3,119:
end
</syntaxhighlight>
=={{header|RPL}}==
<syntaxhighlight lang="userrpl">
DIR
INITIALIZE
Line 3,033 ⟶ 3,154:
END
>>
END</
=={{header|Ruby}}==
<
n = rand(1..10)
puts 'Guess the number: '
puts 'Wrong! Guess again: ' until gets.to_i == n
puts 'Well guessed!'
</syntaxhighlight>
=={{header|Run BASIC}}==
<
choose = int(RND(0) * 9) + 1
while guess <> choose
Line 3,054 ⟶ 3,175:
end if
wend
wend</
=={{header|Rust}}==
{{libheader|rand}}
<
fn main() {
Line 3,082 ⟶ 3,203:
}
}
}</
=={{header|Scala}}==
<
val n = (math.random * 10 + 1).toInt
print("Guess the number: ")
while(readInt != n) print("Wrong! Guess again: ")
println("Well guessed!")
</syntaxhighlight>
=={{header|Scheme}}==
{{works with|Chicken Scheme}}
{{works with|Guile}}
<
(define number (random 11))
(display "Pick a number from 1 through 10.\n> ")
(do ((guess (read) (read)))
((= guess number) (display "Well guessed!\n"))
(display "Guess again.\n")))</
{{Out}}
<pre>scheme> (guess)
Line 3,117 ⟶ 3,238:
=={{header|Seed7}}==
<
const proc: main is func
Line 3,134 ⟶ 3,255:
end while;
writeln("You have won!");
end func;</
=={{header|Self}}==
Line 3,142 ⟶ 3,263:
Well factored:
<
parent* = traits clonable.
copy = (resend.copy secretNumber: random integerBetween: 1 And: 10).
Line 3,154 ⟶ 3,275:
hasGuessed = ( [ask = secretNumber] onReturn: [|:r| r ifTrue: [reportSuccess] False: [reportFailure]] ).
run = (sayIntroduction. [hasGuessed] whileFalse)
|) copy run</
Simple method:
<
userQuery report: 'Try to guess my secret number between 1 and 10.'.
n: random integerBetween: 1 And: 10.
[(userQuery askString: 'Guess the Number.') asInteger = n] whileFalse: [
userQuery report: 'Nope. Guess again.'].
userQuery report: 'You got it!'</
=={{header|Sidef}}==
<
var msg = 'Guess the number: '
while (n != read(msg, Number)) {
msg = 'Wrong! Guess again: '
}
say 'Well guessed!'</
=={{header|Small Basic}}==
<
TextWindow.WriteLine("I just thought of a number between 1 and 10. What is it?")
While guess<>number
Line 3,180 ⟶ 3,301:
TextWindow.WriteLine("Guess again! ")
EndWhile
TextWindow.WriteLine("You win!")</
=={{header|SNUSP}}==
Line 3,218 ⟶ 3,339:
=={{header|Swift}}==
<
var found = false
Line 3,234 ⟶ 3,355:
println("Well guessed!")
}
}</
=={{header|Tcl}}==
<
puts "I have thought of a number."
puts "Try to guess it!"
Line 3,249 ⟶ 3,370:
puts "Your guess was wrong. Try again!"
}
puts "Well done! You guessed it."</
Sample output:
<pre>
Line 3,265 ⟶ 3,386:
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
PRINT "Find the luckynumber (7 tries)!"
Line 3,284 ⟶ 3,405:
ENDLOOP
ENDCOMPILE
</syntaxhighlight>
Output:
<pre>
Line 3,300 ⟶ 3,421:
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
<
# Guess the number
# This simplified program does not check the input is valid
Line 3,313 ⟶ 3,434:
echo 'Sorry, the guess was wrong! Try again!'
done
echo 'Well done! You guessed it.'</
An older version used <code>while [ "$guess" -ne "$number" ]</code>. With [[pdksh]], input like '+' or '4x' would force the test to fail, end that while loop, and act like a correct guess. With <code>until [ "$guess" -eq "$number" ]</code>, input like '+' or '4x' now continues this until loop, and acts like a wrong guess. With Heirloom's Bourne Shell, '+' acts like '0' (always a wrong guess), and '4x' acts like '4' (perhaps correct).
Line 3,319 ⟶ 3,440:
==={{header|C Shell}}===
{{libheader|jot}}
<
# Guess the number
Line 3,332 ⟶ 3,453:
@ guess = "$<"
end
echo 'Well done! You guessed it.'</
=={{header|Ursa}}==
{{trans|Python}}
<
decl ursa.util.random random
Line 3,347 ⟶ 3,468:
end while
out "That's right!" endl console</
=={{header|Vala}}==
<
int x = Random.int_range(1, 10);
stdout.printf("Make a guess (1-10): ");
Line 3,357 ⟶ 3,478:
stdout.printf("Got it!\n");
return 0;
}</
=={{header|VBA}}==
<
Dim NbComputer As Integer, NbPlayer As Integer
Randomize Timer
Line 3,368 ⟶ 3,489:
Loop While NbComputer <> NbPlayer
MsgBox "Well guessed!"
End Sub</
=={{header|VBScript}}==
<
MyNum=Int(rnd*10)+1
Do
Line 3,391 ⟶ 3,512:
wscript.quit
end if
loop</
=={{header|Visual Basic .NET}}==
<
Sub Main()
Dim random As New Random()
Line 3,417 ⟶ 3,538:
Loop Until gameOver
End Sub
End Module</
{{Out}}
<pre>I am thinking of a number from 1 to 10. Can you guess it?
Line 3,431 ⟶ 3,552:
Well guessed!</pre>
=={{header|V (Vlang)}}==
<
import rand.seed
import os
Line 3,450 ⟶ 3,571:
}
}
}</
{{out}}
<pre>Please guess a number from 1-10 and press <Enter>: 1
Line 3,466 ⟶ 3,587:
=={{header|WebAssembly}}==
Uses [https://github.com/WebAssembly/WASI WASI] for I/O and random number generation. May be run directly with [https://github.com/bytecodealliance/wasmtime wasmtime].
<
(import "wasi_unstable" "fd_read"
(func $fd_read (param i32 i32 i32 i32) (result i32)))
Line 3,593 ⟶ 3,714:
end
)
)</
=={{header|Wee Basic}}==
Due to how the code works, any key has to be entered to generate the random number.
<
let mxnumber=10
let number=mnnumber
Line 3,620 ⟶ 3,741:
endif
wend
end</
=={{header|Wortel}}==
{{trans|JavaScript}}
<
num 10Wc
guess 0
Line 3,632 ⟶ 3,753:
!alert "Congratulations!\nThe number was {num}."
]
}</
=={{header|Wren}}==
<
import "random" for Random
Line 3,648 ⟶ 3,769:
break
}
}</
{{out}}
Line 3,661 ⟶ 3,782:
=={{header|X86 Assembly}}==
{{works with|NASM|Linux}}
<
segment .data
Line 3,765 ⟶ 3,886:
; "Guess my number" program by Randomboi (8/8/2021)
</syntaxhighlight>
=={{header|XBS}}==
<
Min:number=1,
Max:number=10,
Line 3,780 ⟶ 3,901:
stop;
}
}</
=={{header|XLISP}}==
<
(defun prompt ()
(display "What is your guess? ")
Line 3,796 ⟶ 3,917:
(display "I have thought of a number between 1 and 10. Try to guess it!")
(newline)
(prompt))</
{{out}}
<pre>[1] (guessing-game)
Line 3,816 ⟶ 3,937:
=={{header|XPL0}}==
<
int N, G;
[N:= Ran(10)+1;
Line 3,826 ⟶ 3,947:
];
Text(0, "Well guessed!^M^J");
]</
=={{header|zkl}}==
Strings are used to avoid dealing with error handling
<
while(1){
n:=ask("Num between 1 & 10: ");
if(n==r){ println("Well guessed!"); break; }
println("Nope")
}</
=={{header|Zoomscript}}==
For typing:
<
var guess
randnum & random 1 10
Line 3,851 ⟶ 3,972:
endif
endwhile
print "Correct number. You win!"</
For importing:
|