Guess the number: Difference between revisions

From Rosetta Code
Content added Content deleted
Line 29: Line 29:
Ada.Text_IO.Put_Line ("Well guessed!");
Ada.Text_IO.Put_Line ("Well guessed!");
end Guess_Number;</lang>
end Guess_Number;</lang>
=={{header|AutoHotkey}}==
<lang AutoHotkey>Random, rand, 1, 10 ; This stores a number between 1 and 10 in the var rand using the Mersenne Twister
msgbox I am thinking of a number between 1 and 10.

loop
{
InputBox, guess, Guess the number, Type in a number from 1 to 10
If (guess = rand)
{
msgbox Well Guessed!
Break ; exits loop
}
Else
Msgbox Try again.
}


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

Revision as of 21:01, 29 January 2011

Task
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>

AutoHotkey

<lang AutoHotkey>Random, rand, 1, 10  ; This stores a number between 1 and 10 in the var rand using the Mersenne Twister msgbox I am thinking of a number between 1 and 10.

loop { InputBox, guess, Guess the number, Type in a number from 1 to 10 If (guess = rand) { msgbox Well Guessed! Break ; exits loop } Else Msgbox Try again. }

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>

  1. include <stdio.h>
  2. 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>

  1. include <cstdlib>
  2. 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>

C#

<lang csharp>using System;

class GuessTheNumberGame {

   static void Main()
   {
       bool numberCorrect = false;
       Random randomNumberGenerator = new Random();
       int randomNumber = randomNumberGenerator.Next(1, 10+1);
       
       Console.WriteLine("I'm thinking of a number between 1 and 10.  Can you guess it?");
       do
       {
           Console.Write("Guess: ");
           int userGuess = int.Parse(Console.ReadLine());
           if (userGuess == randomNumber)
           {
               numberCorrect = true;
               Console.WriteLine("Congrats!!  You guessed right!");
           }
           else
               Console.WriteLine("That's not it.  Guess again.");
       } while (!numberCorrect);
   }

};

</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>

GML

<lang GML>n = string(ceil(random(10))) show_message("I'm thinking of a number from 1 to 10") g = get_string("Please enter guess", "") while(g != n)

   get_string("I'm sorry "+g+" is not my number, try again. Please enter guess", "")

show_message("Correct! "+g+" was my number!") exit</lang>

Go

<lang go> package main

import (

   "bufio"
   "fmt"
   "os"

)

func main() {

   n, _, _ := os.Time()
   s := fmt.Sprintf("%d\n", n%10+1)
   fmt.Print("Guess number from 1 to 10: ")
   for in := bufio.NewReader(os.Stdin); ; {
       guess, err := in.ReadString('\n')
       switch {
       case err != nil:
           fmt.Println("\n", err, "\nSo, bye.")
           return
       case guess == s:
           fmt.Println("Well guessed!")
           return
       }
       fmt.Print("No. Try again: ")
   }

} </lang>

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>

MATLAB

<lang matlab>number = ceil(10*rand(1)); [guess, status] = str2num(input('Guess a number between 1 and 10: ','s'));

while (~status || guess ~= number)

   [guess, status] = str2num(input('Guess again: ','s'));

end disp('Well guessed!')</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.

TUSCRIPT

<lang tuscript> $$ MODE TUSCRIPT PRINT "Find the luckynumber (7 tries)!" luckynumber=RANDOM_NUMBERS (1,10,1) COMPILE LOOP round=1,7 message=CONCAT ("[",round,"] Please insert a number") ASK $message: n=""

IF (n!='digits') THEN
  PRINT "wrong insert: ",n," Please insert a digit"
ELSEIF (n>10.or.n<1) THEN
  PRINT "wrong insert: ",n," Please insert a number between 1-10"
ELSEIF (n==#luckynumber) THEN
  PRINT "BINGO"
  EXIT

ENDIF IF (round==7) PRINT/ERROR "You've lost: luckynumber was: ",luckynumber ENDLOOP ENDCOMPILE </lang> Output:

Find the luckynumber (7 tries)!
[1] Please insert a number >a
wrong insert: a Please insert a digit
[2] Please insert a number >10
[3] Please insert a number >1
[4] Please insert a number >2
[5] Please insert a number >9
[6] Please insert a number >8
BINGO 

UNIX Shell

<lang sh>#!/bin/sh

  1. Guess the number
  2. 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>