Guess the number: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|Java}}: hepp. The slash was the wrong way)
Line 184: Line 184:


=={{header|Java}}==
=={{header|Java}}==
<lang java6>import java.util.Scanner;
<lang java>import java.util.Scanner;


public class GuessNumber {
public class GuessNumber {

Revision as of 17:34, 28 November 2010

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

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>

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>

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>

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>

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>

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>

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

  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>