GUESSNUM
    ; get a random number between 1 and 100
    set target = ($random(100) + 1)    ; $r(100) gives 0-99

    ; loop until correct
    set tries = 0
    for {
        write !,"Guess the integer between 1 and 100: "
        read "",guess    ; gets input following write

        ; validate input
        if (guess?.N) && (guess > 0) && (guess < 101) {
            ; increment attempts
            set tries = tries + 1

            ; evaluate the guess
            set resp = $select(guess < target:"too low.",guess > target:"too high.",1:"correct!")

            ; display result, conditionally exit loop
            write !,"Your guess was "_resp
            quit:resp="correct!"
        }
        else {
            write !,"Please enter an integer between 1 and 100."
        }
    }    ; guess loop

    write !!,"You guessed the number in "_tries_" attempts."
    quit


import ceylon.random {
    DefaultRandom
}

shared void run() {
    value random = DefaultRandom();
    value range = 1..10;
    while(true) {
        value chosen = random.nextElement(range);
        print("I have chosen a number between ``range.first`` and ``range.last``.
               What is your guess?");
        while(true) {
            if(exists line = process.readLine()) {
                value guess = Integer.parse(line.trimmed);

                if(is ParseException guess) {
                    print(guess.message);
                    continue;
                }

                switch(guess <=> chosen)
                case (larger) {
                    print("Too high!");
                }
                case (smaller) {
                    print("Too low!");
                }
                case (equal) {
                    print("You got it!");
                    break;
                }
            } else {
                print("Please enter a number!");
            }
        }
    }
}


(defn guess-run []
  (let [start 1
	end 100
	target (+ start (rand-int (inc (- end start))))]
    (printf "Guess a number between %d and %d" start end)
    (loop [i 1]
      (printf "Your guess %d:\n" i)
      (let [ans (read)]
	(if (cond
	     (not (number? ans)) (println "Invalid format")
	     (or (< ans start) (> ans end)) (println "Out of range")
	     (< ans target)    (println "too low")
	     (> ans target)    (println "too high")
	     :else             true)
	  (println "Correct")
	  (recur (inc i)))))))


read_number = proc (prompt: string) returns (int)
    po: stream := stream$primary_output()
    pi: stream := stream$primary_input()
    while true do
        stream$puts(po, prompt)
        return(int$parse(stream$getl(pi)))
        except when bad_format:
            stream$putl(po, "Invalid number.")
        end
    end
end read_number

read_limits = proc () returns (int,int)
    po: stream := stream$primary_output()
    while true do
        min: int := read_number("Lower limit? ")
        max: int := read_number("Upper limit? ")
        if min >= 0 cand min < max then return(min,max) end
        stream$putl(po, "Invalid limits, try again.")
    end
end read_limits

read_guess = proc (min, max: int) returns (int)
    po: stream := stream$primary_output()
    while true do
        guess: int := read_number("Guess? ")
        if min <= guess cand max >= guess then return(guess) end
        stream$putl(po, "Guess must be between "
                || int$unparse(min) || " and " || int$unparse(max) || ".")
    end
end read_guess

play_game = proc (min, max, secret: int)
    po: stream := stream$primary_output()
    guesses: int := 0
    while true do
        guesses := guesses + 1
        guess: int := read_guess(min, max)
        if guess = secret then break
        elseif guess < secret then stream$putl(po, "Too low!")
        elseif guess > secret then stream$putl(po, "Too high!")
        end
    end
    stream$putl(po, "Correct! You got it in " || int$unparse(guesses) || " tries.")
end play_game

start_up = proc ()
    po: stream := stream$primary_output()
    d: date := now()
    random$seed(d.second + 60*(d.minute + 60*d.hour))

    stream$putl(po, "Guess the number\n----- --- ------\n")
    min, max: int := read_limits()
    secret: int := min + random$next(max - min + 1)
    play_game(min, max, secret)
end start_up


       IDENTIFICATION DIVISION.
       PROGRAM-ID. Guess-With-Feedback.

       DATA DIVISION.
       LOCAL-STORAGE SECTION.
       01  Seed       PIC 9(8).
       01  Random-Num PIC 99.
       01  Guess      PIC 99.

       PROCEDURE DIVISION.
           ACCEPT Seed FROM TIME
           COMPUTE Random-Num =
               FUNCTION REM(FUNCTION RANDOM(Seed) * 1000, 10) + 1

           DISPLAY "Guess a number between 1 and 10:"

           PERFORM FOREVER
               ACCEPT Guess

               IF Guess > Random-Num
                   DISPLAY "Your guess was too high."
               ELSE IF Guess < Random-Num
                   DISPLAY "Your guess was too low."
               ELSE
                   DISPLAY "Well guessed!"
                   EXIT PERFORM
           END-PERFORM

           GOBACK
           .


(defun guess-the-number-feedback (&optional (min 1) (max 100))
  (let ((num-guesses 0)
	(num (+ (random (1+ (- max min))) min))
	(guess nil))
    (format t "Try to guess a number from ~:d to ~:d!~%" min max)
    (loop do (format t "Guess? ")
	  (incf num-guesses)
	  (setf guess (read))
	  (format t "Your guess is ~[not a number.~;too small.~;too large.~;correct!~]~%"
		  (cond ((not (numberp guess)) 0)
			((< guess num) 1)
			((> guess num) 2)
			((= guess num) 3)))
	  until (and (numberp guess)
		     (= guess num)))
    (format t "You got the number correct on the ~:r guess!~%" num-guesses)))


number = rand(1..10)

puts "Guess the number between 1 and 10"

loop do
  begin
    user_number = gets.to_s.to_i
    if user_number == number
      puts "You guessed it."
      break
    elsif user_number > number
      puts "Too high."
    else
      puts "Too low."
    end
  rescue ArgumentError
    puts "Please enter an integer."
  end
end


import std.stdio, std.random, std.typecons, std.conv, std.string,
       std.range;

void main() {
    immutable interval = tuple(1, 100);
    writefln("Guess my target number that is between " ~
             "%d and %d (inclusive).\n", interval[]);
    immutable target = uniform!"[]"(interval[]);

    foreach (immutable i; sequence!q{n}) {
        writef("Your guess #%d: ", i + 1);
        immutable txt = stdin.readln.strip;

        Nullable!int answer;
        try {
            answer = txt.to!int;
        } catch (ConvException e) {
            writefln("  I don't understand your input '%s'", txt);
            continue;
        }
        if (answer < interval[0] || answer > interval[1]) {
            writeln("  Out of range!");
            continue;
        }
        if (answer == target) {
            writeln("  Well guessed.");
            break;
        }
        writeln(answer < target ? "  Too low." : "  Too high.");
    }
}


$ rnd = f$extract( 21, 2, f$time() )
$ count = 0
$ loop:
$ inquire guess "guess what number between 0 and 99 inclusive I am thinking of"
$ guess = f$integer( guess )
$ if guess .lt. 0 .or. guess .gt. 99
$ then
$  write sys$output "out of range"
$  goto loop
$ endif
$ count = count + 1
$ if guess .lt. rnd then $ write sys$output "too small"
$ if guess .gt. rnd then $ write sys$output "too large"
$ if guess .ne. rnd then $ goto loop
$ write sys$output "it only took you ", count, " guesses"


program GuessTheNumber;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  Math;

const
  // Set min/max limits
  min: Integer = 1;
  max: Integer = 10;

var
  last,
  val,
  inp: Integer;
  s: string;

  // Initialise new game
  procedure NewGame;
  begin
    // Make sure this number isn't the same as the last one
    repeat
      val := RandomRange(min,max);
    until
      val <> last;

    // Save this number
    last := val;
    Writeln('Guess a number between ', min, ' and ', max, ' [Answer = ', val, ']');
  end;

begin
  // Initialise the random number generator with a random value
  Randomize;

  // Initialise last number
  last := 0;

  // Initialise user input
  s := '';

  // Start game
  NewGame;

  // Loop
  repeat
    // User input
    Readln(s);

    // Validate - checxk if input is a number
    if TryStrToInt(s,inp) then
      begin
        // Is it the right number?
        if (inp = val) then
          begin
            // Yes - request a new game
            Writeln('Correct! Another go? Y/N');
            Readln(s);
            if SameText(s,'Y') then
              // Start new game
              NewGame
              else
              Exit;
          end
          else
          // Input too low/high
          if (inp < val) then
            Writeln('Too low! Try again...')
            else
            if (inp > val) then
              Writeln('Too high! Try again...');
      end
      else
      // Input invalid
      if not SameText(s,'bored') then
        Writeln('Invalid input! Try again...');

  until
    SameText(s,'bored');

end.


print "Guess a number between 1 and 100!"
n = random 100 + 1
repeat
  g = number input
  write g
  if error = 1
    print "You must enter a number!"
  elif g > n
    print " is too high"
  elif g < n
    print " is too low"
  .
  until g = n
.
print " is correct"


;;(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
(lib 'web) ; (play-sound) is defined in web.lib

(define (guess-feed (msg " 🔮 Enter a number in [0...100], -1 to stop.") (n (random 100)) (user 0))
   (set! user (read user msg))
   (play-sound 'ko)
   (unless (eq? n user ) ; user is the last user answer
       (guess-feed
               (cond ;; adapt prompt according to condition
                    ((not (integer? user)) "❌ Please, enter an integer")
                    (( < user 0) (error "🌵 - It was:" n)) ; exit to top level
                    ((> n user) "Too low ...")
                    ((< n user) "Too high ..."))
              n user))
    (play-sound 'ok )
    " 🔮 Well played!!  🍒 🍇 🍓")


open string datetime random core monad io

guess () = do
  putStrLn "What's the upper bound?"
  ub <- readAny
  main ub
  where main ub
          | ub < 0 = "Bound should be greater than 0."
          | else = do
              putStrLn $ format "Guess a number from 1 to {0}" ub
              dt <- datetime.now
              guesser (rnd (milliseconds $ dt) 1 ub)
        guesser v = do
          x <- readAny
          if x == v then
              cont ()
            else if x < v then
              do putStrLn "Too small!"
                 guesser v
            else
              do putStrLn "Too big!"
                 guesser v
        cont () = do
          putStrLn "Correct! Do you wish to continue (Y/N)?"
          ask ()
        ask () = do
          a <- readStr
          if a == "y" || a == "Y" then
              guess ()
            else if a == "n" || a == "N" then
              do putStrLn "Bye!"
            else
              do putStrLn "Say what?"
                 ask ()

guess () ::: IO


import extensions;

public program()
{
    int randomNumber := randomGenerator.eval(1,10);
    console.printLine("I'm thinking of a number between 1 and 10.  Can you guess it?");
    bool numberCorrect := false;
    until(numberCorrect)
    {
        console.print("Guess: ");
        int userGuess := console.readLine().toInt();
        if (randomNumber == userGuess)
        {
            numberCorrect := true;
            console.printLine("Congrats!!  You guessed right!")
        }
        else if (randomNumber < userGuess)
        {
            console.printLine("Your guess was too high")
        }
        else
        {
            console.printLine("Your guess was too low")
        }
    }
}


defmodule GuessingGame do
  def play(lower, upper) do
    play(lower, upper, Enum.random(lower .. upper))
  end
  defp play(lower, upper, number) do
    guess = Integer.parse(IO.gets "Guess a number (#{lower}-#{upper}): ")
    case guess do
      {^number, _} ->
        IO.puts "Well guessed!"
      {n, _} when n in lower..upper ->
        IO.puts if n > number, do: "Too high.", else: "Too low."
        play(lower, upper, number)
      _ ->
        IO.puts "Guess not in valid range."
        play(lower, upper, number)
    end
  end
end

GuessingGame.play(1, 100)


(let* ((min 1)
       (max 100)
       (number (+ (random (1+ (- max min))) min))
       guess done)
  (message "Guess the number between %d and %d" min max)
  (while (not done)
    (setq guess (read-number "Please enter a number "))
    (cond
     ((< guess number)
      (message "Too low!"))
     ((> guess number)
      (message "Too high!"))
     ((= guess number)
      (setq done t)
      (message "Well guessed!")))))


% Implemented by Arjun Sunel
-module(guess_number).
-export([main/0]).

main() ->
	L = 1 ,	 	% Lower Limit
	U = 100, 	  % Upper Limit

	io:fwrite("Guess my number between ~p and ", [L]),
	io:fwrite("and ~p until you get it right.\n", [U]),
	N = random:uniform(100),
	guess(N).

guess(N) ->
	{ok, [K]} = io:fread("Guess the number :  ","~d"),
	if
		K=:=N ->
			io:format("Well guessed!!\n");
		true ->
			if
				K > N ->
					io:format("Your guess is too high.\n");
				true ->
					io:format("Your guess is too low.\n")
			end,
			guess(N)
	end.


include get.e

constant lower_limit = 0, upper_limit = 100

integer number, guess
number = rand(upper_limit-lower_limit+1)+lower_limit

printf(1,"Guess the number between %d and %d: ", lower_limit & upper_limit)
while 1 do
    guess = floor(prompt_number("", lower_limit & upper_limit))
    if number = guess then
        puts(1,"You guessed correctly!\n")
        exit
    elsif number < guess then
        puts(1,"You guessed too high.\nTry again: ")
    else
        puts(1,"You guessed to low.\nTry again: ")
    end if
end while


open System

[<EntryPoint>]
let main argv =
    let aim =
        let from = 1
        let upto = 100
        let rnd = System.Random()
        Console.WriteLine("Hi, you have to guess a number between {0} and  {1}",from,upto)
        rnd.Next(from,upto)

    let mutable correct = false
    while not correct do

        let guess =
            Console.WriteLine("Please enter your guess:")
            match System.Int32.TryParse(Console.ReadLine()) with
            | true, number -> Some(number)
            | false,_ -> None

        match guess with
            | Some(number) ->
                match number with
                    | number when number > aim ->   Console.WriteLine("You guessed to high!")
                    | number when number < aim ->   Console.WriteLine("You guessed to low!")
                    | _                        ->   Console.WriteLine("You guessed right!")
                                                    correct <- true
            | None -> Console.WriteLine("Error: You didn't entered a parsable number!")

    0


USING:
    formatting
    fry
    io
    kernel
    math math.parser math.ranges
    prettyprint
    random ;
IN: guessnumber

: game-step ( target -- ? )
    readln string>number
    [
        2dup =
        [ 2drop f "Correct!" ]
        [ < "high" "low" ? "Guess too %s, try again." sprintf t swap ]
        if
    ]
    [ drop t "Invalid guess." ]
    if* print flush ;

: main ( -- )
    99 [1,b]
    [ unparse "Number in range %s, your guess?\n" printf flush ]
    [ random '[ _ game-step ] loop ]
    bi ;


class Main
{
  public static Void main ()
  {
    Int lowerLimit := 1
    Int higherLimit := 100

    Int target := (lowerLimit..higherLimit).random
    Int guess
    while (guess != target)
    {
      echo ("Enter a guess: ")
      try
      {
        // read in a line of input, and try to interpret as an Int
        guess = Env.cur.in.readLine.trim.toInt
        if (guess == target)
        {
          echo ("Well guessed!")
        }
        else if (guess < target)
        {
          echo ("Failed - your guess is too small")
        }
        else // if (guess > target)
        {
          echo ("Failed - your guess is too large")
        }
      }
      catch (Err e)
      {
        echo ("Your guess must be an integer")
      }
    }
  }
}


program Guess_a_number
  implicit none

  integer, parameter :: limit = 100
  integer :: guess, number
  real :: rnum

  write(*, "(a, i0, a)") "I have chosen a number between 1 and ", limit, &
                         " and you have to try to guess it."
  write(*, "(a/)")  "I will score your guess by indicating whether it is higher, lower or the same as that number"

  call random_seed
  call random_number(rnum)
  number = rnum * limit + 1
  do
    write(*, "(a)", advance="no") "Enter quess: "
    read*, guess
    if(guess < number) then
      write(*, "(a/)") "That is lower"
    else if(guess > number) then
      write(*, "(a/)") "That is higher"
    else
      write(*, "(a)") "That is correct"
      exit
    end if
  end do
end program


' FB 1.05.0 Win64

Randomize
Dim n As Integer = Int(Rnd * 20) + 1
Dim guess As Integer

Print "Guess which number I've chosen in the range 1 to 20"
Print
Do
  Input " Your guess : "; guess
  If guess > n AndAlso guess <= 20 Then
    Print "Your guess is higher than the chosen number, try again "
  ElseIf guess = n Then
    Print "Correct, well guessed!"
    Exit Do
  ElseIf guess < n AndAlso guess >= 1 Then
    Print "Your guess is lower than the chosen number, try again"
  Else
    Print "Your guess is inappropriate, try again"
  End If
Loop
End


// Guess a Number with feedback.
target = random[1,100] // Min and max are both inclusive for the random function
guess = 0
println["Welcome to guess a number! I've picked a number between 1 and 100. Try to guess it!"]
while guess != target
{
   guessStr = input["What is your guess?"]
   guess = parseInt[guessStr]
   if guess == undef
   {
      println["$guessStr is not a valid guess. Please enter a number from 1 to 100."]
      next
   }
   if guess < target
      println["My number is higher than $guess."]
   if guess > target
      println["My number is lower than $guess."]
   if guess == target
      println["$guess is correct! Well guessed!"]
}


[indent=4]
/*
   Number guessing with feedback, in Genie
   from https://wiki.gnome.org/Projects/Genie/AdvancedSample

   valac numberGuessing.gs
   ./numberGuessing
*/
class NumberGuessing

    prop min:int
    prop max:int

    construct(m:int, n:int)
        self.min = m
        self.max = n

    def start()
        try_count:int = 0
        number:int = Random.int_range(min, max)

        stdout.printf("Welcome to Number Guessing!\n\n")
        stdout.printf("I have thought up a number between %d and %d\n", min, max)
        stdout.printf("which you have to guess. I will give hints as we go.\n\n")

        while true
            stdout.printf("Try #%d, ", ++try_count)
            stdout.printf("please enter a number between %d and %d: ", min, max)
            line:string? = stdin.read_line()
            if line is null
                stdout.printf("bailing...\n")
                break

            input:int64 = 0
            unparsed:string = ""
            converted:bool = int64.try_parse(line, out input, out unparsed)
            if not converted or line is unparsed
                stdout.printf("Sorry, input seems invalid\n")
                continue

            guess:int = (int)input
            if number is guess
                stdout.printf("Congratulations! You win.\n")
                break
            else
                stdout.printf("Try again. The number in mind is %s than %d.\n",
                   number > guess ? "greater" : "less", guess)

init
    var game = new NumberGuessing(1, 100)
    game.start()


package main

import (
    "fmt"
    "math/rand"
    "time"
)

const lower, upper = 1, 100

func main() {
    fmt.Printf("Guess integer number from %d to %d: ", lower, upper)
    rand.Seed(time.Now().Unix())
    n := rand.Intn(upper-lower+1) + lower
    for guess := n; ; {
        switch _, err := fmt.Scan(&guess); {
        case err != nil:
            fmt.Println("\n", err, "So, bye.")
            return
        case guess < n:
            fmt.Print("Too low. Try again: ")
        case guess > n:
            fmt.Print("Too high. Try again: ")
        default:
            fmt.Println("Well guessed!")
            return
        }
    }
}


def rand = new Random() // java.util.Random
def range = 1..100 // Range (inclusive)
def number = rand.nextInt(range.size()) + range.from // get a random number in the range

println "The number is in ${range.toString()}" // print the range

def guess
while (guess != number) { // keep running until correct guess
    try {
        print 'Guess the number: '
        guess = System.in.newReader().readLine() as int // read the guess in as int
        switch (guess) { // check the guess against number
            case { it < number }: println 'Your guess is too low'; break
            case { it > number }: println 'Your guess is too high'; break
            default:              println 'Your guess is spot on!'; break
        }
    } catch (NumberFormatException ignored) { // catches all input that is not a number
        println 'Please enter a number!'
    }
}


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 =
  case compare ans guess of
    LT -> putStrLn "Too high. Guess again." >> return False
    EQ -> putStrLn "You got it!" >> return True
    GT -> putStrLn "Too low. Guess again." >> return False

-- Repeatedly read until the input *starts* with a number.  (Since
-- we use "reads" we allow garbage to follow it, though.)
ask = do line <- getLine
         case reads line of
           ((num,_):_) -> return num
           otherwise -> putStrLn "Please enter a number." >> ask

main = do
  ans <- randomRIO (1,100) :: IO Int
  putStrLn "Try to guess my secret number between 1 and 100."
  ask `until_` answerIs ans


U8 n, *g;
U8 min = 1, max = 100;

n = min + RandU16 % max;

Print("Guess the number between %d and %d: ", min, max);

while(1) {
  g = GetStr;

  if (Str2I64(g) == n) {
    Print("You guessed correctly!\n");
    break;
  }

  if (Str2I64(g) < n)
    Print("Your guess was too low.\nTry again: ");
  if (Str2I64(g) > n)
    Print("Your guess was too high.\nTry again: ");
}


procedure main()
    smallest := 5
    highest := 25
    n := smallest-1 + ?(1+highest-smallest)
    repeat {
      writes("Pick a number from ", smallest, " through ", highest, ": ")
      guess := read ()

      if n = numeric(guess)
        then {
          write ("Well guessed!")
          exit ()
        }
      else if n < numeric(guess)
        then write ("Your guess is too high")
      else if n > numeric(guess)
        then write ("Your guess is too low")
      else write ("Did you enter a number?")
    }
end


require 'misc'
game=: verb define
  assert. y -: 1 >. <.{.y
  n=: 1 + ?y
  smoutput 'Guess my integer, which is bounded by 1 and ',":y
  whilst. -. x -: n do.
    x=. {. 0 ". prompt 'Guess: '
    if. 0 -: x do. 'Giving up.' return. end.
    smoutput (*x-n){::'You win.';'Too high.';'Too low.'
  end.
)


import java.util.Random;
import java.util.Scanner;
public class Main
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        Random random = new Random();
        long from = 1;
        long to = 100;
        int randomNumber = random.nextInt(to - from + 1) + from;
        int guessedNumber = 0;

        System.out.printf("The number is between %d and %d.\n", from, to);

        do
        {
            System.out.print("Guess what the number is: ");
            guessedNumber = scan.nextInt();
            if (guessedNumber > randomNumber)
                System.out.println("Your guess is too high!");
            else if (guessedNumber < randomNumber)
                System.out.println("Your guess is too low!");
            else
                System.out.println("You got it!");
        } while (guessedNumber != randomNumber);
    }
}


Pick a number between 1 and 100.

<form id="guessNumber">
    <input type="text" name="guess">
    <input type="submit" value="Submit Guess">
</form>


function guesswithfeedback(n::Integer)
    number = rand(1:n)
    print("I choose a number between 1 and $n\nYour guess? ")
    while (guess = readline()) != dec(number)
        if all(isdigit, guess)
            print("Too ", parse(Int, guess) < number ? "small" : "big")
        else
            print("Enter an integer please")
        end
        print(", new guess? ")
    end
    println("You guessed right!")
end

guesswithfeedback(10)


import kotlin.random.Random

fun main() {
    val n = 1 + rand.nextInt(20)
    println("Guess which number I've chosen in the range 1 to 20\n")
    while (true) {
        print(" Your guess : ")
        val guess = readLine()?.toInt()
        when (guess) {
            n              ->  { println("Correct, well guessed!") ; return }
            in n + 1 .. 20 ->    println("Your guess is higher than the chosen number, try again")
            in 1 .. n - 1  ->    println("Your guess is lower than the chosen number, try again")
            else           ->    println("Your guess is inappropriate, try again")
        }
    }
}


{def game

 {def game.rec                                  // recursive part
  {lambda {:n :l :h}
   {let { {:n :n} {:l :l} {:h :h}               // :n, :l, :h redefined
          {:g {round {/ {+ :l :h} 2}}}}         // :g is the middle
    {if {< :g :n}
     then {br}:g too low!
          {game.rec :n {+ :g 1} :h}             // do it again higher
     else {if {> :g :n}
     then {br}:g too high!
          {game.rec :n :l {- :g 1}}             // do it again lower
     else {br}{b :g Got it!} }} }}}             // bingo!

 {lambda {:n}
  {let { {:n :n}                                // :n redefined
         {:N {floor {* :n {random}}}}}          // compute a random number
   Find {b :N} between 0 and :n {game.rec :N 0 :n}
}}}

{game {pow 2 32}}       // 2**32 = 4294967296


#!/usr/bin/lasso9

local(
	lower	= integer_random(10, 1),
	higher	= integer_random(100, 20),
	number	= integer_random(#higher, #lower),
	status	= false,
	guess
)

// prompt for a number
stdout('Guess a number: ')

while(not #status) => {
	#guess = null

	// the following bits wait until the terminal gives you back a line of input
	while(not #guess or #guess -> size == 0) => {
		#guess = file_stdin -> readSomeBytes(1024, 1000)
	}
	#guess = integer(#guess)

	if(not (range(#guess, #lower, #higher) == #guess)) => {
		stdout('Input not of correct type or range. Guess a number: ')
	else(#guess > #number)
		stdout('That was to high, try again! ')
	else(#guess < #number)
		stdout('That was to low, try again! ')
	else(#guess == #number)
		stdout('Well guessed!')
		#status = true
	}
}


(defmodule guessing-game
  (export (main 0)))

(defun get-player-guess ()
  (let (((tuple 'ok (list guessed)) (: io fread '"Guess number: " '"~d")))
    guessed))

(defun check-guess (answer guessed)
    (cond
      ((== answer guessed)
        (: io format '"Well-guessed!!~n"))
      ((/= answer guessed)
        (if (> answer guessed) (: io format '"Your guess is too low.~n"))
        (if (< answer guessed) (: io format '"Your guess is too high.~n"))
        (check-guess answer (get-player-guess)))))

(defun main ()
  (: io format '"Guess the number I have chosen, between 1 and 10.~n")
  (check-guess
    (: random uniform 10)
    (get-player-guess)))


[start]
    target = int( rnd( 1) * 100) +1

while 1
    do
        input "Guess a whole number between 1 and 100. To finish, type 'exit' "; b$
        if b$ ="exit" then print "Thank you for playing!": end
        c = val( b$)
        ok =( c =int( c)) and ( c >=1) and ( c <=100)
        if ok =0 then notice "Invalid data. Integers 1 to 100 only."
    loop until ok <>0

    if c =target       then print "      You guessed correctly.": print: goto [start]
    if c <target       then print "   Your guess was too low."
    if c >target       then print "   Your guess was too high."
wend


command guessTheNumber lowN highN
    local tNumber, tguess, tmin, tmax
    if lowN is empty or lowN < 1 then
        put 1 into tmin
    else
        put lowN into tmin
    end if
    if highN is empty then
        put 10 into tmax
    else
        put highN into tmax
    end if
    put random(tmax - tmin + 1) + tmin - 1 into tNumber
    repeat until tguess is tNumber
        ask question "Please enter a number between" && tmin && "and" && tmax titled "Guess the number"
        if it is not empty then
            put it into tguess
            if tguess is tNumber then
                answer "Well guessed!"
            else if tguess < tNumber then
                answer "too low"
            else
                answer "too high"
            end if
        else
            exit repeat
        end if
    end repeat
end guessTheNumber


10 CLS:RANDOMIZE TIME
20 PRINT "Please specify lower and upper limits":guess=0
30 INPUT "  (must be positive integers) :", first, last
40 IF first<1 OR last<1 THEN 20
50 num=INT(RND*(last-first+1)+first)
60 WHILE num<>guess
70 INPUT "Your guess? ", guess
80 IF guess<num THEN PRINT "too small!"
90 IF guess>num THEN PRINT "too large!"
100 WEND
110 INPUT "That's correct! Another game (y/n)? ", yn$
120 IF yn$="y" THEN 20


to guess [:max 100]
  local "number
  make "number random :max
  local "guesses
  make "guesses 0

  local "guess
  forever [
    (type [Guess my number! \(range 1 -\ ] :max "\):\ )
    make "guess first readlist
    ifelse (or (not numberp :guess) (lessp :guess 1) (greaterp :guess :max)) [
      print sentence [Guess must be a number between 1 and] (word :max ".)
    ] [
      make "guesses (:guesses + 1)
      ifelse lessp :guess :number [
        print [Too low!]
      ] [ifelse equalp :guess :number [
        (print [You got it in] :guesses "guesses!)
        stop
      ] [
        print [Too high!]
      ]]
    ]
  ]
end


math.randomseed(os.time())
me_win=false
my_number=math.random(1,10)
while me_win==false do
	print "Guess my number from 1 to 10:"
	your_number = io.stdin:read'*l'
	if type(tonumber(your_number))=="number" then
		your_number=tonumber(your_number)
		if your_number>10 or your_number<1 then
			print "Your number was not between 1 and 10, try again."
		elseif your_number>my_number then
			print "Your number is greater than mine, try again."
		elseif your_number<my_number then
			print "Your number is smaller than mine, try again."
		elseif your_number==my_number then
			print "That was correct."
			me_win=true
		end
	else
		print "Your input was not a number, try again."
	end
end


Module GuessNumber {
      Read Min, Max
      chosen = Random(Min, Max)
      print "guess a whole number between ";Min;" and ";Max
      do {
                  \\ we use guess so Input get integer value
                  \\ if we press enter without a number we get error
                  do {
                        \\ if we get error then we change line, checking the cursor position
                        If Pos>0 then Print
                        Try ok {
                              input "Enter your number " , guess%
                        }
                  } until ok
                  Select Case guess%
                  case  min to chosen-1
                        print "Sorry, your number was too low"
                  case chosen+1 to max
                        print "Sorry, your number was too high"
                  case chosen
                        print "Well guessed!"
                  else case
                        print "That was an invalid number"
                  end select
      } until guess% = chosen
}
GuessNumber 5, 15


GuessANumber := proc(low, high)
    local number, input;
    randomize():
    printf( "Guess a number between %d and %d:\n:> ", low, high );
    number := rand(low..high)();
    do
        input := parse(readline());
        if input > number then
            printf("Too high, try again!\n:> ");
        elif input < number then
            printf("Too low, try again!\n:> ");
        else
            printf("Well guessed! The answer was %d.\n", number);
            break;
        end if;
    end do:
end proc:


guessnumber[min_, max_] :=
 Module[{number = RandomInteger[{min, max}], guess},
  While[guess =!= number,
   guess = Input[
     If[guess > number, "Too high.Guess again.",
      "Too low.Guess again.",
      "Guess a number between " <> [email protected] <> " and " <>
       [email protected] <> "."]]];
  CreateDialog[{"Well guessed!", DefaultButton[]}]];
guessnumber[1, 10]


function guess_a_number(low, high)

if nargin < 1 || ~isnumeric(low) || length(low) > 1 || isnan(low)
    low = 1;
end;
if nargin < 2 || ~isnumeric(high) || length(high) > 1 || isnan(high)
    high = low+9;
elseif low > high
    [low, high] = deal(high, low);
end

n = floor(rand(1)*(high-low+1))+low;
gs = input(sprintf('Guess an integer between %i and %i (inclusive): ', low, high), 's');
while gs    % No guess quits the game
    g = str2double(gs);
    if length(g) > 1 || isnan(g) || g < low || g > high
        gs = input('Invalid input, guess again: ', 's');
    elseif g < n
        gs = input('Too low, guess again: ', 's');
    elseif g > n
        gs = input('Too high, guess again: ', 's');
    else
        disp('Good job, you win!')
        gs = '';
    end
end


Range = [1,100]
randomNumber = (random Range.x Range.y) as integer
clearListener()
while true do
(
	userVal = getKBValue prompt:("Enter a number between "+(range[1] as integer) as string+" and "+(range[2] as integer) as string+": ")
	if userVal == randomNumber do (format "\nWell guessed!\n"; exit with OK)
	case of
	(
		(classOf userVal != classof randomNumber): (format "\nBad number!\n")
		(userVal > Range[2] or userVal < Range[1]): (format "\nNumber out of range\n")
		(userVal > randomNumber): (format "\nToo high!\n")
		(userVal < randomNumber): (format "\nToo low!\n")
	)
)


def getInput:int
  s = System.console.readLine()
  Integer.parseInt(s)
end

number = int(Math.random() * 10 + 1)

puts "Guess the number between 1 and 10"

guessed = false

while !guessed do
  begin
    userNumber = getInput
    if userNumber == number
      guessed = true
      puts "You guessed it."
    elsif userNumber > number
      puts "Too high."
    else
      puts "Too low."
    end
  rescue NumberFormatException => e
    puts "Please enter an integer."
  end
end


MODULE guessf;

IMPORT  InOut, Random, NumConv, Strings;

VAR     number, guess           : CARDINAL;
        input                   : Strings.String;
        OK, Done                : BOOLEAN;

BEGIN
  number := Random.nr (1000);
  InOut.WriteString ("I have chosen a number below 1000; please try to guess it.");
  InOut.WriteLn;
  REPEAT
    REPEAT
      InOut.WriteString ("Enter your guess : ");        InOut.WriteBf;
      InOut.ReadString (input);
      NumConv.Str2Num (guess, 10, input, OK);
      IF  NOT OK  THEN
        InOut.WriteString (input);
        InOut.WriteString (" is not a valid number...");
        InOut.WriteLn
      END
    UNTIL  OK;
    InOut.WriteString ("Your guess is ");
    IF  number = guess  THEN
      Done := TRUE;
      InOut.WriteString ("spot on!")
    ELSE
      Done := FALSE;
      IF  guess > number  THEN
        InOut.WriteString ("too high.")
      ELSE
        InOut.WriteString ("too low.")
      END
    END;
    InOut.WriteLn
  UNTIL  Done;
  InOut.WriteString ("Thank you for playing; have a nice day!");
  InOut.WriteLn
END guessf.


import Nanoquery.Util

random = new(Random)
inclusive_range = {1, 100}

print format("Guess my target number that is between %d and %d (inclusive).\n",\
             inclusive_range[0], inclusive_range[1])
target = random.getInt(inclusive_range[1]) + inclusive_range[0]
answer = 0
i = 0
while answer != target
	i += 1
	print format("Your guess(%d): ", i)
	txt = input()

	valid = true
	try
		answer = int(txt)
	catch
		println format("  I don't understand you input of '%s' ?", txt)
		value = false
	end

	if valid
		if (answer < inclusive_range[0]) or (answer > inclusive_range[1])
			println "  Out of range!"
		else if answer = target
			println "  Ye-Haw!!"
		else if answer < target
			println "  Too low."
		else if answer > target
			println "  Too high."
		end
	end
end

println "\nThanks for playing."


using System;
using System.Console;

module GuessHints
{
    Main() : void
    {
        def     rand   = Random();
        def     secret = rand.Next(1, 101);
        mutable guess  = 0;

        def GetGuess() : int {Int32.Parse(ReadLine())}

        WriteLine("Guess a number between 1 and 100:");

        do
        {
            guess = GetGuess();
            match(guess.CompareTo(secret))
            {
                |(-1) => WriteLine("Too low! Guess again:")
                |1    => WriteLine("Too high! Guess again:")
                |0    => WriteLine("Well guessed!")
            }
        } while (guess != secret)
    }
}


/* NetRexx */
options replace format comments java crossref symbols nobinary

parse arg lo hi .
if lo = '' | lo = '.' then lo = 1
if hi = '' | hi = '.' then hi = 100
if lo > hi then parse (hi lo) lo hi -- make sure lo is < hi
rg = Random()
tries = 0
guessThis = rg.nextInt(hi - lo) + lo

say
say 'Rules:  Guess a number between' lo 'and' hi
say '        Use QUIT or . to stop the game'
say '        Use TELL to get the game to tell you the answer.'
say
say 'Starting...'
say

loop label g_ forever
  say  'Try guessing a number between' lo 'and' hi
  parse ask guess .
  select
    when guess.upper = 'QUIT' | guess = '.' then do
      say 'You asked to leave the game.  Goodbye...'
      leave g_
      end
    when guess.upper = 'TELL' | guess = '.' then do
      say 'The number you were looking for is' guessThis
      end
    when \guess.datatype('w') then do
      say guess 'is not a whole number.  Try again.'
      end
    when guess = guessThis then do
      tries = tries + 1
      say 'Well guessed!' guess 'is the correct number.'
      say 'It took you' tries 'tries.'
      leave g_
      end
    when guess < lo then do
      tries = tries + 1
      say guess 'is below the lower limit of' lo
      end
    when guess > hi then do
      tries = tries + 1
      say guess 'is above the upper limit of' hi
      end
    when guess < guessThis then do
      tries = tries + 1
      say guess 'is too low. Try again.'
      end
    when guess > guessThis then do
      tries = tries + 1
      say guess 'is too high. Try again.'
      end
    otherwise do
      say guess 'is an unexpected value.'
      end
    end
  end g_

return


; guess-number-feedback.lsp
; oofoe 2012-01-19
; http://rosettacode.org/wiki/Guess_the_number/With_feedback

(seed (time-of-day)) ; Initialize random number generator from clock.
(setq low  -5
      high 62
      number (+ low (rand (- high low)))
      found nil
)

(print "I'm thinking of a number between " low " and " high ".")

(while (not found)
  (print " What's your guess? ")
  (setq guess (int (read-line) 'bad))
  (print (cond ((= 'bad guess) "That's not a number! Try again!")
               ((or (< guess low) (> guess high))
                (string "My number is between " low
                        " and " high ". Try again!"))
               ((< number guess) "Try a little lower...")
               ((> number guess) "Maybe a bit higher...")
               ((= number guess) (setq found true) "Exactly right!")))
  )

(println "\nWell guessed! Congratulations!")

(exit)


import random, strutils

randomize()

let iRange = 1..100

echo "Guess my target number that is between ", iRange.a, " and ", iRange.b, " (inclusive)."
let target = rand(iRange)
var answer, i = 0
while answer != target:
  inc i
  stdout.write "Your guess ", i, ": "
  let txt = stdin.readLine()
  try: answer = parseInt(txt)
  except ValueError:
    echo "  I don't understand your input of '", txt, "'"
    continue
  if answer notin iRange: echo "  Out of range!"
  elif answer < target: echo "  Too low."
  elif answer > target: echo "  Too high."
  else: echo "  Ye-Haw!!"

echo "Thanks for playing."


10 NUMBER=RND(10)+1
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
40 IF GUESS<NUMBER THEN PRINT "MY NUMBER IS HIGHER THAN THAT.": GOTO 20
50 PRINT "THAT'S THE CORRECT NUMBER."


use IO;

bundle Default {
   class GuessNumber {
      function : Main(args : String[]) ~ Nil {
         Guess();
      }
      function : native : Guess() ~ Nil {
         done := false;
         "Guess the number which is between 1 and 10 or 'n' 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) {
                  Console->Print("Your guess was too ")
                     ->Print(number < rand_num ? "low" : "high")
                     ->Print(".\nGuess again: ");
               }
               else {
                  "Hurray! You guessed correctly!"->PrintLine();
                  done := true;
               };
            }
            else {
               if(guess->StartsWith("q") | guess->StartsWith("Q")) {
                  done := true;
               };
            };
         };
      }
   }
}


let rec _read_int() =
  try read_int()
  with _ ->
    print_endline "Please give a cardinal numbers.";
    (* TODO: what is the correct word? cipher, digit, figure or numeral? *)
    _read_int() ;;

let () =
  print_endline "Please give a set limits (two integers):";
  let a = _read_int()
  and b = _read_int() in
  let a, b =
    if a < b
    then (a, b)
    else (b, a)
  in
  Random.self_init();
  let target = a + Random.int (b - a) in
  Printf.printf "I have choosen a number between %d and %d\n%!" a b;
  print_endline "Please guess it!";
  let rec loop () =
    let guess = _read_int() in
    if guess = target then
    begin
      print_endline "The guess was equal to the target.\nCongratulation!";
      exit 0
    end;
    if guess < a || guess > b then
      print_endline "The input was inappropriate."
    else if guess > target then
      print_endline "The guess was higher than the target."
    else if guess < target then
      print_endline "The guess was less than the target.";
    loop ()
  in
  loop ()


function guess_a_number(low,high)
% Guess a number (with feedback)
% http://rosettacode.org/wiki/Guess_the_number/With_feedback

if nargin<1,
	low=1;
end;
if nargin<2,
	high=10;
end;

n = floor(rand(1)*(high-low+1))+low;
[guess,state] = str2num(input(sprintf('Guess a number between %i and %i: ',low,high),'s'));
while (~state || guess~=n)
	if guess < n,
		g = input('to low, guess again: ','s');
		[guess, state] = str2num(g);
	elseif guess > n,
		g = input('to high, guess again: ','s');
		[guess, state] = str2num(g);
	end;
	while ~state
		g = input('invalid input, guess again: ','s');
		[guess, state] = str2num(g);
	end
end
disp('Well guessed!')


import: console

: guessNumber(a, b)
| n g |
   b a - rand a + 1- ->n
   begin
      "Guess a number between" . a . "and" . b . ":" .
      while(System.Console askln asInteger dup -> g isNull) [ "Not a number " println ]
      g n == ifTrue: [ "You found it !" .cr return ]
      g n <  ifTrue: [ "Less" ] else: [ "Greater" ] . "than the target" .cr
   again ;


(import (otus random!))

(define from 0)
(define to 100)

(define number (+ from (rand! (+ from to 1))))

(let loop ()
   (for-each display `("Pick a number from " ,from " through " ,to ": "))
   (let ((guess (read)))
      (cond
         ((not (number? guess))
            (print "Not a number!")
            (loop))
         ((or (< guess from)
              (< to guess))
            (print "Out of range!")
            (loop))
         ((< guess number)
            (print "Too low!")
            (loop))
         ((> guess number)
            (print "Too high!")
            (loop))
         ((= guess number)
            (print "Well guessed!")))))


Select instead of a series of If's
simple comparison instead of strict
different indentations.
entering ? shows the number we are looking for


guess_the_number(N=10)={
	a=random(N);
	print("guess the number between 0 and "N);
	for(x=1,N,
		if(x>1,
			if(b>a,
				print("guess again lower")
			,
				print("guess again higher")
		);
		b=input();
		if(b==a,break())
	);
	print("You guessed it correctly")
};


sub prompt {
	my $prompt = shift;
	while (1) {
		print "\n", $prompt, ": ";
		# type ^D, q, quit, quagmire, etc to quit
		defined($_ = <STDIN>) and !/^\s*q/ or exit;

		return $_ if /^\s*\d+\s*$/s;
		$prompt = "Please give a non-negative integer";
	}
}

my $tgt = int(rand prompt("Hola! Please tell me the upper bound") + 1);
my $tries = 1;

$tries++, print "You guessed too ", ($_ == -1 ? "high" : "low"), ".\n"
	while ($_ = $tgt <=> prompt "Your guess");

print "Correct! You guessed it after $tries tries.\n";


--
-- demo\rosetta\Guess_the_number3.exw
--
with javascript_semantics
requires("1.0.1") -- (VALUECHANGED_CB fix)
include pGUI.e

constant lower_limit = 0, upper_limit = 100,
         secret = rand_range(lower_limit,upper_limit),
         fmt = "Enter your guess, a number between %d and %d",
         prompt = sprintf(fmt,{lower_limit,upper_limit})

Ihandle dlg, label, input, state

function valuechanged_cb(Ihandle /*input*/)
    integer guess = IupGetInt(input,"VALUE")
    string msg = iff(guess<secret?"Too low":
                 iff(guess=secret?"You got it!":
                 iff(guess>secret?"Too high":
                                  "uh?")))
    IupSetAttribute(state,"TITLE",msg)
    return IUP_CONTINUE
end function

IupOpen()
label = IupLabel(prompt)
input = IupText("VALUE=0, EXPAND=HORIZONTAL, MASK="&IUP_MASK_INT)
state = IupLabel("","EXPAND=HORIZONTAL")
IupSetAttributes({label,input,state},"PADDING=0x15")
IupSetCallback(input,"VALUECHANGED_CB",Icallback("valuechanged_cb"))
{} = valuechanged_cb(input)
dlg = IupDialog(IupVbox({label,input,state},"MARGIN=15x15"),`TITLE="Guess the number"`)
IupShow(dlg)
if platform()!=JS then
    IupMainLoop()
    IupClose()
end if


<?php

session_start();

if(isset($_SESSION['number']))
{
   $number = $_SESSION['number'];
}
else
{
   $_SESSION['number'] = rand(1,10);
}

if($_POST["guess"]){
    $guess  = htmlspecialchars($_POST['guess']);

	echo $guess . "
";
    if ($guess < $number)
	{
        echo "Your guess is too low";
    }
	elseif($guess > $number)
	{
        echo "Your guess is too high";
    }
	elseif($guess == $number)
	{
        echo "You got the correct number!";
    }

}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>Guess A Number</title>

		<form action="<?=$_SERVER['PHP_SELF'] ?>" method="post" name="guess-a-number">
		    Guess A Number:

		    <input type="text" name="guess" />
		    <input name="number" type="hidden" value="<?= $number ?>" />
		    <input name="submit" type="submit" />
		</form>


(de guessTheNumber ()
   (use (Low High Guess)
      (until
         (and
            (prin "Enter low limit : ")
            (setq Low (read))
            (prin "Enter high limit: ")
            (setq High (read))
            (> High Low) ) )
      (seed (time))
      (let Number (rand Low High)
         (loop
            (prin "Guess what number I have: ")
            (T (= Number (setq Guess (read)))
               (prinl "You got it!") )
            (prinl
               "Your guess is too "
               (if (> Number Guess) "low" "high")
               "." ) ) ) ) )


The low number is 1.

The high number is 100.

To run:
Start up.
Play the guessing game.
Wait for the escape key.
Shut down.

To play the guessing game:
Pick a secret number between the low number and the high number.
Write "I chose a secret number between " then the low number then " and " then the high number then "." then the return byte on the console.
Loop.
Ask the user for a number.
If the number is the secret number, break.
If the number is less than the secret number, write "  Too low." on the console.
If the number is greater than the secret number, write "  Too high." on the console.
Repeat.
Write "  Well guessed!" on the console.

To ask the user for a number:
Write "Your guess? " to the console without advancing.
Read a string from the console.
If the string is not any integer, write "  Guess must be an integer." on the console; repeat.
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 greater than the high number, write "  Guess can't be higher than " then the high number then "." on the console; repeat.


function Get-Guess
{
    [int]$number = 1..100 | Get-Random
    [int]$guess = 0
    [int[]]$guesses = @()

    Write-Host "Guess a number between 1 and 100" -ForegroundColor Cyan

    while ($guess -ne $number)
    {
        try
        {
            [int]$guess = Read-Host -Prompt "Guess"

            if ($guess -lt $number)
            {
                Write-Host "Greater than..."
            }
            elseif ($guess -gt $number)
            {
                Write-Host "Less than..."
            }
            else
            {
                Write-Host "You guessed it"
            }
        }
        catch [Exception]
        {
            Write-Host "Input a number between 1 and 100." -ForegroundColor Yellow
            continue
        }

        $guesses += $guess
    }

    [PSCustomObject]@{
        Number  = $number
        Guesses = $guesses
    }
}

$answer = Get-Guess

Write-Host ("The number was {0} and it took {1} guesses to find it." -f $answer.Number, $answer.Guesses.Count)


main :-
    play_guess_number.

/* Parameteres */

low(1).
high(10).

/* Basic Game Logic */

play_guess_number :-
    low(Low),
    high(High),
    random(Low, High, N),
    tell_range(Low, High),
    repeat,                         % roughly, "repeat ... (until) Guess == N "
        ask_for_guess(Guess),
        give_feedback(N, Guess),
    Guess == N.

/* IO Stuff */

tell_range(Low, High) :-
    format('Guess an integer between ~d and ~d.~n', [Low,High]).

ask_for_guess(Guess) :-
    format('Guess the number: '),
    read(Guess).

give_feedback(N, Guess) :-
    ( \+integer(Guess) -> writeln('Invalid input.')
    ; Guess < N        -> writeln('Your guess is too low.')
    ; Guess > N        -> writeln('Your guess is too high.')
    ; Guess =:= N      -> writeln("Correct!")
    ).


OpenConsole()

Repeat
  ; Ask for limits, with sanity check
  Print("Enter low limit : "): low  =Val(Input())
  Print("Enter high limit: "): High =Val(Input())
Until High>low

TheNumber=Random(High-low)+low
Debug TheNumber
Repeat
  Print("Guess what number I have: "): Guess=Val(Input())
  If Guess=TheNumber
    PrintN("You got it!"): Break
  ElseIf Guess < TheNumber
    PrintN("Your guess is to low.")
  Else
    PrintN("Your guess is to high.")
  EndIf
ForEver


import random

inclusive_range = (1, 100)

print("Guess my target number that is between %i and %i (inclusive).\n"
      % inclusive_range)
target = random.randint(*inclusive_range)
answer, i = None, 0
while answer != target:
    i += 1
    txt = input("Your guess(%i): " % i)
    try:
        answer = int(txt)
    except ValueError:
        print("  I don't understand your input of '%s' ?" % txt)
        continue
    if answer < inclusive_range[0] or answer > inclusive_range[1]:
        print("  Out of range!")
        continue
    if answer == target:
        print("  Ye-Haw!!")
        break
    if answer < target: print("  Too low.")
    if answer > target: print("  Too high.")

print("\nThanks for playing.")


  [ say "Guess the number (1-100 inclusive.)"
    cr cr
    100 random 1+
    [ $ "Your guess... " input
      trim reverse trim reverse
      $->n
      not iff
        [ drop
          say "That is not a number." cr ]
        again
      2dup != while
      over < iff
        [ say "Too small." cr ]
        again
      say "Too large." cr
      again ]
    say "Well done! "
    echo say " is correct. " cr
    drop ]                                   is guess-the-number ( --> )


guessANumber <- function(low, high)
{
  boundryErrorCheck(low, high)
  goal <- sample(low:high, size = 1)
  guess <- getValidInput(paste0("I have a whole number between ", low, " and ", high, ". What's your guess? "))
  while(guess != goal)
  {
    if(guess < low || guess > high){guess <- getValidInput("Out of range! Try again "); next}
    if(guess > goal){guess <- getValidInput("Too high! Try again "); next}
    if(guess < goal){guess <- getValidInput("Too low! Try again "); next}
  }
  "Winner!"
}

boundryErrorCheck <- function(low, high)
{
  if(!is.numeric(low) || as.integer(low) != low) stop("Lower bound must be an integer. Try again.")
  if(!is.numeric(high) || as.integer(high) != high) stop("Upper bound must be an integer. Try again.")
  if(high < low) stop("Upper bound must be strictly greater than lower bound. Try again.")
  if(low == high) stop("This game is impossible to lose. Try again.")
  invisible()
}

#R's system for checking if numbers are integers is lacking (e.g. is.integer(1) returns FALSE)
#so we need this next function.
#A better way to check for integer inputs can be found in is.interger's docs, but this is easier to read.
#Note that readline outputs the user's input as a string, hence the need for type.convert.
getValidInput <- function(requestText)
{
  guess <- type.convert(readline(requestText))
  while(!is.numeric(guess) || as.integer(guess) != guess){guess <- type.convert(readline("That wasn't an integer! Try again "))}
  as.integer(guess)
}


#lang racket

(define (guess-number min max)
  (define target (+ min (random (- max min -1))))
  (printf "I'm thinking of a number between ~a and ~a\n" min max)
  (let loop ([prompt "Your guess"])
    (printf "~a: " prompt)
    (flush-output)
    (define guess (read))
    (define response
      (cond [(not (exact-integer? guess)) "Please enter a valid integer"]
            [(< guess target)             "Too low"]
            [(> guess target)             "Too high"]
            [else #f]))
    (when response (printf "~a\n" response) (loop "Try again")))
  (printf "Well guessed!\n"))

(guess-number 1 100)


my $maxnum = prompt("Hello, please give me an upper boundary: ");
until 0 < $maxnum < Inf {
    say "Oops! The upper boundary should be > 0 and not Inf";
    $maxnum = prompt("Please give me a valid upper boundary: ");
}

my $count = 0;
my $number = (1..$maxnum).pick;

say "I'm thinking of a number from 1 to $maxnum, try to guess it!";
repeat until my $guessed-right {
    given prompt("Your guess: ") {
        when /^[e|q]/ { say 'Goodbye.'; exit; }
        when not 1 <= $_ <= $maxnum {
           say "You really should give me a number from 1 to $maxnum."
        }
        $count++;
        when $number { $guessed-right = True }
        when $number < $_ { say "Sorry, my number is smaller." }
        when $number > $_ { say "Sorry, my number is bigger." }
    }
}
say "Great you guessed right after $count attempts!";


: high|low ( gn-g$ )
  over > [ "high" ] [ "low" ] if ;

: checkGuess ( gn-gf || f )
  2over = [ "You guessed correctly!\n" puts 2drop 0 ]
          [ high|low "Sorry, your guess was too %s.\nTry again.\n" puts -1 ] if ;

: think ( -n )
  random abs 100 mod 1+ ;

: guess ( - )
  "I'm thinking of a number between 1 and 100.\n" puts
  "Try to guess it!\n" puts
  think [ getToken toNumber checkGuess ] while
  "You got it!\n" puts ;


/*REXX program plays guess the number  game with a human;  the computer picks the number*/
  low=   1                                       /*the lower range for the guessing game*/
 high= 100                                       /* "  upper   "    "   "      "      " */
  try=   0                                       /*the number of valid (guess) attempts.*/
    r= random(low, high)                         /*get a random number  (low ───► high).*/
 lows= 'too_low  too_small too_little below under underneath   too_puny'
highs= 'too_high too_big   too_much   above over  over_the_top too_huge'
  erm= '***error***'
 @gtn= "guess the number, it's between"
prompt= centre(@gtn   low     'and'     high     '(inclusive)  ───or───  Quit:', 79, "─")
                                                 /* [↓]  BY 0 ─── used to  LEAVE  a loop*/
  do ask=0  by 0;     say;      say prompt;      say;     pull g;     g= space(g);    say
    do validate=0  by 0                          /*DO index required; LEAVE instruction.*/
       select
       when g==''                 then iterate ask
       when abbrev('QUIT', g, 1)  then exit                              /*what a whoos.*/
       when words(g) \== 1        then say erm    'too many numbers entered:'        g
       when \datatype(g, 'N')     then say erm g  "isn't numeric"
       when \datatype(g, 'W')     then say erm g  "isn't a whole number"
       when g<low                 then say erm g  'is below the lower limit of'     low
       when g>high                then say erm g  'is above the higher limit of'   high
       otherwise       leave  /*validate*/
       end   /*select*/
    iterate ask
    end      /*validate*/

  try= try + 1
  if g=r  then leave
  if g>r  then what= word(highs, random(1, words(highs) ) )
          else what= word( lows, random(1, words( lows) ) )
  say 'your guess of'     g     "is"      translate(what, , "_").
  end        /*ask*/
                                                 /*stick a fork in it,  we're all done. */
if try==1  then say 'Gadzooks!!!       You guessed the number right away!'
           else say 'Congratulations!, you guessed the number in '     try     " tries."


fr = 1 t0 = 10
while true
see "Hey There,
========================
I'm thinking of a number between " + fr + " and " + t0 + ", Can you guess it??
Guess :> "
give x
n = nrandom(fr,t0)
if x = n see "

                  Congratulations :D

*****************************************************
     ** Your guess was right You Are Genius :D **
*****************************************************

"
exit
else
see "Oops its not true, you were just few steps"
if x > n see " up :)" else see " down :)" ok
see copy(nl,3)
ok
end

func nRandom s,e
while true
d = random(e)
if d >= s return d ok
end


number = rand(1..10)

puts "Guess the number between 1 and 10"

loop do
  begin
    user_number = Integer(gets)
    if user_number == number
      puts "You guessed it."
      break
    elsif user_number > number
      puts "Too high."
    else
      puts "Too low."
    end
  rescue ArgumentError
    puts "Please enter an integer."
  end
end


use rand::Rng;
use std::cmp::Ordering;
use std::io;

const LOWEST: u32 = 1;
const HIGHEST: u32 = 100;

fn main() {
    let secret_number = rand::thread_rng().gen_range(1..101);

    println!("I have chosen my number between {} and {}. Guess the number!", LOWEST, HIGHEST);

    loop {
        println!("Please input your guess.");

        let mut guess = String::new();

        io::stdin()
            .read_line(&mut guess)
            .expect("Failed to read line");

        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };

        println!("You guessed: {}", guess);

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break;
            }
        }
    }
}


import java.util.Random
import java.util.Scanner

val scan = new Scanner(System.in)
val random = new Random
val (from , to) = (1, 100)
val randomNumber = random.nextInt(to - from + 1) + from
var guessedNumber = 0
printf("The number is between %d and %d.\n", from, to)

do {
  print("Guess what the number is: ")
  guessedNumber = scan.nextInt
  if (guessedNumber > randomNumber) println("Your guess is too high!")
  else if (guessedNumber < randomNumber) println("Your guess is too low!")
  else println("You got it!")
} while (guessedNumber != randomNumber)


(define maximum 5)
(define minimum -5)
(define number (+ (random (- (+ maximum 1) minimum)) minimum))

(display "Pick a number from ")
(display minimum)
(display " through ")
(display maximum)
(display ".\n> ")
(do ((guess (read) (read))) ((eq? guess number))
        (if (or (>= guess maximum) (< guess minimum))
                (display "Out of range!\n> ")
                (begin
                        (if (> guess number)
                                (display "Too high!\n> "))
                        (if (< guess number)
                                (display "Too low!\n> ")))))
(display "Correct!\n")


$ include "seed7_05.s7i";

const integer: lower_limit is 0;
const integer: upper_limit is 100;

const proc: main is func
  local
    var integer: number is 0;
    var integer: guess is 0;
  begin
    number := rand(lower_limit, upper_limit);
    write("Guess the number between " <& lower_limit <& " and " <& upper_limit <& ": ");
    while succeeds(readln(guess)) and number <> guess do
      write("Your guess was too ");
      if number < guess then
        writeln("high.");
      else
        writeln("low.");
      end if;
      write("Try again: ");
    end while;
    if number = guess then
      writeln("You guessed correctly!");
    else
      writeln("You gave up!");
    end if;
  end func;


var number = rand(1..10);
say "Guess the number between 1 and 10";

loop {
    given(var n = Sys.scanln("> ").to_i) {
        when (number)     { say "You guessed it."; break }
        case (n < number) { say "Too low" }
        default           { say "Too high" }
    }
}


number=Math.GetRandomNumber(10)
TextWindow.WriteLine("I just thought of a number between 1 and 10. What is it?")
While guess<>number
  guess=TextWindow.ReadNumber()
  If guess>number Then
    TextWindow.WriteLine("Lower number!")
  EndIf
  If guess<number Then
    TextWindow.WriteLine("Higher number!")
  EndIf
EndWhile
TextWindow.WriteLine("You win!")


'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
	instanceVariableNames: 'min max uiManager tries'
	classVariableNames: ''
	poolDictionaries: ''
	category: 'GuessingGame'!

!GuessingGame methodsFor: 'initialization' stamp: 'EduardoPadoan 10/26/2019 23:51'!
initialize
	uiManager := UIManager default.
	tries := 0! !

!GuessingGame methodsFor: 'services' stamp: 'EduardoPadoan 10/26/2019 23:40'!
alert: aString
	uiManager alert: aString! !

!GuessingGame methodsFor: 'accessing' stamp: 'EduardoPadoan 10/26/2019 23:36'!
max
	^ max! !

!GuessingGame methodsFor: 'accessing' stamp: 'EduardoPadoan 10/26/2019 23:36'!
min
	^ min! !

!GuessingGame methodsFor: 'accessing' stamp: 'EduardoPadoan 10/26/2019 23:36'!
min: anObject
	min := anObject! !

!GuessingGame methodsFor: 'accessing' stamp: 'EduardoPadoan 10/26/2019 23:36'!
max: anObject
	max := anObject! !

!GuessingGame methodsFor: 'playing-main' stamp: 'EduardoPadoan 10/27/2019 00:18'!
play
	| toGuess |
	toGuess := self selectNumber.
	[ :break |
		| choice |
		[
			choice := self getGuessOrExitWith: break.
			choice
				ifNil: [ self alert: 'Invalid Input' ]
				ifNotNil: [
					self incrementTries.
					choice = toGuess
                   ifTrue: [ self congratulateForGuess: choice andExitWith: break ]
                   ifFalse: [ choice > toGuess ifTrue: [ self alert: 'Too high' ]
                                               ifFalse: [ self alert: 'Too low' ] ]
				]
		] repeat.
	] valueWithExit.! !

!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/26/2019 23:39'!
makeRequest: aString
	^ uiManager request: aString! !

!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/26/2019 23:48'!
getGuessOrExitWith: anExitBlock
	^ [(self makeRequest: 'Guess number a between , min,' and ', max, '.') asInteger]
     on: MessageNotUnderstood "nil"
     do: [
         self sayGoodbye.
         anExitBlock value ].! !

!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/26/2019 23:51'!
incrementTries
	tries := tries + 1! !

!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/27/2019 00:05'!
sayGoodbye
	self alert: 'Gave up? Sad.'.! !

!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/27/2019 00:15'!
congratulateForGuess: anInteger andExitWith: anExitBlock
	self alert: 'Correct!! The value was indeed ', anInteger asString, '. Took you only ', tries asString, ' tries.'.
	^ anExitBlock value! !

!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/26/2019 23:35'!
selectNumber
	^ (min to: max) atRandom ! !

"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!

GuessingGame class
	slots: {  }!

!GuessingGame class methodsFor: 'creating' stamp: 'EduardoPadoan 10/27/2019 00:15'!
playFrom: aMinNumber to: aMaxNumber
	self new
		min: aMinNumber;
		max: aMaxNumber;
		play! !


printf("Lower bound: ");
let lowerBound = toint(getline());

printf("Upper bound: ");
let upperBound = toint(getline());

assert(upperBound > lowerBound, "upper bound must be greater than lower bound");

seed(time());
let n = floor(random() * (upperBound - lowerBound) + lowerBound);
var guess;

print();

while true {
    printf("Your guess: ");
    guess = toint(getline());

    if guess < n {
        print("too low");
    } else if guess > n {
        print("too high");
    } else {
        print("You guessed it!");
        break;
    }
}


import Cocoa

var found = false

let randomNum = Int(arc4random_uniform(100) + 1)

println("Guess a number between 1 and 100\n")

while (!found) {
    var fh = NSFileHandle.fileHandleWithStandardInput()

    println("Enter a number: ")
    let data = fh.availableData
    let str = NSString(data: data, encoding: NSUTF8StringEncoding)
    if (str?.integerValue == randomNum) {
        found = true
        println("Well guessed!")
    } else if (str?.integerValue < randomNum) {
        println("Good try but the number is more than that!")
    } else if (str?.integerValue > randomNum) {
        println("Good try but the number is less than that!")
    }
}


set from 1
set to 10
set target [expr {int(rand()*($to-$from+1) + $from)}]
puts "I have thought of a number from $from to $to."
puts "Try to guess it!"
while 1 {
    puts -nonewline "Enter your guess: "
    flush stdout
    gets stdin guess
    if {![string is int -strict $guess] || $guess < $from || $guess > $to} {
	puts "Your guess should be an integer from $from to $to (inclusive)."
    } elseif {$guess > $target} {
	puts "Your guess was too high. Try again!"
    } elseif {$guess < $target} {
	puts "Your guess was too low. Try again!"
    } else {
	puts "Well done! You guessed it."
	break
    }
}


$$ MODE TUSCRIPT
PRINT "Find the luckynumber (7 tries)!"
SET luckynumber=RANDOM NUMBERS (1,100,1)
LOOP round=1,7
SET message=CONCAT ("[",round,"] Please insert a number")
ASK $message: n=""
 IF (n!='digits') THEN
   PRINT "wrong insert: ",n," Please insert a digit"
 ELSEIF (n>100.or.n<1) THEN
   PRINT "wrong insert: ",n," Please insert a number between 1-100"
 ELSEIF (n==#luckynumber) THEN
   PRINT "BINGO"
   EXIT
 ELSEIF (n.gt.#luckynumber) THEN
   PRINT "too big"
 ELSEIF (n.lt.#luckynumber) THEN
   PRINT "too small"
ENDIF
IF (round==7) PRINT/ERROR "You've lost: luckynumber was: ",luckynumber
ENDLOOP


function guess {
  [[ -n $BASH_VERSION ]] && shopt -s extglob
  [[ -n $ZSH_VERSION ]] && set -o KSH_GLOB
  local -i max=${1:-100}
  local -i number=RANDOM%max+1
  local -i guesses=0

  local guess
  while true; do
    echo -n "Guess my number! (range 1 - $max): "
    read guess
    if [[ "$guess" != +([0-9]) ]] || (( guess < 1 || guess > max )); then
      echo "Guess must be a number between 1 and $max."
      continue
    fi
    let guesses+=1
    if (( guess < number )); then
      echo "Too low!"
    elif (( guess == number )); then
      echo "You got it in $guesses guesses!"
      break
    else
      echo "Too high!"
    fi
  done
}


decl int high low
set low 0
set high 100

out "Guess a number between " low " and " high "." endl endl console
decl int target answer i
decl ursa.util.random random
set target (int (+ 1 (+ low (random.getint (int (- high low))))))
while (not (= answer target))
	inc i
	out "Your guess(" i "): " console
	set answer (in int console)

	if (or (< answer low) (> answer high))
		out "  Out of range!" endl console
		continue
	end if
	if (= answer target)
		out "  Ye-Haw!!" endl console
		continue
	end if
	if (< answer target)
		out "  Too low." endl console
	end if
	if (> answer target)
		out "  Too high." endl console
	end if
end while

out endl "Thanks for playing." endl console


void main(){
	const int from = 1;
	const int to = 100;

	int random = Random.int_range(from, to);
	int guess = 0;

	while (guess != random){
		stdout.printf("Guess the target number that's between %d and %d.\n", from, to);

		string? num = stdin.read_line ();
		num.canon("0123456789", '!'); // replaces any character in num that's not in "0123456789" with "!"

		if ("!" in num)
			stdout.printf("Please enter a number!\n");

		else{
			guess = int.parse(num);

			if (guess > random && guess <= to)
				stdout.printf("Too high!\n");
			if (guess < random && guess >= from)
				stdout.printf("Too low!\n");
			if (guess == random)
				stdout.printf("You guess it! You win!\n");
			if (guess < from || guess > to)
				stdout.printf("%d Your guess isn't even in the right range!\n", guess);
		}

	}//while
} // main


Sub GuessTheNumberWithFeedback()
Dim Nbc&, Nbp&, m&, n&, c&

    Randomize Timer
    m = 11
    n = 100
    Nbc = Int((Rnd * (n - m + 1)) + m)
    Do
        c = c + 1
        Nbp = Application.InputBox("Choose a number between " & m & " and " & n & " : ", "Enter your guess", Type:=1)
        Select Case Nbp
            Case Is > Nbc: MsgBox "Higher than target!"
            Case Is < Nbc: MsgBox "Less than target!"
            Case Else: Exit Do
        End Select
    Loop
    MsgBox "Well guessed!" & vbCrLf & "You find : " & Nbc & " in " & c & " guesses!"
End Sub


Dim max,min,secretnum,numtries,usernum
max=100
min=1
numtries=0
Randomize
secretnum = Int((max-min+1)*Rnd+min)

Do While usernum <> secretnum
  usernum = Inputbox("Guess the secret number beween 1-100","Guessing Game")
  If IsEmpty(usernum) Then
    WScript.Quit
  End If
  If IsNumeric(usernum) Then
    numtries = numtries + 1
    usernum = Cint(usernum)
    If usernum < secretnum Then
      Msgbox("The secret number is higher than " + CStr(usernum))
    ElseIf usernum > secretnum Then
      Msgbox("The secret number is lower than " + CStr(usernum))
    Else
      Msgbox("Congratulations, you found the secret number in " + CStr(numtries) + " guesses!")
    End If
  Else
    Msgbox("Please enter a valid number.")
  End If
Loop


import rand.seed
import rand
import os
const (
    lower = 1
    upper = 100
)

fn main() {
    rand.seed(seed.time_seed_array(2))
    n := rand.intn(upper-lower+1) or {0} + lower
    for {
        guess := os.input("Guess integer number from $lower to $upper: ").int()

        if guess < n {
            println("Too low. Try again: ")
        } else if guess > n {
            println("Too high. Try again: ")
        } else {
            println("Well guessed!")
            return
        }
    }
}


import "io" for Stdin, Stdout
import "random" for Random

var rand = Random.new()
var n = rand.int(1, 21) // computer number from 1..20 inclusive, say
System.print("The computer has chosen a number between 1 and 20 inclusive.")
while (true) {
    System.write("  Your guess 1-20 : ")
    Stdout.flush()
    var g = Num.fromString(Stdin.readLine())
    if (!g || g.type != Num || !g.isInteger || g < 1 || g > 20) {
        System.print("  Inappropriate")
    } else if (g > n) {
        System.print("  Too high")
    } else if (g < n) {
        System.print("  Too low")
    } else {
        System.print("  Spot on!")
        break
    }
}


(defun guessing-game (a b)
    ; minimum and maximum, to be supplied by the user
    (defun prompt ()
        (display "What is your guess? ")
        (define guess (read))
        (if (eq guess n) ; EQ, unlike =, won't blow up
                         ; if GUESS isn't a number
            (display "Well guessed!")
            (begin
                (display
                    (cond
                        ((not (integer? guess)) "Come on, that isn't even an integer")
                        ((or (< guess a) (> guess b)) "Now you   k n o w   it won't be that")
                        ((< guess n) "Too low")
                        ((> guess n) "Too high")))
                (display "! Try again...")
                (newline)
                (prompt))))
    (define n (+ (random (- (+ b 1) a)) a))
    (display "I have thought of an integer between ")
    (display a)
    (display " and ")
    (display b)
    (display ". Try to guess it!")
    (newline)
    (prompt))


include c:\cxpl\codes;
int Lo, Hi, C, Guess, Number;

[loop  [Text(0, "Low  limit: ");  Lo:= IntIn(0);
        Text(0, "High limit: ");  Hi:= IntIn(0);
        if Lo < Hi then quit;
        Text(0, "Low limit must be lower!^M^J^G");
       ];
Number:= Ran(Hi-Lo+1)+Lo;
Text(0, "I'm thinking of a number between ");
IntOut(0, Lo);  Text(0, " and ");  IntOut(0, Hi); Text(0, ".^M^J");
repeat  Text(0, "Can you guess the number? ");
        loop    [C:= ChIn(0);
                if C>=^0 & C<=^9 then quit;
                Text(0, "Please enter a number in the given range.^M^J");
                OpenI(0);
                ];
        Backup;  Guess:= IntIn(0);
        Text(0, if Guess = Number then "Correct!"
                else if Guess > Number then "Nope, too high."
                else "You're too low.");
        CrLf(0);
until   Guess = Number;
]


r:=(0).random(10)+1;
while(1){
   n:=ask("Num between 1 & 10: ");
   try{n=n.toInt()}catch{ println("Number please"); continue; }
   if(n==r){ println("Well guessed!"); break; }
   println((n<r) and "small" or "big");
}


var randnum
var guess
randnum & random 1 10
guess = 0
while ne randnum guess
print "I'm thinking of a number between 1 and 10. What is it? "
guess & get
if lt guess randnum
print "Too low. Try again!"
println
endif
if gt guess randnum
print "Too high. Try again!"
println
endif
endwhile
print "Correct number. You win!"


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
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
4 IF g>n THEN PRINT "That guess is too high!": GO TO 2


F hailstone(=n)
   V seq = [n]
   L n > 1
      n = I n % 2 != 0 {3 * n + 1} E n I/ 2
      seq.append(n)
   R seq

V h = hailstone(27)
assert(h.len == 112 & h[0.<4] == [27, 82, 41, 124] & h[(len)-4 ..] == [8, 4, 2, 1])

V m = max((1..99999).map(i -> (hailstone(i).len, i)))
print(‘Maximum length #. was found for hailstone(#.) for numbers <100,000’.format(m[0], m[1]))


*        Hailstone sequence        16/08/2015
HAILSTON CSECT
         USING  HAILSTON,R12
         LR     R12,R15
         ST     R14,SAVER14
BEGIN    L      R11,=F'100000'     nmax
         LA     R8,27              n=27
         LR     R1,R8
         MVI    FTAB,X'01'         ftab=true
         BAL    R14,COLLATZ
         LR     R10,R1             p
         XDECO  R8,XDEC            n
         MVC    BUF1+10(6),XDEC+6
         XDECO  R10,XDEC           p
         MVC    BUF1+18(5),XDEC+7
         LA     R5,6
         LA     R3,0               i
         LA     R4,BUF1+25
LOOPED   L      R2,TAB(R3)         tab(i)
         XDECO  R2,XDEC
         MVC    0(7,R4),XDEC+5
         LA     R3,4(R3)           i=i+1
         LA     R4,7(R4)
         C      R5,=F'4'
         BNE    BCT
         LA     R4,7(R4)
BCT      BCT    R5,LOOPED
         XPRNT  BUF1,80            print hailstone(n)=p,tab(*)
         MVC    LONGEST,=F'0'      longest=0
         MVI    FTAB,X'00'         ftab=true
         LA     R8,1               i
LOOPI    CR     R8,R11             do i=1 to nmax
         BH     ELOOPI
         LR     R1,R8              n
         BAL    R14,COLLATZ
         LR     R10,R1             p
         L      R4,LONGEST
         CR     R4,R10             if longest<p
         BNL    NOTSUP
         ST     R8,IVAL            ival=i
         ST     R10,LONGEST        longest=p
NOTSUP   LA     R8,1(R8)           i=i+1
         B      LOOPI
ELOOPI   EQU    *                  end i
         XDECO  R11,XDEC           maxn
         MVC    BUF2+9(6),XDEC+6
         L      R1,IVAL            ival
         XDECO  R1,XDEC
         MVC    BUF2+28(6),XDEC+6
         L      R1,LONGEST         longest
         XDECO  R1,XDEC
         MVC    BUF2+36(5),XDEC+7
         XPRNT  BUF2,80            print maxn,hailstone(ival)=longest
         B      RETURN
*        *      *                  r1=collatz(r1)
COLLATZ  LR     R7,R1              m=n  (R7)
         LA     R6,1               p=1  (R6)
LOOPP    C      R7,=F'1'           do p=1 by 1 while(m>1)
         BNH    ELOOPP
         CLI    FTAB,X'01'         if ftab
         BNE    NONOK
         C      R6,=F'1'           if p>=1
         BL     NONOK
         C      R6,=F'3'           & p<=3
         BH     NONOK
         LR     R1,R6              then
         BCTR   R1,0
         SLA    R1,2
         ST     R7,TAB(R1)         tab(p)=m
NONOK    LR     R4,R7              m
         N      R4,=F'1'           m&1
         LTR    R4,R4              if m//2=0  (if not(m&1))
         BNZ    ODD
EVEN     SRA    R7,1               m=m/2
         B      EIFM
ODD      LA     R3,3
         MR     R2,R7              *m
         LA     R7,1(R3)           m=m*3+1
EIFM     CLI    FTAB,X'01'         if ftab
         BNE    NEXTP
         MVC    TAB+12,TAB+16      tab(4)=tab(5)
         MVC    TAB+16,TAB+20      tab(5)=tab(6)
         ST     R7,TAB+20          tab(6)=m
NEXTP    LA     R6,1(R6)           p=p+1
         B      LOOPP
ELOOPP   LR     R1,R6              end p; return(p)
         BR     R14                end collatz
*
RETURN   L      R14,SAVER14        restore caller address
         XR     R15,R15            set return code
         BR     R14                return to caller
SAVER14  DS     F
IVAL     DS     F
LONGEST  DS     F
N        DS     F
TAB      DS     6F
FTAB     DS     X
BUF1     DC     CL80'hailstone(nnnnnn)=nnnnn : nnnnnn nnnnnn nnnnnn ...*
               ... nnnnnn nnnnnn nnnnnn'
BUF2     DC     CL80'longest <nnnnnn : hailstone(nnnnnn)=nnnnn'
XDEC     DS     CL12
         YREGS
         END    HAILSTON


CLASS lcl_hailstone DEFINITION.
  PUBLIC SECTION.
    TYPES: tty_sequence TYPE STANDARD TABLE OF i
                             WITH NON-UNIQUE EMPTY KEY,
           BEGIN OF ty_seq_len,
             start TYPE i,
             len   TYPE i,
           END OF ty_seq_len,
           tty_seq_len TYPE HASHED TABLE OF ty_seq_len
                            WITH UNIQUE KEY start.

    CLASS-METHODS:
      get_next
        IMPORTING
          n                           TYPE i
        RETURNING
          VALUE(r_next_hailstone_num) TYPE i,

      get_sequence
        IMPORTING
          start             TYPE i
        RETURNING
          VALUE(r_sequence) TYPE tty_sequence,

      get_longest_sequence_upto
        IMPORTING
          limit                     TYPE i
        RETURNING
          VALUE(r_longest_sequence) TYPE ty_seq_len.

  PRIVATE SECTION.
    TYPES: BEGIN OF ty_seq,
             start TYPE i,
             seq   TYPE tty_sequence,
           END OF ty_seq.
    CLASS-DATA: sequence_buffer TYPE HASHED TABLE OF ty_seq
                                     WITH UNIQUE KEY start.
ENDCLASS.

CLASS lcl_hailstone IMPLEMENTATION.
  METHOD get_next.
    r_next_hailstone_num = COND #( WHEN n MOD 2 = 0 THEN n / 2
                                   ELSE ( 3 * n ) + 1 ).
  ENDMETHOD.

  METHOD get_sequence.
    INSERT start INTO TABLE r_sequence.
    IF start = 1.
      RETURN.
    ENDIF.

    READ TABLE sequence_buffer ASSIGNING FIELD-SYMBOL(<buff>)
                               WITH TABLE KEY start = start.
    IF sy-subrc = 0.
      INSERT LINES OF <buff>-seq INTO TABLE r_sequence.
    ELSE.
      DATA(seq) = get_sequence( get_next( start ) ).
      INSERT LINES OF seq INTO TABLE r_sequence.
      INSERT VALUE ty_seq( start = start
                           seq   = seq ) INTO TABLE sequence_buffer.
    ENDIF.
  ENDMETHOD.

  METHOD get_longest_sequence_upto.
    DATA: max_seq TYPE ty_seq_len,
          act_seq TYPE ty_seq_len.

    DO limit TIMES.
      act_seq-len = lines( get_sequence( sy-index ) ).

      IF act_seq-len > max_seq-len.
        max_seq-len   = act_seq-len.
        max_seq-start = sy-index.
      ENDIF.
    ENDDO.

    r_longest_sequence = max_seq.
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  cl_demo_output=>begin_section( |Hailstone sequence of 27 is: | ).
  cl_demo_output=>write( REDUCE string( INIT result = ``
                                        FOR item IN lcl_hailstone=>get_sequence( 27 )
                                        NEXT result = |{ result } { item }| ) ).
  cl_demo_output=>write( |With length: { lines( lcl_hailstone=>get_sequence( 27 ) ) }| ).
  cl_demo_output=>begin_section( |Longest hailstone sequence upto 100k| ).
  cl_demo_output=>write( lcl_hailstone=>get_longest_sequence_upto( 100000 ) ).
  cl_demo_output=>display( ).


(defun hailstone (len)
    (loop for x = len
             then (if (evenp x)
                         (/ x 2)
                         (+ 1 (* 3 x)))
        collect x until (= x 1)))

;; Must be tail recursive
(defun max-hailstone-start (limit mx curr)
   (declare (xargs :mode :program))
   (if (zp limit)
       (mv mx curr)
       (let ((new-mx (len (hailstone limit))))
          (if (> new-mx mx)
              (max-hailstone-start (1- limit) new-mx limit)
              (max-hailstone-start (1- limit) mx curr)))))


with Ada.Text_IO; use Ada.Text_IO;
procedure hailstone is
	type int_arr is array(Positive range <>) of Integer;
	type int_arr_pt is access all int_arr;

	function hailstones(num:Integer; pt:int_arr_pt) return Integer is
		stones : Integer := 1;
		n : Integer := num;
		begin
		if pt /= null then pt(1) := num; end if;
		while (n/=1) loop
			stones := stones + 1;
			if n mod 2 = 0 then n := n/2;
			else n := (3*n)+1;
			end if;
			if pt /= null then pt(stones) := n; end if;
		end loop;
		return stones;
	end hailstones;

	nmax,stonemax,stones : Integer := 0;
	list : int_arr_pt;
begin
	stones := hailstones(27,null);
	list := new int_arr(1..stones);
	stones := hailstones(27,list);
	put(" 27: "&Integer'Image(stones)); new_line;
	for n in 1..4 loop put(Integer'Image(list(n)));	end loop;
	put(" .... ");
	for n in stones-3..stones loop put(Integer'Image(list(n))); end loop;
	new_line;
	for n in 1..100000 loop
		stones := hailstones(n,null);
		if stones>stonemax then
			nmax := n; stonemax := stones;
		end if;
	end loop;
	put_line(Integer'Image(nmax)&" max @ n= "&Integer'Image(stonemax));
end hailstone;


void
print_hailstone(integer h)
{
    list l;

    while (h ^ 1) {
        lb_p_integer(l, h);
        h = h & 1 ? 3 * h + 1 : h / 2;
    }

    o_form("hailstone sequence for ~ is ~1 ~ ~ ~ .. ~ ~ ~ ~, it is ~ long\n",
           l[0], l[1], l[2], l[3], l[-3], l[-2], l[-1], 1, ~l + 1);
}

void
max_hailstone(integer x)
{
    integer e, i, m;
    index r;

    m = 0;
    i = 1;
    while (i < x) {
        integer h, k, l;

        h = i;
        l = 1;
        while (h ^ 1) {
            if (i_j_integer(k, r, h)) {
                l += k;
                break;
            } else {
                l += 1;
                h = h & 1 ? 3 * h + 1 : h / 2;
            }
        }

        r[i] = l - 1;

        if (m < l) {
            m = l;
            e = i;
        }

        i += 1;
    }

    o_form("hailstone sequence length for ~ is ~\n", e, m);
}

integer
main(void)
{
    print_hailstone(27);
    max_hailstone(100000);

    return 0;
}


begin
    comment Hailstone sequence - Algol 60;
    integer array collatz[1:400]; integer icollatz;

    integer procedure mod(i,j); value i,j; integer i,j;
    mod:=i-(i div j)*j;

    integer procedure hailstone(num);
    value num; integer num;
    begin
        integer i,n;
        icollatz:=1; n:=num; i:=0;
        collatz[icollatz]:=n;
        for i:=i+1 while n notequal 1 do begin
            if mod(n,2)=0 then n:=n div 2
                          else n:=(3*n)+1;
            icollatz:=icollatz+1;
            collatz[icollatz]:=n
        end;
        hailstone:=icollatz
    end hailstone;

    integer i,nn,ncollatz,count,nlongest,nel,nelcur,nnn;
    nn:=27;
    ncollatz:=hailstone(nn);
    outstring(1,"sequence for"); outinteger(1,nn); outstring(1," :\n");
    for i:=1 step 1 until ncollatz do outinteger(1,collatz[i]);
    outstring(1,"\n");
    outstring(1,"number of elements:"); outinteger(1,ncollatz);
    outstring(1,"\n\n");
    nlongest:=0; nel:=0; nnn:=100000;
    for count:=1, count+1 while count<nnn do begin
        nelcur:=hailstone(count);
        if nelcur>nel then begin
            nel:=nelcur;
            nlongest:=count
        end
    end;
    outstring(1,"number <"); outinteger(1,nnn);
    outstring(1,"with the longest sequence:"); outinteger(1,nlongest);
    outstring(1,", with"); outinteger(1,nel); outstring(1,"elements.");
    outstring(1,"\n")
end


MODE LINT = # LONG ... # INT;

PROC hailstone = (INT in n, REF[]LINT array)INT:
(
    INT hs := 1;
    INT index := 0;
    LINT n := in n;

    WHILE n /= 1 DO
        hs +:= 1;
        IF array ISNT REF[]LINT(NIL) THEN array[index +:= 1] := n FI;
        n := IF ODD n THEN 3*n+1 ELSE n OVER 2 FI
    OD;
    IF array ISNT REF[]LINT(NIL) THEN array[index +:= 1] := n FI;
    hs
);

main:
(
    INT j, hmax := 0;
    INT jatmax, n;
    INT border = 4;

    FOR j TO 100000-1 DO
       n := hailstone(j, NIL);
       IF hmax < n THEN
           hmax := n;
           jatmax := j
       FI
    OD;

    [2]INT test := (27, jatmax);
    FOR key TO UPB test DO
        INT val = test[key];
        n := hailstone(val, NIL);
        [n]LINT array;
        n := hailstone(val, array);

        printf(($"[ "n(border)(g(0)", ")" ..."n(border)(", "g(0))"] len="g(0)l$,
            array[:border], array[n-border+1:], n))
        #;free(array) #
    OD;
    printf(($"Max "g(0)" at j="g(0)l$, hmax, jatmax))
# ELLA Algol68RS:
    print(("Max",hmax," at j=",jatmax, new line))
#
)


BEGIN

INTEGER N, LEN, YES, NO, LIMIT, LONGEST, NLONG;

% RETURN P MOD Q %
INTEGER FUNCTION MOD(P, Q);
INTEGER P, Q;
BEGIN
  MOD := P - Q * (P / Q);
END;

% COMPUTE AND OPTIONALLY DISPLAY HAILSTONE SEQUENCE FOR N. %
% RETURN LENGTH OF SEQUENCE OR ZERO ON OVERFLOW. %
INTEGER FUNCTION HAILSTONE(N, DISPLAY);
INTEGER N, DISPLAY;
BEGIN
  INTEGER LEN;
  LEN := 1;
  IF DISPLAY = 1 THEN WRITE("");
  WHILE (N <> 1) AND (N > 0) DO
    BEGIN
      IF DISPLAY = 1 THEN WRITEON(N,"  ");
      IF MOD(N,2) = 0 THEN
         N := N / 2
      ELSE
         N := (N * 3) + 1;
      LEN := LEN + 1;
    END;
  IF DISPLAY = 1 THEN WRITEON(N);
  HAILSTONE := (IF N < 0 THEN 0 ELSE LEN);
END;

% EXERCISE THE FUNCTION %
YES := 1; NO := 0;
WRITE("DISPLAY HAILSTONE SEQUENCE FOR WHAT NUMBER?");
READ(N);
LEN := HAILSTONE(N, YES);
WRITE("SEQUENCE LENGTH =", LEN);

% FIND LONGEST SEQUENCE BEFORE OVERFLOW %
N := 2;
LONGEST := 1;
LEN := 2;
NLONG := 2;
LIMIT := 1000;
WRITE("SEARCHING FOR LONGEST SEQUENCE UP TO N =",LIMIT," ...");
WHILE (N < LIMIT) AND (LEN <> 0) DO
  BEGIN
    LEN := HAILSTONE(N, NO);
    IF LEN > LONGEST THEN
       BEGIN
          LONGEST := LEN;
          NLONG := N;
       END;
    N := N + 1;
  END;
IF LEN = 0 THEN WRITE("SEARCH TERMINATED WITH OVERFLOW AT N =",N-1);
WRITE("MAXIMUM SEQUENCE LENGTH =", LONGEST, " FOR N =", NLONG);

END


begin
    % show some Hailstone Sequence related information                       %
    % calculates the length of the sequence generated by n,                  %
    % if showFirstAndLast is true, the first and last 4 elements of the      %
    % sequence are stored in first and last                                  %
    % hs holds a cache of the upbHs previously calculated sequence lengths   %
    % if showFirstAndLast is false, the cache will be used                   %
    procedure hailstone ( integer value  n
                        ; integer array  first, last ( * )
                        ; integer result length
                        ; integer array  hs          ( * )
                        ; integer value  upbHs
                        ; logical value  showFirstAndLast
                        ) ;
    if not showFirstAndLast and n <= upbHs and hs( n ) not = 0 then begin
        % no need to store the start and end of the sequence and we already  %
        % know the length of the sequence for n                              %
        length := hs( n )
        end
    else begin
        % must calculate the sequence length                                 %
        integer sv;
        for i := 1 until 4 do first( i ) := last( i ) := 0;
        length := 0;
        sv     := n;
        if sv > 0 then begin
            while begin
                length := length + 1;
                if showFirstAndLast then begin
                    if length <= 4 then first( length ) := sv;
                    for lPos := 1 until 3 do last( lPos ) := last( lPos + 1 );
                    last( 4 ) := sv
                    end
                else if sv <= upbHs and hs( sv ) not = 0 then begin
                    % have a known value                                 %
                    length := ( length + hs( sv ) ) - 1;
                    sv     := 1
                end ;
                sv not = 1
            end do begin
                sv := if odd( sv ) then ( 3 * sv ) + 1 else sv div 2
            end while_sv_ne_1 ;
            if n < upbHs then hs( n ) := length
        end if_sv_gt_0
    end hailstone ;
    begin
        % test the hailstone procedure                                       %
        integer HS_CACHE_SIZE;
        HS_CACHE_SIZE := 100000;
        begin
            integer array first, last ( 1 :: 4 );
            integer       length, maxLength, maxNumber;
            integer array hs          ( 1 :: HS_CACHE_SIZE );
            for i := 1 until HS_CACHE_SIZE do hs( i ) := 0;
            hailstone( 27, first, last, length, hs, HS_CACHE_SIZE, true );
            write( i_w := 1, s_w := 0
                 , "27: length ", length, ", first: ["
                 , first( 1 ), " ", first( 2 ), " ", first( 3 ), " ", first( 4 )
                 , "] last: ["
                 , last( 1 ), " ", last( 2 ), " ", last( 3 ), " ", last( 4 )
                 , "]"
                 );
            maxNumber := 0;
            maxLength := 0;
            for n := 1 until 100000 do begin
                hailstone( n, first, last, length, hs, HS_CACHE_SIZE, false );
                if length > maxLength then begin
                    maxNumber := n;
                    maxLength := length
                end if_length_gt_maxLength
            end for_n ;
            write( i_w := 1, s_w := 1, "Maximum sequence length: ", maxLength, " for: ", maxNumber )
        end
    end
end.


⍝ recursive dfn:
dfnHailstone←{
    c←⊃⌽⍵ ⍝ last element
    1=c:1 ⍝ if it is 1, stop.
    ⍵,∇(1+2|c)⊃(c÷2)(1+3×c) ⍝ otherwise pick the next step, and append the result of the recursive call
}

⍝ tradfn version:
∇seq←hailstone n;next
⍝ Returns the hailstone sequence for a given number

seq←n                   ⍝ Init the sequence
:While n≠1
    next←(n÷2) (1+3×n)  ⍝ Compute both possibilities
    n←next[1+2|n]       ⍝ Pick the appropriate next step
    seq,←n              ⍝ Append that to the sequence
:EndWhile
∇


on hailstoneSequence(n)
    script o
        property sequence : {n}
    end script

    repeat until (n = 1)
        if (n mod 2 is 0) then
            set n to n div 2
        else
            set n to 3 * n + 1
        end if
        set end of o's sequence to n
    end repeat

    return o's sequence
end hailstoneSequence

set n to 27
tell hailstoneSequence(n)
    return {n:n, |length of sequence|:(its length), |first 4 numbers|:items 1 thru 4, |last 4 numbers|:items -4 thru -1}
end tell


        .org 0x08000000

        b ProgramStart

        ;cartridge header goes here

;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Program Start

	.equ ramarea, 0x02000000
	.equ CursorX,ramarea
	.equ CursorY,ramarea+1
	.equ hailstoneram,0x02000004

ProgramStart:
	mov sp,#0x03000000			;Init Stack Pointer

	mov r4,#0x04000000  		        ;DISPCNT - LCD Video Controller
	mov r2,#0x403    			;4= Layer 2 on / 3= ScreenMode 3
	str	r2,[r4]         	        ;now the user can see the screen

	bl ResetTextCursors			;set text cursors to top left of screen. This routine, as well as the other I/O
	                                        ;     routines, were omitted to keep this entry short.
	mov r0,#27
	adr r1,HailStoneMessage_Init
	bl PrintString
	bl NewLine
	bl ShowHex32
	bl NewLine
	bl NewLine

	bl Hailstone

                ;function is complete, return the output
	        adr r1,HailStoneMessage_0
		bl PrintString
		bl NewLine
		ldr r1,HailStoneRam_Mirror		;mov r2,0x02000004

		ldr r0,[r1],#4
		bl ShowHex32
		bl NewLine

		ldr r0,[r1],#4
		bl ShowHex32
		bl NewLine

		ldr r0,[r1],#4
		bl ShowHex32
		bl NewLine

		ldr r0,[r1],#4
		bl ShowHex32
		bl NewLine
		bl NewLine

		adr r1,HailStoneMessage_1
		bl PrintString
		bl NewLine

		ldr r0,[r2],#4
		bl ShowHex32
		bl NewLine

		ldr r0,[r2],#4
		bl ShowHex32
		bl NewLine

		ldr r0,[r2],#4
		bl ShowHex32
		bl NewLine

		ldr r0,[r2],#4
		bl ShowHex32
		bl NewLine
		bl NewLine

		adr r1,HailStoneMessage_2
		bl PrintString
		bl NewLine
		mov r0,r3
		bl ShowHex32

forever:
	b forever              ;we're done, so trap the program counter.

Hailstone:
	;input: R0 = n.
	;out: 	r2 = pointer to last 4 entries
	;	r3 = length of sequence

	;reg usage:
	;R1 = scratchpad
	;R3 = counter for entries in the sequence.
	;R5 = pointer to output ram
	stmfd sp!,{r4-r12,lr}

		mov r5,#0x02000000
		add r5,r5,#4
		str r0,[r5],#4				;store in hailstone ram and post-inc by 4
		mov r3,#0
loop_hailstone:
		add r3,r3,#1				;represents number of entries in the sequence
		cmp r0,#1
		beq hailstone_end
		tst r0,#1
		;;;; executes only if r0 was even
		moveq r0,r0,lsr #1			;divide

		;;;; executes only if r0 was odd
		movne r1,r0
		movne r0,r0,lsl #1
		addne r0,r1,r0
		addne r0,r0,#1

		str r0,[r5],#4			;store in hailstone ram, post inc by 4

		b loop_hailstone

hailstone_end:
		sub r5,r5,#16			;subtract 16 to get pointer to last 4 entries.
		mov r2,r5				;output ptr to last 4 entries to r2.
		;pointer to first 4 entries is 0x02000004
		ldmfd sp!,{r4-r12,pc}

HailStoneRam_Mirror:
	.long 0x02000004
HailstoneMessage_Init:
	.byte "Your input was:",255
	.align 4
HailstoneMessage_0:
	.byte "First 4 numbers are:",255
	.align 4
HailstoneMessage_1:
	.byte "Last 4 numbers are:",255
	.align 4
HailstoneMessage_2:
	.byte "Sequence length is:",255
	.align 4

;;;;;;;;;;; EVERYTHING PAST THIS POINT IS JUST I/O ROUTINES FOR PRINTING NUMBERS AND WORDS TO THE GAME BOY ADVANCE'S SCREEN
;;;;;;;;;;; I ASSURE YOU THAT ALL OF IT WORKS BUT CHANCES ARE YOU DIDN'T COME HERE TO SEE THAT.
;;;;;;;;;;; THANKS TO KEITH OF CHIBIAKUMAS.COM FOR WRITING THEM!


hailstone: function [n][
	ret: @[n]
	while [n>1][
		if? 1 = and n 1 -> n: 1+3*n
		else -> n: n/2

		'ret ++ n
	]
	ret
]

print "Hailstone sequence for 27:"
print hailstone 27

maxHailstoneLength: 0
maxHailstone: 0

loop 2..1000 'x [
	l: size hailstone x
	if l>maxHailstoneLength [
		maxHailstoneLength: l
		maxHailstone: x
	]
]

print ["max hailstone sequence found (<100000): of length" maxHailstoneLength "for" maxHailstone]


; Submitted by MasterFocus --- http://tiny.cc/iTunis

; [1] Generate the Hailstone Seq. for a number

List := varNum := 7 ; starting number is 7, not counting elements
While ( varNum > 1 )
  List .= ", " ( varNum := ( Mod(varNum,2) ? (varNum*3)+1 : varNum//2 ) )
MsgBox % List

; [2] Seq. for starting number 27 has 112 elements

Count := 1, List := varNum := 27 ; starting number is 27, counting elements
While ( varNum > 1 )
  Count++ , List .= ", " ( varNum := ( Mod(varNum,2) ? (varNum*3)+1 : varNum//2 ) )
MsgBox % "Sequence:`n" List "`n`nCount: " Count

; [3] Find number<100000 with longest seq. and show both values

MaxNum := Max := 0 ; reset the Maximum variables
TimesToLoop := 100000 ; limit number here is 100000
Offset := 70000 ; offset - use 0 to process from 0 to 100000
Loop, %TimesToLoop%
{
  If ( TimesToLoop < ( varNum := Index := A_Index+Offset ) )
    Break
  text := "Processing...`n-------------------`n"
  text .= "Current starting number: " Index "`n"
  text .= "Current sequence count: " Count
  text .= "`n-------------------`n"
  text .= "Maximum starting number: " MaxNum "`n"
  text .= "Maximum sequence count: " Max " <<" ; text split to avoid long code lines
  ToolTip, %text%
  Count := 1 ; going to count the elements, but no "List" required
  While ( varNum > 1 )
    Count++ , varNum := ( Mod(varNum,2) ? (varNum*3)+1 : varNum//2 )
  If ( Count > Max )
    Max := Count , MaxNum := Index ; set the new maximum values, if necessary
}
ToolTip
MsgBox % "Number: " MaxNum "`nCount: " Max


$Hail = Hailstone(27)
ConsoleWrite("Sequence-Lenght: "&$Hail&@CRLF)
$Big = -1
$Sequenzlenght = -1
For $I = 1 To 100000
	$Hail = Hailstone($i, False)
	If Number($Hail) > $Sequenzlenght Then
	$Sequenzlenght = Number($Hail)
	$Big = $i
	EndIf
Next
ConsoleWrite("Longest Sequence : "&$Sequenzlenght&" from number "&$Big&@CRLF)
Func Hailstone($int, $sequence = True)
	$Counter = 0
	While True
		$Counter += 1
		If $sequence = True Then ConsoleWrite($int & ",")
		If $int = 1 Then ExitLoop
		If Not Mod($int, 2) Then
			$int = $int / 2
		Else
			$int = 3 * $int + 1
		EndIf
		If Not Mod($Counter, 25) AND $sequence = True Then ConsoleWrite(@CRLF)
	WEnd
	If $sequence = True Then ConsoleWrite(@CRLF)
	Return $Counter
EndFunc   ;==>Hailstone


#!/usr/bin/awk -f
function hailstone(v, verbose) {
	n = 1;
	u = v;
	while (1) {
		if (verbose) printf " "u;
		if (u==1) return(n);
		n++;
		if (u%2 > 0 )
			u = 3*u+1;
		else
			u = u/2;
	}
}

BEGIN {
	i = 27;
	printf("hailstone(%i) has %i elements\n",i,hailstone(i,1));
	ix=0;
	m=0;
	for (i=1; i<100000; i++) {
		n = hailstone(i,0);
		if (m<n) {
			m=n;
			ix=i;
		}
	}
	printf("longest hailstone sequence is %i and has %i elements\n",ix,m);
}