task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Vlang
Vlang
import ui   fn main() { ui.message_box('Hello World') }
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Web_68
Web 68
@1Introduction. Define the structure of the program.   @aPROGRAM goodbye world CONTEXT VOID USE standard BEGIN @<Included declarations@> @<Logic at the top level@> END FINISH   @ Include the graphical header file.   @iforms.w@>   @ Program code.   @<Logic...@>= open(LOC FILE,"",arg channel); fl initialize(argc,argv,NIL,0); fl show messages("Goodbye World!"); fl finish   @ Declare the necessary macros.   @<Include...@>= macro fl initialize; macro fl show messages; macro fl finish;   @ The end.
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#Fish
Fish
$
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function MaxElement(a() As Double) As Double Dim max As Double = a(LBound(a)) For i As Integer = LBound(a) + 1 To UBound(a) If a(i) > max Then max = a(i) Next Return max End Function   Dim As Integer i, n Input "How many values are to be input "; n If n < 1 Then End Dim a(1 To n) As Double For i = 1 To n Print " Value"; i; " : "; Input "", a(i) Next Dim max As Double = MaxElement(a()) Print Print "The greatest value is"; max Print Print "Press any key to quit" Sleep  
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#Euler_Math_Toolbox
Euler Math Toolbox
  >ggt(123456795,1234567851) 33 >function myggt (n:index, m:index) ... $ if n<m then {n,m}={m,n}; endif; $ repeat $ k=mod(n,m); $ if k==0 then return m; endif; $ if k==1 then return 1; endif; $ {n,m}={m,k}; $ end; $ endfunction >myggt(123456795,1234567851) 33  
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):   hailstone sequence,   hailstone numbers   3x + 2 mapping,   3n + 1 problem   Collatz sequence   Hasse's algorithm   Kakutani's problem   Syracuse algorithm,   Syracuse problem   Thwaites conjecture   Ulam's problem The hailstone sequence is also known as   hailstone numbers   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). Task Create a routine to generate the hailstone sequence for a number. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.   (But don't show the actual sequence!) See also   xkcd (humourous).   The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).   The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
#Fortran
Fortran
program Hailstone implicit none   integer :: i, maxn integer :: maxseqlen = 0, seqlen integer, allocatable :: seq(:)   call hs(27, seqlen) allocate(seq(seqlen)) call hs(27, seqlen, seq) write(*,"(a,i0,a)") "Hailstone sequence for 27 has ", seqlen, " elements" write(*,"(a,4(i0,a),3(i0,a),i0)") "Sequence = ", seq(1), ", ", seq(2), ", ", seq(3), ", ", seq(4), " ...., ", & seq(seqlen-3), ", ", seq(seqlen-2), ", ", seq(seqlen-1), ", ", seq(seqlen)   do i = 1, 99999 call hs(i, seqlen) if (seqlen > maxseqlen) then maxseqlen = seqlen maxn = i end if end do write(*,*) write(*,"(a,i0,a,i0,a)") "Longest sequence under 100000 is for ", maxn, " with ", maxseqlen, " elements"   deallocate(seq)   contains   subroutine hs(number, length, seqArray) integer, intent(in) :: number integer, intent(out) :: length integer, optional, intent(inout) :: seqArray(:) integer :: n   n = number length = 1 if(present(seqArray)) seqArray(1) = n do while(n /= 1) if(mod(n,2) == 0) then n = n / 2 else n = n * 3 + 1 end if length = length + 1 if(present(seqArray)) seqArray(length) = n end do end subroutine   end program
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#Ring
Ring
  see "h(1) = 1" + nl for nr = 1 to 19 see "h(" + (nr+1) + ") = " + hamming(nr) + nl next see "h(1691) = " + hamming(1690) + nl see nl   func hamming limit h = list(1690) h[1] =1 x2 = 2 x3 = 3 x5 =5 i = 0 j = 0 k =0 for n =1 to limit h[n] = min(x2, min(x3, x5)) if x2 = h[n] i = i +1 x2 =2 *h[i] ok if x3 = h[n] j = j +1 x3 =3 *h[j] ok if x5 = h[n] k = k +1 x5 =5 *h[k] ok next hamming = h[limit] return hamming  
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#X86_Assembly
X86 Assembly
    segment .data   random dd 0 ; Where the random number will be stored guess dd 0 ; Where the user input will be stored   instructions db 10, "Welcome user! The game is simple: Guess a random number (1-10)!", 10, 10 len1 equ $ - instructions ; 1 \n before and 2 \n after instructions for better appearance   wrong db "Not the number :(", 10 len2 equ $ - wrong   correct db "You guessed right, congratulations :D", 10 len3 equ $ - correct   segment .bss   segment .text global main   main: push rbp mov rbp, rsp ; ********** CODE STARTS HERE **********   ;;;;; Random number generator ;;;;;   mov eax, 13 mov ebx, random int 80h mov eax, [ebx] mov ebx, 10 xor edx, edx div ebx inc edx mov [random], edx   ;;;;; Print the instructions ;;;;;   mov eax, 4 mov ebx, 1 mov ecx, instructions mov edx, len1 int 80h   userInput:   ;;;;; Ask user for input ;;;;;   mov eax, 3 xor ebx, ebx mov ecx, instructions mov edx, 1 int 80h mov al, [ecx] cmp al, 48 jl valCheck cmp al, 57 jg valCheck   ;;;;; If number ;;;;;   sub al, 48 xchg eax, [guess] mov ebx, 10 mul ebx add [guess], eax jmp userInput   valCheck:   ;;;;; Else check number ;;;;;   mov eax, 4 inc ebx mov ecx, [guess] cmp ecx, [random] je correctResult   ;;;;; If not equal, "not the number :(" ;;;;;   mov ecx, wrong mov edx, len2 mov DWORD [guess], 0 int 80h jmp userInput   correctResult:   ;;;;; If equal, "congratulations :D" ;;;;;   mov ecx, correct mov edx, len3 int 80h   ;;;;; EXIT ;;;;;   mov rax, 0 mov rsp, rbp pop rbp ret   ; "Guess my number" program by Randomboi (8/8/2021)  
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#Perl
Perl
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";
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#PHP
PHP
function isHappy($n) { while (1) { $total = 0; while ($n > 0) { $total += pow(($n % 10), 2); $n /= 10; } if ($total == 1) return true; if (array_key_exists($total, $past)) return false; $n = $total; $past[$total] = 0; } }   $i = $cnt = 0; while ($cnt < 8) { if (isHappy($i)) { echo "$i "; $cnt++; } $i++; }
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Keg
Keg
Hello world\!
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Wee_Basic
Wee Basic
print 1 at 10,12 "Hello world!" end
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Wren
Wren
import "graphics" for Canvas, Color   class Game { static init() { Canvas.print("Goodbye, World!", 10, 10, Color.white) }   static update() {}   static draw(alpha) {} }
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#Forth
Forth
swap
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Frink
Frink
  println[max[[1,2,3,5,10,20]]]  
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#FunL
FunL
println( max([1,2,3,-1,0]) )
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#Euphoria
Euphoria
function gcd_iter(integer u, integer v) integer t while v do t = u u = v v = remainder(t, v) end while if u < 0 then return -u else return u end if end function
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):   hailstone sequence,   hailstone numbers   3x + 2 mapping,   3n + 1 problem   Collatz sequence   Hasse's algorithm   Kakutani's problem   Syracuse algorithm,   Syracuse problem   Thwaites conjecture   Ulam's problem The hailstone sequence is also known as   hailstone numbers   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). Task Create a routine to generate the hailstone sequence for a number. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.   (But don't show the actual sequence!) See also   xkcd (humourous).   The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).   The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
#Frege
Frege
module Hailstone where   import Data.List (maximumBy)   hailstone :: Int -> [Int] hailstone 1 = [1] hailstone n | even n = n : hailstone (n `div` 2) | otherwise = n : hailstone (n * 3 + 1)   withResult :: (t -> t1) -> t -> (t1, t) withResult f x = (f x, x)   main :: IO () main = do let h27 = hailstone 27 putStrLn $ show $ length h27 let h4 = show $ take 4 h27 let t4 = show $ drop (length h27 - 4) h27 putStrLn ("hailstone 27: " ++ h4 ++ " ... " ++ t4) putStrLn $ show $ maximumBy (comparing fst) $ map (withResult (length . hailstone)) [1..100000]
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#Ruby
Ruby
hamming = Enumerator.new do |yielder| next_ham = 1 queues = [[ 2, []], [3, []], [5, []] ]   loop do yielder << next_ham # or: yielder.yield(next_ham)   queues.each {|m,queue| queue << next_ham * m} next_ham = queues.collect{|m,queue| queue.first}.min queues.each {|m,queue| queue.shift if queue.first==next_ham} end end
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#XBS
XBS
const Range:{Min:number,Max:number} = { Min:number=1, Max:number=10, };   while(true){ set RandomNumber:number = math.random(Range.Min,Range.Max); set Response:string = window->prompt("Enter a number from "+tostring(Range.Min)+" to "+tostring(Range.Max)); if (toint(Response)==RandomNumber){ log("Well guessed!"); stop; } }
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#XLISP
XLISP
(defun guessing-game () (defun prompt () (display "What is your guess? ") (define guess (read)) (if (= guess n) (display "Well guessed!") (begin (display "No...") (newline) (prompt)))) (define n (+ (random 10) 1)) (display "I have thought of a number between 1 and 10. Try to guess it!") (newline) (prompt))
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#Phix
Phix
-- -- 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
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#Picat
Picat
go => println(happy_len(8)).   happy(N) => S = [N], Happy = 1, while (Happy == 1, N > 1) N := sum([to_integer(I)**2 : I in N.to_string()]), if member(N,S) then Happy := 0 else S := S ++ [N] end end, Happy == 1.   happy_len(Limit) = S => S = [], N = 1, while (S.length < Limit) if happy(N) then S := S ++ [N] end, N := N + 1 end.
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Kite
Kite
"#!/usr/local/bin/kite   "Hello world!"|print;
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#X86_Assembly
X86 Assembly
;;; hellowin.asm ;;; ;;; nasm -fwin32 hellowin.asm ;;; link -subsystem:console -out:hellowin.exe -nodefaultlib -entry:main \ ;;; hellowin.obj user32.lib kernel32.lib   global _main extern _MessageBoxA@16 extern _ExitProcess@4   MessageBox equ _MessageBoxA@16 ExitProcess equ _ExitProcess@4   section .text _main: push 0  ; MB_OK push title  ; push message  ; push 0  ; call MessageBox  ; eax = MessageBox(0,message,title,MB_OK); push eax  ; call ExitProcess  ; ExitProcess(eax); message: db 'Goodbye, World',0 title: db 'RosettaCode sample',0  
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#X86-64_Assembly
X86-64 Assembly
  option casemap:none   printf proto :qword, :vararg exit proto :dword ;; curses.h stuff initscr proto ;; WINDOW *initsrc(void); endwin proto ;; int endwin(void); start_color proto ;; int start_color(void); wrefresh proto :qword ;; int wrefresh(WINDOW *w); wgetch proto :qword ;; int wgetch(WINDOW *w) waddnstr proto :qword, :qword, :dword ;; int waddnstr(WINDOW *w, const char *str, int n); ;; Just a wrapper to make printing easier.. println proto :qword, :qword   .code main proc local stdscr:qword   call initscr mov stdscr, rax call start_color invoke println, stdscr, CSTR("Goodbye, World!",10) invoke wgetch, stdscr call endwin invoke exit, 0 ret main endp   println proc wnd:qword, pstr:qword invoke waddnstr, wnd, pstr, -1 invoke wrefresh, wnd ret println endp   end  
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#Fortran
Fortran
MODULE Genericswap IMPLICIT NONE   INTERFACE Swap MODULE PROCEDURE Swapint, Swapreal, Swapstring END INTERFACE   CONTAINS   SUBROUTINE Swapint(a, b) INTEGER, INTENT(IN OUT) :: a, b INTEGER :: temp temp = a ; a = b ; b = temp END SUBROUTINE Swapint   SUBROUTINE Swapreal(a, b) REAL, INTENT(IN OUT) :: a, b REAL :: temp temp = a ; a = b ; b = temp END SUBROUTINE Swapreal   SUBROUTINE Swapstring(a, b) CHARACTER(*), INTENT(IN OUT) :: a, b CHARACTER(len(a)) :: temp temp = a ; a = b ; b = temp END SUBROUTINE Swapstring END MODULE Genericswap   PROGRAM EXAMPLE USE Genericswap IMPLICIT NONE INTEGER :: i1 = 1, i2 = 2 REAL :: r1 = 1.0, r2 = 2.0 CHARACTER(3) :: s1="abc", s2="xyz"   CALL Swap(i1, i2) CALL Swap(r1, r2) CALL Swap(s1, s2)   WRITE(*,*) i1, i2 ! Prints 2 and 1 WRITE(*,*) r1, r2 ! Prints 2.0 and 1.0 WRITE(*,*) s1, s2 ! Prints xyz and abc END PROGRAM EXAMPLE
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Futhark
Futhark
let main (xs: []f64) = reduce f64.max (-f64.inf) xs
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#Excel
Excel
=GCD(A1:E1)
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):   hailstone sequence,   hailstone numbers   3x + 2 mapping,   3n + 1 problem   Collatz sequence   Hasse's algorithm   Kakutani's problem   Syracuse algorithm,   Syracuse problem   Thwaites conjecture   Ulam's problem The hailstone sequence is also known as   hailstone numbers   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). Task Create a routine to generate the hailstone sequence for a number. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.   (But don't show the actual sequence!) See also   xkcd (humourous).   The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).   The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
#Frink
Frink
  hailstone[n] := { results = new array   while n != 1 { results.push[n] if n mod 2 == 0 // n is even? n = n / 2 else n = (3n + 1) }   results.push[1] return results }   longestLen = 0 longestN = 0 for n = 1 to 100000 { seq = hailstone[n] if length[seq] > longestLen { longestLen = length[seq] longestN = n } }   println["$longestN has length $longestLen"]  
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#Run_BASIC
Run BASIC
  dim h(1000000) for i =1 to 20 print hamming(i);" "; next i   print print "Hamming List First(1691) =";chr$(9);hamming(1691) print "Hamming List Last(1000000) =";chr$(9);hamming(1000000)   end   function hamming(limit) h(0) =1 x2 = 2: x3 = 3: x5 =5 i = 0: j = 0: k =0 for n =1 to limit h(n) = min(x2, min(x3, x5)) if x2 = h(n) then i = i +1: x2 =2 *h(i) if x3 = h(n) then j = j +1: x3 =3 *h(j) if x5 = h(n) then k = k +1: x5 =5 *h(k) next n hamming = h(limit -1) end function
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#XPL0
XPL0
code Ran=1, IntIn=10, Text=12; int N, G; [N:= Ran(10)+1; Text(0, "I'm thinking of a number between 1 and 10.^M^J"); loop [Text(0, "Can you guess it? "); G:= IntIn(0); if G=N then quit; Text(0, "Nope, that's not it.^M^J"); ]; Text(0, "Well guessed!^M^J"); ]
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#zkl
zkl
r:=((0).random(10)+1).toString(); while(1){ n:=ask("Num between 1 & 10: "); if(n==r){ println("Well guessed!"); break; } println("Nope") }
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#PHP
PHP
  <?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 . "<br />"; 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"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Guess A Number</title> </head>   <body> <form action="<?=$_SERVER['PHP_SELF'] ?>" method="post" name="guess-a-number"> <label for="guess">Guess A Number:</label><br/ > <input type="text" name="guess" /> <input name="number" type="hidden" value="<?= $number ?>" /> <input name="submit" type="submit" /> </form> </body> </html>  
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#PicoLisp
PicoLisp
(de happy? (N) (let Seen NIL (loop (T (= N 1) T) (T (member N Seen)) (setq N (sum '((C) (** (format C) 2)) (chop (push 'Seen N)) ) ) ) ) )   (let H 0 (do 8 (until (happy? (inc 'H))) (printsp H) ) )
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Kitten
Kitten
"Hello world!" say
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#XPL0
XPL0
[SetVid($13); Text(6, "Goodbye, World!")]
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#XSLT
XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml"/> <xsl:template match="/*"> <!-- Use a template to insert some text into a simple SVG graphic with hideous colors. --> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 200"> <rect x="0" y="0" width="400" height="200" fill="cyan"/> <circle cx="200" cy="100" r="50" fill="yellow"/> <text x="200" y="115" style="font-size: 40px; text-align: center; text-anchor: middle; fill: black;"> <!-- The text inside the element --> <xsl:value-of select="."/> </text> </svg> </xsl:template> </xsl:stylesheet>
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#Free_Pascal
Free Pascal
{$ifdef fpc}{$mode delphi}{$H+}{$endif} { note this is compiled with delphi mode but will only compile in Free Pascal } { Delphi doesn't support this syntax } procedure swap<T>(var left,right:T); var temp:T; begin temp:=left; left:=right; right:=temp; end; var a:string = 'Test'; b:string = 'me'; begin writeln(a:6,b:6); swap<string>(a,b); writeln(a:6,b:6); end.
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#F.C5.8Drmul.C3.A6
Fōrmulæ
10 INPUT "How many items? ", N% 20 DIM ARR(N%) 30 FOR I% = 0 TO N%-1 40 PRINT "Value of item #";I% 50 INPUT ARR(I%) 60 NEXT I% 70 CHAMP = ARR(0) : INDEX = 0 80 FOR I% = 1 TO N%-1 90 IF ARR(I%)>CHAMP THEN CHAMP=ARR(I%):INDEX=I% 100 NEXT I% 110 PRINT "The maximum value was ";CHAMP;" at index ";INDEX;"." 120 END
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#Ezhil
Ezhil
  ## இந்த நிரல் இரு எண்களுக்கு இடையிலான மீச்சிறு பொது மடங்கு (LCM), மீப்பெரு பொது வகுத்தி (GCD) என்ன என்று கணக்கிடும்   நிரல்பாகம் மீபொவ(எண்1, எண்2)   @(எண்1 == எண்2) ஆனால்   ## இரு எண்களும் சமம் என்பதால், அந்த எண்ணேதான் அதன் மீபொவ   பின்கொடு எண்1   @(எண்1 > எண்2) இல்லைஆனால்   சிறியது = எண்2 பெரியது = எண்1   இல்லை   சிறியது = எண்1 பெரியது = எண்2   முடி   மீதம் = பெரியது % சிறியது   @(மீதம் == 0) ஆனால்   ## பெரிய எண்ணில் சிறிய எண் மீதமின்றி வகுபடுவதால், சிறிய எண்தான் மீப்பெரு பொதுவகுத்தியாக இருக்கமுடியும்   பின்கொடு சிறியது   இல்லை   தொடக்கம் = சிறியது - 1   நிறைவு = 1   @(எண் = தொடக்கம், எண் >= நிறைவு, எண் = எண் - 1) ஆக   மீதம்1 = சிறியது % எண்   மீதம்2 = பெரியது % எண்   ## இரு எண்களையும் மீதமின்றி வகுக்கக்கூடிய பெரிய எண்ணைக் கண்டறிகிறோம்   @((மீதம்1 == 0) && (மீதம்2 == 0)) ஆனால்   பின்கொடு எண்   முடி   முடி   முடி   முடி   அ = int(உள்ளீடு("ஓர் எண்ணைத் தாருங்கள் ")) ஆ = int(உள்ளீடு("இன்னோர் எண்ணைத் தாருங்கள் "))   பதிப்பி "நீங்கள் தந்த இரு எண்களின் மீபொவ (மீப்பெரு பொது வகுத்தி, GCD) = ", மீபொவ(அ, ஆ)  
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):   hailstone sequence,   hailstone numbers   3x + 2 mapping,   3n + 1 problem   Collatz sequence   Hasse's algorithm   Kakutani's problem   Syracuse algorithm,   Syracuse problem   Thwaites conjecture   Ulam's problem The hailstone sequence is also known as   hailstone numbers   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). Task Create a routine to generate the hailstone sequence for a number. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.   (But don't show the actual sequence!) See also   xkcd (humourous).   The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).   The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
#FunL
FunL
def hailstone( 1 ) = [1] hailstone( n ) = n # hailstone( if 2|n then n/2 else n*3 + 1 )   if _name_ == '-main-' h27 = hailstone( 27 ) assert( h27.length() == 112 and h27.startsWith([27, 82, 41, 124]) and h27.endsWith([8, 4, 2, 1]) )   val (n, len) = maxBy( snd, [(i, hailstone( i ).length()) | i <- 1:100000] )   println( n, len )
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#Rust
Rust
extern crate num; num::bigint::BigUint;   use std::time::Instant;   fn basic_hamming(n: usize) -> BigUint { let two = BigUint::from(2u8); let three = BigUint::from(3u8); let five = BigUint::from(5u8); let mut h = vec![BigUint::from(0u8); n]; h[0] = BigUint::from(1u8); let mut x2 = BigUint::from(2u8); let mut x3 = BigUint::from(3u8); let mut x5 = BigUint::from(5u8); let mut i = 0usize; let mut j = 0usize; let mut k = 0usize;   // BigUint comparisons are expensive, so do it only as necessary... fn min3(x: &BigUint, y: &BigUint, z: &BigUint) -> (usize, BigUint) { let (cs, r1) = if y == z { (0x6, y) } else if y < z { (2, y) } else { (4, z) }; if x == r1 { (cs | 1, x.clone()) } else if x < r1 { (1, x.clone()) } else { (cs, r1.clone()) } }   let mut c = 1; while c < n { // satisfy borrow checker with extra blocks: { } let (cs, e1) = { min3(&x2, &x3, &x5) }; h[c] = e1; // vector now owns the generated value if (cs & 1) != 0 { i += 1; x2 = &two * &h[i] } if (cs & 2) != 0 { j += 1; x3 = &three * &h[j] } if (cs & 4) != 0 { k += 1; x5 = &five * &h[k] } c += 1; }   match h.pop() { Some(v) => v, _ => panic!("basic_hamming: arg is zero; no elements") } }   fn main() { print!("["); for (i, h) in (1..21).map(basic_hamming).enumerate() { if i != 0 { print!(",") } print!(" {}", h) } println!(" ]"); println!("{}", basic_hamming(1691));   let strt = Instant::now();   let rslt = basic_hamming(1000000);   let elpsd = strt.elapsed(); let secs = elpsd.as_secs(); let millis = (elpsd.subsec_nanos() / 1000000)as u64; let dur = secs * 1000 + millis;   let rs = rslt.to_str_radix(10); let mut s = rs.as_str(); println!("{} digits:", s.len()); while s.len() > 100 { let (f, r) = s.split_at(100); s = r; println!("{}", f); } println!("{}", s);   println!("This last took {} milliseconds", dur); }
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#Zoomscript
Zoomscript
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 ne guess randnum print "Incorrect. Try again!" println endif endwhile print "Correct number. You win!"
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#PicoLisp
PicoLisp
(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") "." ) ) ) ) )
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#Plain_English
Plain English
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.
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#PILOT
PILOT
C :max=8  :n=0  :i=0 *test U :*happy T (a=1):#n C (a=1):i=i+1 C :n=n+1 J (i<max):*test E :   *happy C :a=n  :x=n U :*sumsq C :b=s *loop C :x=a U :*sumsq C :a=s C :x=b U :*sumsq C :x=s U :*sumsq C :b=s J (a<>b):*loop E :   *sumsq C :s=0 *digit C :y=x/10  :z=x-y*10  :s=s+z*#z  :x=y J (x):*digit E :
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Koka
Koka
fun main() { println("Hello world!") }
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Yabasic
Yabasic
open window 200, 100 text 10, 20, "Hello world" color 255, 0, 0 : text 10, 40, "Good bye world", "roman14"
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#zkl
zkl
System.cmd(0'|zenity --info --text="Goodbye, World!"|); // GTK+ pop up System.cmd(0'|notify-send "Goodbye, World!"|); // desktop notification System.cmd(0'|xmessage -buttons Ok:0,"Not sure":1,Cancel:2 -default Ok -nearmouse "Goodbye, World!" -timeout 10|); // X Windows dialog
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#FreeBASIC
FreeBASIC
' FB 1.05.0 #Macro Declare_Swap(T) Sub Swap_##T(ByRef t1 As T, ByRef t2 As T) Dim temp As T = t2 t2 = t1 t1 = temp End Sub #EndMacro   Dim As Integer i, j i = 1 : j = 2   Declare_Swap(Integer) ' expands the macro Swap_Integer(i, j) Print i, j   Dim As String s, t s = "Hello" : t = "World"   Declare_Swap(String) Swap_String(s, t) Print s, t   Print Print "Press any key to exit" Sleep
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#GW-BASIC
GW-BASIC
10 INPUT "How many items? ", N% 20 DIM ARR(N%) 30 FOR I% = 0 TO N%-1 40 PRINT "Value of item #";I% 50 INPUT ARR(I%) 60 NEXT I% 70 CHAMP = ARR(0) : INDEX = 0 80 FOR I% = 1 TO N%-1 90 IF ARR(I%)>CHAMP THEN CHAMP=ARR(I%):INDEX=I% 100 NEXT I% 110 PRINT "The maximum value was ";CHAMP;" at index ";INDEX;"." 120 END
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#F.23
F#
  let rec gcd a b = if b = 0 then abs a else gcd b (a % b)   >gcd 400 600 val it : int = 200
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):   hailstone sequence,   hailstone numbers   3x + 2 mapping,   3n + 1 problem   Collatz sequence   Hasse's algorithm   Kakutani's problem   Syracuse algorithm,   Syracuse problem   Thwaites conjecture   Ulam's problem The hailstone sequence is also known as   hailstone numbers   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). Task Create a routine to generate the hailstone sequence for a number. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.   (But don't show the actual sequence!) See also   xkcd (humourous).   The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).   The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
#Futhark
Futhark
  fun hailstone_step(x: int): int = if (x % 2) == 0 then x/2 else (3*x) + 1   fun hailstone_seq(x: int): []int = let capacity = 100 let i = 1 let steps = replicate capacity (-1) let steps[0] = x loop ((capacity,i,steps,x)) = while x != 1 do let (steps, capacity) = if i == capacity then (concat steps (replicate capacity (-1)), capacity * 2) else (steps, capacity) let x = hailstone_step x let steps[i] = x in (capacity, i+1, steps, x) in #1 (split i steps)   fun hailstone_len(x: int): int = let i = 1 loop ((i,x)) = while x != 1 do (i+1, hailstone_step x) in i   fun max (x: int) (y: int): int = if x < y then y else x   fun main (x: int) (n: int): ([]int, int) = (hailstone_seq x, reduce max 0 (map hailstone_len (map (1+) (iota (n-1)))))  
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#Scala
Scala
class Hamming extends Iterator[BigInt] { import scala.collection.mutable.Queue val qs = Seq.fill(3)(new Queue[BigInt]) def enqueue(n: BigInt) = qs zip Seq(2, 3, 5) foreach { case (q, m) => q enqueue n * m } def next = { val n = qs map (_.head) min; qs foreach { q => if (q.head == n) q.dequeue } enqueue(n) n } def hasNext = true qs foreach (_ enqueue 1) }
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#PowerShell
PowerShell
  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)  
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#PL.2FI
PL/I
test: proc options (main); /* 19 November 2011 */ declare (i, j, n, m, nh initial (0) ) fixed binary (31);   main_loop: do j = 1 to 100; n = j; do i = 1 to 100; m = 0; /* Form the sum of squares of the digits. */ do until (n = 0); m = m + mod(n, 10)**2; n = n/10; end; if m = 1 then do; put skip list (j || ' is a happy number'); nh = nh + 1; if nh = 8 then return; iterate main_loop; end; n = m; /* Replace n with the new number formed from digits. */ end; end; end test;  
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#KonsolScript
KonsolScript
function main() { Konsol:Log("Hello world!") }
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#Frink
Frink
  [b,a] = [a,b]  
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#GAP
GAP
# Built-in   L := List([1 .. 100], n -> Random(1, 10));   MaximumList(L); # 10
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   // function, per task description func largest(a []int) (lg int, ok bool) { if len(a) == 0 { return } lg = a[0] for _, e := range a[1:] { if e > lg { lg = e } } return lg, true }   func main() { // random size slice rand.Seed(time.Now().UnixNano()) a := make([]int, rand.Intn(11)) for i := range a { a[i] = rand.Intn(101) - 100 // fill with random numbers }   fmt.Println(a) lg, ok := largest(a) if ok { fmt.Println(lg) } else { fmt.Println("empty list. no maximum.") } }
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#Factor
Factor
: gcd ( a b -- c ) [ abs ] [ [ nip ] [ mod ] 2bi gcd ] if-zero ;
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):   hailstone sequence,   hailstone numbers   3x + 2 mapping,   3n + 1 problem   Collatz sequence   Hasse's algorithm   Kakutani's problem   Syracuse algorithm,   Syracuse problem   Thwaites conjecture   Ulam's problem The hailstone sequence is also known as   hailstone numbers   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). Task Create a routine to generate the hailstone sequence for a number. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.   (But don't show the actual sequence!) See also   xkcd (humourous).   The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).   The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
#F.C5.8Drmul.C3.A6
Fōrmulæ
CollatzSequence := function(n) local v; v := [ n ]; while n > 1 do if IsEvenInt(n) then n := QuoInt(n, 2); else n := 3*n + 1; fi; Add(v, n); od; return v; end;   CollatzLength := function(n) local m; m := 1; while n > 1 do if IsEvenInt(n) then n := QuoInt(n, 2); else n := 3*n + 1; fi; m := m + 1; od; return m; end;   CollatzMax := function(a, b) local n, len, nmax, lmax; lmax := 0; for n in [a .. b] do len := CollatzLength(n); if len > lmax then nmax := n; lmax := len; fi; od; return [ nmax, lmax ]; end;   CollatzSequence(27); # [ 27, 82, 41, 124, 62, 31, 94, 47, 142, 71, 214, 107, 322, 161, 484, 242, 121, 364, 182, 91, 274, 137, 412, 206, # 103, 310, 155, 466, 233, 700, 350, 175, 526, 263, 790, 395, 1186, 593, 1780, 890, 445, 1336, 668, 334, 167, 502, # 251, 754, 377, 1132, 566, 283, 850, 425, 1276, 638, 319, 958, 479, 1438, 719, 2158, 1079, 3238, 1619, 4858, 2429, # 7288, 3644, 1822, 911, 2734, 1367, 4102, 2051, 6154, 3077, 9232, 4616, 2308, 1154, 577, 1732, 866, 433, 1300, # 650, 325, 976, 488, 244, 122, 61, 184, 92, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1 ] CollatzLength(27); # 112   CollatzMax(1, 100); # [ 97, 119 ] CollatzMax(1, 1000); # [ 871, 179 ] CollatzMax(1, 10000); # [ 6171, 262 ] CollatzMax(1, 100000); # [ 77031, 351 ] CollatzMax(1, 1000000); # [ 837799, 525 ]
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#Scheme
Scheme
(define-syntax lons (syntax-rules () ((_ lar ldr) (delay (cons lar (delay ldr))))))   (define (lar lons) (car (force lons)))   (define (ldr lons) (force (cdr (force lons))))   (define (lap proc . llists) (lons (apply proc (map lar llists)) (apply lap proc (map ldr llists))))   (define (take n llist) (if (zero? n) (list) (cons (lar llist) (take (- n 1) (ldr llist)))))   (define (llist-ref n llist) (if (= n 1) (lar llist) (llist-ref (- n 1) (ldr llist))))   (define (merge llist-1 . llists) (define (merge-2 llist-1 llist-2) (cond ((null? llist-1) llist-2) ((null? llist-2) llist-1) ((< (lar llist-1) (lar llist-2)) (lons (lar llist-1) (merge-2 (ldr llist-1) llist-2))) ((> (lar llist-1) (lar llist-2)) (lons (lar llist-2) (merge-2 llist-1 (ldr llist-2)))) (else (lons (lar llist-1) (merge-2 (ldr llist-1) (ldr llist-2)))))) (if (null? llists) llist-1 (apply merge (cons (merge-2 llist-1 (car llists)) (cdr llists)))))   (define hamming (lons 1 (merge (lap (lambda (x) (* x 2)) hamming) (lap (lambda (x) (* x 3)) hamming) (lap (lambda (x) (* x 5)) hamming))))   (display (take 20 hamming)) (newline) (display (llist-ref 1691 hamming)) (newline) (display (llist-ref 1000000 hamming)) (newline)
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#Prolog
Prolog
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!") ).
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#PL.2FM
PL/M
100H:   /* FIND SUM OF SQUARE OF DIGITS OF NUMBER */ DIGIT$SQUARE: PROCEDURE (N) BYTE; DECLARE (N, T, D) BYTE; T = 0; DO WHILE N > 0; D = N MOD 10; T = T + D * D; N = N / 10; END; RETURN T; END DIGIT$SQUARE;   /* CHECK IF NUMBER IS HAPPY */ HAPPY: PROCEDURE (N) BYTE; DECLARE (N, I) BYTE; DECLARE FLAG (256) BYTE;   DO I=0 TO 255; FLAG(I) = 0; END;   DO WHILE NOT FLAG(N); FLAG(N) = 1; N = DIGIT$SQUARE(N); END;   RETURN N = 1; END HAPPY;   /* CP/M BDOS CALL */ BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;   /* PRINT STRING */ PRINT: PROCEDURE (STR); DECLARE STR ADDRESS; CALL BDOS(9, STR); END PRINT;   /* PRINT NUMBER */ PRINT$NUMBER: PROCEDURE (N); DECLARE S (6) BYTE INITIAL ('...',13,10,'$'); DECLARE P ADDRESS; DECLARE (N, C BASED P) BYTE; P = .S(3); DIGIT: P = P - 1; C = (N MOD 10) + '0'; N = N / 10; IF N > 0 THEN GO TO DIGIT; CALL PRINT(P); END PRINT$NUMBER;   /* FIND FIRST 8 HAPPY NUMBERS */ DECLARE SEEN BYTE INITIAL (0); DECLARE N BYTE INITIAL (1);   DO WHILE SEEN < 8; IF HAPPY(N) THEN DO; CALL PRINT$NUMBER(N); SEEN = SEEN + 1; END; N = N + 1; END;   CALL BDOS(0,0); EOF
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Kotlin
Kotlin
fun main() { println("Hello world!") }
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#FutureBasic
FutureBasic
window 1, @"Generic Swap", (0,0,480,270)   text ,,,,, 60   long i, j double x, y CFStringRef a, b   i = 1059 : j = 62 print i, j swap i, j print i, j   print   x = 1.23 : y = 4.56 print x, y swap x, y print x, y   print   a = @"Hello" : b = @"World!" print a, b swap a, b print a, b   HandleEvents  
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Golfscript
Golfscript
{$-1=}:max; [1 4 8 42 6 3]max # Example usage
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Groovy
Groovy
println ([2,4,0,3,1,2,-12].max())
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#FALSE
FALSE
10 15$ [0=~][$@$@$@\/*-$]#%. { gcd(10,15)=5 }
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):   hailstone sequence,   hailstone numbers   3x + 2 mapping,   3n + 1 problem   Collatz sequence   Hasse's algorithm   Kakutani's problem   Syracuse algorithm,   Syracuse problem   Thwaites conjecture   Ulam's problem The hailstone sequence is also known as   hailstone numbers   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). Task Create a routine to generate the hailstone sequence for a number. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.   (But don't show the actual sequence!) See also   xkcd (humourous).   The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).   The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
#GAP
GAP
CollatzSequence := function(n) local v; v := [ n ]; while n > 1 do if IsEvenInt(n) then n := QuoInt(n, 2); else n := 3*n + 1; fi; Add(v, n); od; return v; end;   CollatzLength := function(n) local m; m := 1; while n > 1 do if IsEvenInt(n) then n := QuoInt(n, 2); else n := 3*n + 1; fi; m := m + 1; od; return m; end;   CollatzMax := function(a, b) local n, len, nmax, lmax; lmax := 0; for n in [a .. b] do len := CollatzLength(n); if len > lmax then nmax := n; lmax := len; fi; od; return [ nmax, lmax ]; end;   CollatzSequence(27); # [ 27, 82, 41, 124, 62, 31, 94, 47, 142, 71, 214, 107, 322, 161, 484, 242, 121, 364, 182, 91, 274, 137, 412, 206, # 103, 310, 155, 466, 233, 700, 350, 175, 526, 263, 790, 395, 1186, 593, 1780, 890, 445, 1336, 668, 334, 167, 502, # 251, 754, 377, 1132, 566, 283, 850, 425, 1276, 638, 319, 958, 479, 1438, 719, 2158, 1079, 3238, 1619, 4858, 2429, # 7288, 3644, 1822, 911, 2734, 1367, 4102, 2051, 6154, 3077, 9232, 4616, 2308, 1154, 577, 1732, 866, 433, 1300, # 650, 325, 976, 488, 244, 122, 61, 184, 92, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1 ] CollatzLength(27); # 112   CollatzMax(1, 100); # [ 97, 119 ] CollatzMax(1, 1000); # [ 871, 179 ] CollatzMax(1, 10000); # [ 6171, 262 ] CollatzMax(1, 100000); # [ 77031, 351 ] CollatzMax(1, 1000000); # [ 837799, 525 ]
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i";   const func bigInteger: min (in bigInteger: a, in bigInteger: b, in bigInteger: c) is func result var bigInteger: min is 0_; begin if a < b then min := a; else min := b; end if; if c < min then min := c; end if; end func;   const func bigInteger: hamming (in integer: n) is func result var bigInteger: hammingNum is 1_; local var array bigInteger: hammingNums is 0 times 0_; var integer: index is 0; var bigInteger: x2 is 2_; var bigInteger: x3 is 3_; var bigInteger: x5 is 5_; var integer: i is 1; var integer: j is 1; var integer: k is 1; begin hammingNums := n times 1_; for index range 2 to n do hammingNum := min(x2, x3, x5); hammingNums[index] := hammingNum; if x2 = hammingNum then incr(i); x2 := 2_ * hammingNums[i]; end if; if x3 = hammingNum then incr(j); x3 := 3_ * hammingNums[j]; end if; if x5 = hammingNum then incr(k); x5 := 5_ * hammingNums[k]; end if; end for; end func;   const proc: main is func local var integer: n is 0; begin for n range 1 to 20 do write(hamming(n) <& " "); end for; writeln; writeln(hamming(1691)); writeln(hamming(1000000)); end func;
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#PureBasic
PureBasic
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
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#Potion
Potion
sqr = (n): n * n.   isHappy = (n) : loop : if (n == 1): return true. if (n == 4): return false. sum = 0 n = n string n length times (i): sum = sum + sqr(n(i) number integer). n = sum . .   firstEight = () i = 0 while (firstEight length < 8) : i++ if (isHappy(i)): firstEight append(i). . firstEight string print
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#KQL
KQL
print 'Hello world!'
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#F.C5.8Drmul.C3.A6
Fōrmulæ
Public Sub Main() Dim vA As Variant = " World" Dim vB As Variant = 1   Swap vA, vB   Print vA; vB   End
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Haskell
Haskell
my_max = maximum
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#hexiscript
hexiscript
fun greatest a let l len a let max a[0] for let i 1; i < l; i++ if max < a[i] let max a[i] endif endfor return max endfun
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#Fantom
Fantom
  class Main { static Int gcd (Int a, Int b) { a = a.abs b = b.abs while (b > 0) { t := a a = b b = t % b } return a }   public static Void main() { echo ("GCD of 51, 34 is: " + gcd(51, 34)) } }  
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#Fermat
Fermat
GCD(a,b)
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):   hailstone sequence,   hailstone numbers   3x + 2 mapping,   3n + 1 problem   Collatz sequence   Hasse's algorithm   Kakutani's problem   Syracuse algorithm,   Syracuse problem   Thwaites conjecture   Ulam's problem The hailstone sequence is also known as   hailstone numbers   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). Task Create a routine to generate the hailstone sequence for a number. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.   (But don't show the actual sequence!) See also   xkcd (humourous).   The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).   The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
#Go
Go
package main   import "fmt"   // 1st arg is the number to generate the sequence for. // 2nd arg is a slice to recycle, to reduce garbage. func hs(n int, recycle []int) []int { s := append(recycle[:0], n) for n > 1 { if n&1 == 0 { n = n / 2 } else { n = 3*n + 1 } s = append(s, n) } return s }   func main() { seq := hs(27, nil) fmt.Printf("hs(27): %d elements: [%d %d %d %d ... %d %d %d %d]\n", len(seq), seq[0], seq[1], seq[2], seq[3], seq[len(seq)-4], seq[len(seq)-3], seq[len(seq)-2], seq[len(seq)-1])   var maxN, maxLen int for n := 1; n < 100000; n++ { seq = hs(n, seq) if len(seq) > maxLen { maxN = n maxLen = len(seq) } } fmt.Printf("hs(%d): %d elements\n", maxN, maxLen) }
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#Sidef
Sidef
func ham_gen { var s = [[1], [1], [1]] var m = [2, 3, 5]   func { var n = [s[0][0], s[1][0], s[2][0]].min { |i| s[i].shift if (s[i][0] == n) s[i].append(n * m[i]) } << ^3 return n } }   var h = ham_gen()   var i = 20; say i.of { h() }.join(' ')   { h() } << (i+1 ..^ 1691) say h()
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#Python
Python
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.")
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#PowerShell
PowerShell
function happy([int] $n) { $a=@() for($i=2;$a.count -lt $n;$i++) { $sum=$i $hist=@{} while( $hist[$sum] -eq $null ) { if($sum -eq 1) { $a+=$i } $hist[$sum]=$sum $sum2=0 foreach($j in $sum.ToString().ToCharArray()) { $k=([int]$j)-0x30 $sum2+=$k*$k } $sum=$sum2 } } $a -join ',' }
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#KSI
KSI
  `plain 'Hello world!' #echo #  
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#Gambas
Gambas
Public Sub Main() Dim vA As Variant = " World" Dim vB As Variant = 1   Swap vA, vB   Print vA; vB   End
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#HicEst
HicEst
  max_value = MAX( -123, 234.56, 345.678, -456E3, -455) ! built-in function MAX(...)   ! or for an array: max_value = MAX( array_of_values )   ! or to find a maximum value in a file named filename: CHARACTER List, filename='Greatest element of a list.hic' ! filename contains this script REAL values(1) ! unknown number of values, allocate more below   OPEN(FIle=filename, BINary, LENgth=len) ALLOCATE(values, len/2) ! number of values <= half byte count of file ! read all values, returns item count in values_found: READ(FIle=filename, ItemS=values_found, CLoSe=1) values ! no Format needed for plain text numbers   max_value = MAX(values)   ! write values found in filename and result to spreadsheet type dialog window: DLG(Text=values, Text=max_value, TItle=values_found)   WRITE(ClipBoard, Name) max_value, values_found, values ! pasted to line below ! max_value=345.678; values_found=30; values(1)=-123; values(2)=234.56; values(3)=345.678; values(4)=-456E3; values(5)=-455; values(6)=1; values(7)=2; values(8)=1; values(9)=0; values(10)=0; ...truncated END  
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#Forth
Forth
: gcd ( a b -- n ) begin dup while tuck mod repeat drop ;
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):   hailstone sequence,   hailstone numbers   3x + 2 mapping,   3n + 1 problem   Collatz sequence   Hasse's algorithm   Kakutani's problem   Syracuse algorithm,   Syracuse problem   Thwaites conjecture   Ulam's problem The hailstone sequence is also known as   hailstone numbers   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). Task Create a routine to generate the hailstone sequence for a number. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.   (But don't show the actual sequence!) See also   xkcd (humourous).   The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).   The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
#Groovy
Groovy
def hailstone = { long start -> def sequence = [] while (start != 1) { sequence << start start = (start % 2l == 0l) ? start / 2l : 3l * start + 1l } sequence << start }
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#Smalltalk
Smalltalk
Object subclass: Hammer [ Hammer class >> hammingNumbers: howMany [ |h i j k x2 x3 x5| h := OrderedCollection new. i := 0. j := 0. k := 0. h add: 1. x2 := 2. x3 := 2. x5 := 5. [ ( h size) < howMany ] whileTrue: [ |m| m := { x2. x3. x5 } sort first. (( h indexOf: m ) = 0) ifTrue: [ h add: m ]. ( x2 = (h last) ) ifTrue: [ i := i + 1. x2 := 2 * (h at: i) ]. ( x3 = (h last) ) ifTrue: [ j := j + 1. x3 := 3 * (h at: j) ]. ( x5 = (h last) ) ifTrue: [ k := k + 1. x5 := 5 * (h at: k) ]. ]. ^ h sort ] ].   (Hammer hammingNumbers: 20) displayNl. (Hammer hammingNumbers: 1690) last displayNl.
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#Quackery
Quackery
[ 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 ( --> )
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#R
R
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) }
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#Prolog
Prolog
happy_numbers(L, Nb) :- % creation of the list length(L, Nb), % Process of this list get_happy_number(L, 1).     % the game is over get_happy_number([], _).   % querying the newt happy_number get_happy_number([H | T], N) :- N1 is N+1, (is_happy_number(N) -> H = N, get_happy_number(T, N1); get_happy_number([H | T], N1)).   % we must memorized the numbers reached is_happy_number(N) :- is_happy_number(N, [N]).   % a number is happy when we get 1 is_happy_number(N, _L) :- get_next_number(N, 1), !.   % or when this number is not already reached ! is_happy_number(N, L) :- get_next_number(N, NN), \+member(NN, L), is_happy_number(NN, [NN | L]).   % Process of the next number from N get_next_number(N, NewN) :- get_list_digits(N, LD), maplist(square, LD, L), sumlist(L, NewN).   get_list_digits(N, LD) :- number_chars(N, LCD), maplist(number_chars_, LD, LCD).   number_chars_(D, CD) :- number_chars(D, [CD]).   square(N, SN) :- SN is N * N.
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Lambdatalk
Lambdatalk
  Hello world! {h1 Hello world!} _h1 Hello world!\n  
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#Gecho
Gecho
  1 !0 2 !1  
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Hoon
Hoon
:-  %say |= [^ [a=(list ,@) ~] ~] :-  %noun (snag 0 (sort a gte))
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#i
i
concept largest(l) { large = l[0] for element in l if element > large large = element end end return large }   software { print(largest([23, 1313, 21, 35757, 4, 434, 232, 2, 2342])) }
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#Fortran
Fortran
recursive function gcd_rec(u, v) result(gcd) integer :: gcd integer, intent(in) :: u, v   if (mod(u, v) /= 0) then gcd = gcd_rec(v, mod(u, v)) else gcd = v end if end function gcd_rec
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):   hailstone sequence,   hailstone numbers   3x + 2 mapping,   3n + 1 problem   Collatz sequence   Hasse's algorithm   Kakutani's problem   Syracuse algorithm,   Syracuse problem   Thwaites conjecture   Ulam's problem The hailstone sequence is also known as   hailstone numbers   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). Task Create a routine to generate the hailstone sequence for a number. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.   (But don't show the actual sequence!) See also   xkcd (humourous).   The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).   The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
#Haskell
Haskell
import Data.List (maximumBy) import Data.Ord (comparing)   -------------------- HAILSTONE SEQUENCE ------------------   collatz :: Int -> Int collatz n | even n = n `div` 2 | otherwise = 1 + 3 * n   hailstone :: Int -> [Int] hailstone = takeWhile (1 /=) . iterate collatz   longestChain :: Int longestChain = fst $ maximumBy (comparing snd) $ (,) <*> (length . hailstone) <$> [1 .. 100000]   --------------------------- TEST ------------------------- main :: IO () main = mapM_ putStrLn [ "Collatz sequence for 27: ", (show . hailstone) 27, "The number " <> show longestChain, "has the longest hailstone sequence", "for any number less then 100000. ", "The sequence has length: " <> (show . length . hailstone $ longestChain) ]