Guess the number
You are encouraged to solve this task according to the task description, using any language you may know.
The task is to write a program where the program chooses a number between 1 and 10. The player is then prompted to enter a guess. If the player guesses wrong then they are prompted again until their guess is correct. When the user has made a successful guess the computer will give a "Well guessed!" message, and the program will exit.
A conditional loop may be used to repeat the guessing until the user is correct.
C.f: Guess the number/With Feedback, Bulls and cows
Ada
<lang Ada>with Ada.Numerics.Discrete_Random; with Ada.Text_IO; procedure Guess_Number is
subtype Number is Integer range 1 .. 10; package Number_IO is new Ada.Text_IO.Integer_IO (Number); package Number_RNG is new Ada.Numerics.Discrete_Random (Number); Generator : Number_RNG.Generator; My_Number : Number; Your_Guess : Number;
begin
Number_RNG.Reset (Generator); My_Number := Number_RNG.Random (Generator); Ada.Text_IO.Put_Line ("Guess my number!"); loop Ada.Text_IO.Put ("Your guess: "); Number_IO.Get (Your_Guess); exit when Your_Guess = My_Number; Ada.Text_IO.Put_Line ("Wrong, try again!"); end loop; Ada.Text_IO.Put_Line ("Well guessed!");
end Guess_Number;</lang>
BASIC
ZX Spectrum Basic
The ZX Spectrum does not have conditional loop constructs. We emulate that here using IF and GO TO <lang zxbasic>10 LET n=INT (RND*10)+1 20 PRINT "I have thought of a number." 30 PRINT "Try to guess it!" 40 INPUT "Enter your guess: ";g 50 IF g=n THEN GO TO 100 60 PRINT "Your guess was wrong. Try again!" 70 GO TO 40
100 PRINT "Well done! You guessed it." 110 STOP</lang>
C
<lang c>#include <stdlib.h>
- include <stdio.h>
- include <time.h>
int main(void) {
int n; int g; srand((unsigned int)time(NULL)); n = 1 + (rand() % 10); puts("I'm thinking of a number between 1 and 10."); puts("Try to guess it!"); while (1) { (void) scanf("%d", &g); if (g == n) { break; } else { puts("That's not my number."); puts("Try another guess!"); } } puts("You have won!"); return 0;
}</lang>
C++
<lang cpp>#include <iostream>
- include <cstdlib>
- include <ctime>
int main() {
srand(time(0)); int n = 1 + (rand() % 10); int g; std::cout << "I'm thinking of a number between 1 and 10.\nTry to guess it! "; while(true) { std::cin >> g; if (g == n) break; else std::cout << "That's not my number.\nTry another guess! "; } std::cout << "You've guessed my number!"; return 0;
}
</lang>
Clojure
<lang Clojure> (def target (inc (rand-int 10))
(loop [n 0]
(println "Guess a number between 1 and 10 until you get it right:") (let [guess (read)]
(if (= guess target) (printf "Correct on the %d guess.\n" n) (do (println "Try again") (recur (inc n)))))) </lang>
CoffeeScript
<lang coffeescript>num = Math.ceil(Math.random() * 10) guess = prompt "Guess the number. (1-10)" while parseInt(guess) isnt num
guess = prompt "YOU LOSE! Guess again. (1-10)"
alert "Well guessed!"</lang>
Common Lisp
<lang lisp>(defun guess-the-number ()
(let ((num-guesses 0)
(num (1+ (random 9))) (guess nil))
(format t "Try to guess a number from 1 to 10!~%") (loop do (format t "Guess? ")
(incf num-guesses) (setf guess (read)) (cond ((not (numberp guess)) (format t "Your guess is not a number!~%")) ((not (= guess num)) (format t "Your guess was wrong. Try again.~%"))) until (and (numberp guess) (= guess num)))
(format t "You guessed correctly on the ~:r try!~%" num-guesses)))
</lang> Output:
CL-USER> (guess-the-number) Try to guess a number from 1 to 10! Guess? a Your guess is not a number! Guess? 1 Your guess was wrong. Try again. Guess? 2 Your guess was wrong. Try again. Guess? 3 You guessed correctly on the fourth try!
Fortran
<lang fortran>program guess_the_number
implicit none
integer :: guess real :: r integer :: i, clock, count, n integer,dimension(:),allocatable :: seed
real,parameter :: rmax = 10
!initialize random number generator:
call random_seed(size=n) allocate(seed(n)) call system_clock(count) seed = count call random_seed(put=seed) deallocate(seed)
!pick a random number between 1 and rmax:
call random_number(r) !r between 0.0 and 1.0 i = int((rmax-1.0)*r + 1.0) !i between 1 and rmax
!get user guess:
write(*,'(A)') 'Im thinking of a number between 1 and 10.' do !loop until guess is correct
write(*,'(A)',advance='NO') 'Enter Guess: ' read(*,'(I5)') guess if (guess==i) exit write(*,*) 'Sorry, try again.'
end do
write(*,*) 'Youve guessed my number!'
end program guess_the_number </lang>
Go
<lang go> package main
import (
"bufio" "os"
)
func main() {
n, _, _ := os.Time() s := string(n%10 + '0') if s == "0" { s = "10" } s += "\n" _, err := os.Stdout.WriteString("Guess number from 1 to 10: ") if err != nil { os.Stderr.WriteString("stdout write failure\n") os.Exit(-1) } for in := bufio.NewReader(os.Stdin); ; { guess, err := in.ReadString('\n') switch { case err != nil: os.Stdout.WriteString("\nSo, bye.\n") return case guess == s: os.Stdout.WriteString("Well guessed!\n") return default: os.Stdout.WriteString("No. Try again: ") } }
} </lang> Notes: Go programmers might first think of using functions in packages like fmt, rand, and strconv. Reading a line from the keyboard though, kind of needs os and bufio, and as shown, it turns out there is enough functionality in those two packages to complete the task.
Haskell
<lang haskell> import Control.Monad import System.Random
-- Repeat the action until the predicate is true. until_ act pred = act >>= pred >>= flip unless (until_ act pred)
answerIs ans guess
| ans == guess = putStrLn "You got it!" >> return True | otherwise = putStrLn "Nope. Guess again." >> return False
ask = liftM read getLine
main = do
ans <- randomRIO (1,10) :: IO Int putStrLn "Try to guess my secret number between 1 and 10." ask `until_` answerIs ans
</lang>
J
<lang j>require 'misc' game=: verb define
n=: 1 + ?10 smoutput 'Guess my integer, which is bounded by 1 and 10' whilst. -. guess -: n do. guess=. {. 0 ". prompt 'Guess: ' if. 0 -: guess do. 'Giving up.' return. end. smoutput (guess=n){::'no.';'Well guessed!' end.
)</lang>
Example session:
<lang> game Guess my integer, which is bounded by 1 and 10 Guess: 1 no. Guess: 2 Well guessed!</lang>
Java
<lang java>import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) { Scanner keyboard = new Scanner(System.in);
int number = (int) ((Math.random()*10)+1); System.out.print("Guess the number which is between 1 and 10: "); int guess = keyboard.nextInt(); while(number != guess) { System.out.print("Guess again: "); guess = keyboard.nextInt(); } System.out.print("Hurray! You guessed correctly!");
}
}</lang>
Liberty BASIC
<lang lb>number = int(rnd(0) * 10) + 1 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;"."</lang>
Locomotive Basic
<lang locobasic>10 RANDOMIZE TIME:num=INT(RND*10+1):guess=0 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!"</lang>
Lua
<lang lua>math.randomseed( os.time() ) n = math.random( 1, 10 )
print( "I'm thinking of a number between 1 and 10. Try to guess it: " )
repeat
x = tonumber( io.read() )
if x == n then
print "Well guessed!"
else
print "Guess again: "
end
until x == n</lang>
Objeck
<lang objeck> use IO;
bundle Default {
class GuessNumber { function : Main(args : String[]) ~ Nil { done := false; "Guess the number which is between 1 and 10 or 'q' to quite: "->PrintLine(); rand_num := (Float->Random() * 10.0)->As(Int) + 1; while(done = false) { guess := Console->ReadString(); number := guess->ToInt(); if(number <> 0) { if(number <> rand_num) { "Guess again: "->PrintLine(); } else { "Hurray! You guessed correctly!"->PrintLine(); done := true; }; } else { if(guess->StartsWith("q") | guess->StartsWith("Q")) { done := true; }; }; }; } }
} </lang>
OCaml
<lang ocaml>#!/usr/bin/ocaml
let () =
Random.self_init(); let n = if Random.bool () then let n = 2 + Random.int 8 in print_endline "Please guess a number between 1 and 10 excluded"; (n) else let n = 1 + Random.int 10 in print_endline "Please guess a number between 1 and 10 included"; (n) in let rec loop () = let maybe = read_int() in if maybe = n then print_endline "Well guessed!" else begin print_endline "The guess was wrong! Please try again!"; loop () end in loop ()</lang>
Perl 6
<lang perl6>my $number = (1..10).pick; repeat {} until prompt("Guess a number: ") == $number; say "Guessed right!";</lang>
PicoLisp
<lang PicoLisp>(de guessTheNumber ()
(let Number (rand 1 9) (loop (prin "Guess the number: ") (T (= Number (read)) (prinl "Well guessed!") ) (prinl "Sorry, this was wrong") ) ) )</lang>
PureBasic
<lang PureBasic>TheNumber=Random(9)+1
Repeat
Print("Guess the number: ")
Until TheNumber=Val(Input())
PrintN("Well guessed!")</lang>
Python
<lang python>'Simple number guessing game'
import random
target, guess = random.randint(1, 10), 0 while target != guess:
guess = int(input('Guess my number between 1 and 10 until you get it right: '))
print('Thats right!')</lang>
R
<lang R>f <- function() {
print("Guess a number between 1 and 10 until you get it right.") n <- 1 + floor(10*runif(1)) while (as.numeric(readline()) != n) { print("Try again.") } print("You got it!")
}</lang>
REXX
version 1
<lang rexx>#!/usr/bin/rexx /* Guess the number */
number = random(1,10) say "I have thought of a number. Try to guess it!"
guess=0 /* We don't want a valid guess, before we start */
do while guess \= number
pull guess if guess \= number then say "Sorry, the guess was wrong. Try again!" /* endif - There is no endif in rexx. */
end
say "Well done! You guessed it!" </lang>
version 2
<lang rexx> ?=random(1,10) say 'Try to guess a number between 1 --> 10 (inclusive).'
do j=1 while g\==? if j\==1 then say 'Try again.' pull g end
say 'Well guessed!' </lang>
Ruby
<lang ruby> target = rand( 10 ) + 1 print 'I have thought of a number. Try to guess it! ' until gets.to_i == target
print 'Your guess was wrong. Try again! '
end puts 'Well done! You guessed it.' </lang>
Tcl
<lang tcl>set target [expr {int(rand()*10 + 1)}] puts "I have thought of a number." puts "Try to guess it!" while 1 {
puts -nonewline "Enter your guess: " flush stdout gets stdin guess if {$guess == $target} {
break
} puts "Your guess was wrong. Try again!"
} puts "Well done! You guessed it."</lang> Sample output:
I have thought of a number. Try to guess it! Enter your guess: 1 Your guess was wrong. Try again! Enter your guess: 2 Your guess was wrong. Try again! Enter your guess: 3 Your guess was wrong. Try again! Enter your guess: 8 Well done! You guessed it.
UNIX Shell
<lang sh>#!/bin/sh
- Guess the number
- This simplified program does not check the input is valid
number=`awk 'BEGIN{print int(rand()*10+1)}'` # We use ask to get a random number echo 'I have thought of a number. Try to guess it!' guess='0' # We don't want a valid guess, before we start while [ "$guess" -ne "$number" ] do
read guess if [ "$guess" -ne "$number" ]; then echo 'Sorry, the guess was wrong! Try again!' fi
done echo 'Well done! You guessed it.'</lang>