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
#ScratchScript
ScratchScript
pos -100 70 print "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
#Seed7
Seed7
$ include "seed7_05.s7i"; include "draw.s7i"; include "keybd.s7i"; include "bitmapfont.s7i"; include "stdfont24.s7i"; include "pixmap_file.s7i";   const proc: main is func local var text: screen is STD_NULL; begin screen(400, 100); clear(curr_win, white); KEYBOARD := GRAPH_KEYBOARD; screen := openPixmapFontFile(curr_win); color(screen, black, white); setFont(screen, stdFont24); setPosXY(screen, 68, 60); write(screen, "Goodbye, World"); ignore(getc(KEYBOARD)); end func;
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] Reference Converting Between Gray and Binary Codes. It includes step-by-step animations.
#Scala
Scala
def encode(n: Int) = (n ^ (n >>> 1)).toBinaryString def decode(s: String) = Integer.parseInt( s.scanLeft(0)(_ ^ _.asDigit).tail.mkString , 2)   println("decimal binary gray decoded") for (i <- 0 to 31; g = encode(i)) println("%7d  %6s  %5s  %7s".format(i, i.toBinaryString, g, decode(g)))  
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] Reference Converting Between Gray and Binary Codes. It includes step-by-step animations.
#Scratch
Scratch
$ include "seed7_05.s7i"; include "bin32.s7i";   const func integer: grayEncode (in integer: n) is return ord(bin32(n) >< bin32(n >> 1));   const func integer: grayDecode (in var integer: n) is func result var integer: decoded is 0; begin decoded := n; while n > 1 do n >>:= 1; decoded := ord(bin32(decoded) >< bin32(n)); end while; end func;   const proc: main is func local var integer: i is 0; begin for i range 0 to 32 do writeln(i <& " => " <& grayEncode(i) radix 2 lpad0 6 <& " => " <& grayDecode(grayEncode(i))); end for; end func;
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!
#dc
dc
1 2 SaSbLaLb f =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.
#E
E
pragma.enable("accumulator") # non-finalized syntax feature   def max([first] + rest) { return accum first for x in rest { _.max(x) } }
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.
#D
D
import std.stdio, std.numeric;   long myGCD(in long x, in long y) pure nothrow @nogc { if (y == 0) return x; return myGCD(y, x % y); }   void main() { gcd(15, 10).writeln; // From Phobos. myGCD(15, 10).writeln; }
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).
#Eiffel
Eiffel
  class APPLICATION   create make   feature   make local test: LINKED_LIST [INTEGER] count, number, te: INTEGER do create test.make test := hailstone_sequence (27) io.put_string ("There are " + test.count.out + " elements in the sequence for the number 27.") io.put_string ("%NThe first 4 elements are: ") across 1 |..| 4 as t loop io.put_string (test [t.item].out + "%T") end io.put_string ("%NThe last 4 elements are: ") across (test.count - 3) |..| test.count as t loop io.put_string (test [t.item].out + "%T") end across 1 |..| 99999 as c loop test := hailstone_sequence (c.item) te := test.count if te > count then count := te number := c.item end end io.put_string ("%NThe longest sequence for numbers below 100000 is " + count.out + " for the number " + number.out + ".") end   hailstone_sequence (n: INTEGER): LINKED_LIST [INTEGER] -- Members of the Hailstone Sequence starting from 'n'. require n_is_positive: n > 0 local seq: INTEGER do create Result.make from seq := n until seq = 1 loop Result.extend (seq) if seq \\ 2 = 0 then seq := seq // 2 else seq := ((3 * seq) + 1) end end Result.extend (seq) ensure sequence_terminated: Result.last = 1 end   end  
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).
#Picat
Picat
go => println([hamming(I) : I in 1..20]), time(println(hamming_1691=hamming(1691))), time(println(hamming_1000000=hamming(1000000))), nl.   hamming(1) = 1. hamming(2) = 2. hamming(3) = 3. hamming(N) = Hamming => A = new_array(N), [Next2, Next3, Next5] = [2,3,5], A[1] := Next2, A[2] := Next3, A[3] := Next5, I = 0, J = 0, K = 0, M = 1, while (M < N) A[M] := min([Next2,Next3,Next5]), if A[M] == Next2 then I := I+1, Next2 := 2*A[I] end, if A[M] == Next3 then J := J+1, Next3 := 3*A[J] end, if A[M] == Next5 then K := K+1, Next5 := 5*A[K] end, M := M + 1 end, Hamming = A[N-1].
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
#Ring
Ring
    ### Bert Mariani ### 2018-03-01 ### Guess_My_Number   myNumber = random(10) answer = 0   See "Guess my number between 1 and 10"+ nl   while answer != myNumber See "Your guess: " Give answer   if answer = myNumber See "Well done! You guessed it! "+ myNumber +nl else See "Try again"+ nl ok   if answer = 0 See "Give up. My number is: "+ myNumber +nl ok 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
#RPL
RPL
  DIR INITIALIZE << { C G R } PURGE RAND 10 * 1 + IP 'R' STO GUESSING >> GUESSING << "Pick a number between 1 and 10." "" INPUT OBJ-> 'G' STO IF G R == THEN CLLCD "You got it!" 1 DISP 7 FREEZE 0 WAIT CLLCD CONTINUE ELSE IF G R < THEN CLLCD "Try a larger number." 1 DISP 7 FREEZE 0 WAIT GUESSING ELSE CLLCD "Try a smaller number." 1 DISP 7 FREEZE 0 WAIT GUESSING END END >> CONTINUE << "Do you want to continue? (0/1)" "" INPUT OBJ-> 'C' STO IF C 1 == THEN INITIALIZE ELSE CLEAR END >> END
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#Tcl
Tcl
package require Tcl 8.5 set a {-1 -2 3 5 6 -2 -1 4 -4 2 -1}   # from the Perl solution proc maxsumseq1 {a} { set len [llength $a] set maxsum 0   for {set start 0} {$start < $len} {incr start} { for {set end $start} {$end < $len} {incr end} { set sum 0 incr sum [expr [join [lrange $a $start $end] +]] if {$sum > $maxsum} { set maxsum $sum set maxsumseq [lrange $a $start $end] } } } return $maxsumseq }   # from the Python solution proc maxsumseq2 {sequence} { set start -1 set end -1 set maxsum_ 0 set sum_ 0 for {set i 0} {$i < [llength $sequence]} {incr i} { set x [lindex $sequence $i] incr sum_ $x if {$maxsum_ < $sum_} { set maxsum_ $sum_ set end $i } elseif {$sum_ < 0} { set sum_ 0 set start $i } } assert {$maxsum_ == [maxsum $sequence]} assert {$maxsum_ == [sum [lrange $sequence [expr {$start + 1}] $end]]} return [lrange $sequence [expr {$start + 1}] $end] }   proc maxsum {sequence} { set maxsofar 0 set maxendinghere 0 foreach x $sequence { set maxendinghere [expr {max($maxendinghere + $x, 0)}] set maxsofar [expr {max($maxsofar, $maxendinghere)}] } return $maxsofar }   proc assert {condition {message "Assertion failed!"}} { if { ! [uplevel 1 [list expr $condition]]} { return -code error $message } }   proc sum list { expr [join $list +] }     puts "sequence: $a" puts "maxsumseq1: [maxsumseq1 $a]" puts [time {maxsumseq1 $a} 1000] puts "maxsumseq2: [maxsumseq2 $a]" puts [time {maxsumseq2 $a} 1000]
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)
#MATLAB_.2F_Octave
MATLAB / Octave
function guess_a_number(low, high)   if nargin < 1 || ~isnumeric(low) || length(low) > 1 || isnan(low) low = 1; end; if nargin < 2 || ~isnumeric(high) || length(high) > 1 || isnan(high) high = low+9; elseif low > high [low, high] = deal(high, low); end   n = floor(rand(1)*(high-low+1))+low; gs = input(sprintf('Guess an integer between %i and %i (inclusive): ', low, high), 's'); while gs % No guess quits the game g = str2double(gs); if length(g) > 1 || isnan(g) || g < low || g > high gs = input('Invalid input, guess again: ', 's'); elseif g < n gs = input('Too low, guess again: ', 's'); elseif g > n gs = input('Too high, guess again: ', 's'); else disp('Good job, you win!') gs = ''; end end
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
#ML
ML
(* 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 ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers. Display an example of your output here. *)   local fun get_digits (d, s) where (d = 0) = s | (d, s) = get_digits( d div 10, (d mod 10) :: s) | n = get_digits( n div 10, [n mod 10] ) ; fun mem (x, []) = false | (x, a :: as) where (x = a) = true | (x, _ :: as) = mem (x, as) in fun happy 1 = "happy" | n = let val this = (fold (+,0) ` map (fn n = n ^ 2) ` get_digits n); val sads = [2, 4, 16, 37, 58, 89, 145, 42, 20] in if (mem (n,sads)) then "unhappy" else happy this end end ;   foreach (fn n = (print n; print " is "; println ` happy n)) ` iota 10;  
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
#Jacquard_Loom
Jacquard Loom
+---------------+ | | | * * | |* * * * | |* * *| |* * *| |* * * | | * * * | | * | +---------------+   +---------------+ | | |* * * | |* * * | | * *| | * *| |* * * | |* * * * | | * | +---------------+   +---------------+ | | |* ** * * | |******* *** * | | **** * * ***| | **** * ******| | ****** ** * | | * * * * | | * | +---------------+   +---------------+ | | |******* *** * | |******* *** * | | ** *| |* * * *| |******* ** * | |******* *** * | | * | +---------------+   +---------------+ | | |******* *** * | |******* *** * | | * * * *| | * * * *| |******* ** * | |******* ** * | | * | +---------------+   +---------------+ | | |***** * *** * | |******* *** * | | * * * * | | * * * | |****** ** * | |****** ** * | | * | +---------------+   +---------------+ | | | * * * | |***** * ***** | |***** ** * ***| |***** ** * ***| |******* * ** | | * * * * | | * | +---------------+   +---------------+ | | | | | * * | | * * | | * | | * | | | | | +---------------+
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
#SenseTalk
SenseTalk
Answer "Good Bye"
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
#Sidef
Sidef
var tk = require('Tk'); var main = %s'MainWindow'.new; main.Button( '-text' => 'Goodbye, World!', '-command' => 'exit', ).pack; tk.MainLoop;
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] Reference Converting Between Gray and Binary Codes. It includes step-by-step animations.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bin32.s7i";   const func integer: grayEncode (in integer: n) is return ord(bin32(n) >< bin32(n >> 1));   const func integer: grayDecode (in var integer: n) is func result var integer: decoded is 0; begin decoded := n; while n > 1 do n >>:= 1; decoded := ord(bin32(decoded) >< bin32(n)); end while; end func;   const proc: main is func local var integer: i is 0; begin for i range 0 to 32 do writeln(i <& " => " <& grayEncode(i) radix 2 lpad0 6 <& " => " <& grayDecode(grayEncode(i))); end for; end func;
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] Reference Converting Between Gray and Binary Codes. It includes step-by-step animations.
#SenseTalk
SenseTalk
  function BinaryToGray param1 set theResult to "" repeat for each character in param1 if the counter is equal to 1 put it after theResult else if it is equal to previousCharacter put "0" after theResult else put "1" after theResult end if end if set previousCharacter to it end repeat return theResult end BinaryToGray   function GrayToBinary param1 set theResult to param1 repeat for each character in param1 if the counter is equal to 1 next repeat end if set currentChar to it set lastCharInd to the counter - 1 repeat for lastCharInd down to 1 if currentChar is equal to character it of param1 set currentChar to "0" else set currentChar to "1" end if end repeat set character the counter of theResult to currentChar end repeat   return theResult end GrayToBinary  
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!
#DCL
DCL
$ a1 = 123 $ a2 = "hello" $ show symbol a* $ gosub swap $ show symbol a* $ exit $ $ swap: $ t = a1 $ a1 = a2 $ a2 = t $ return
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.
#EasyLang
EasyLang
a[] = [ 2 9 4 3 8 5 ] for e in a[] max = higher e max . print max
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.
#EchoLisp
EchoLisp
  ;; a random length list of random values (define L (map random (make-list (random 50) 100))) → L L → (24 60 83 8 24 60 31 97 96 65 9 41 64 24 22 57 73 17 6 28 77 58 18 13 27 22 41 69 85)   ;; find max (apply max L) → 97  
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.
#Dc
Dc
[dSa%Lard0<G]dsGx+
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).
#Elena
Elena
import system'collections; import extensions;   const int maxNumber = 100000;   Hailstone(int n,Map<int,int> lengths) { if (n == 1) { ^ 1 };   while (true) { if (lengths.containsKey(n)) { ^ lengths[n] } else { if (n.isEven()) { lengths[n] := 1 + Hailstone(n/2, lengths) } else { lengths[n] := 1 + Hailstone(3*n + 1, lengths) } } } }   public program() { int longestChain := 0; int longestNumber := 0; auto recursiveLengths := new Map<int,int>(4096,4096);   for(int i := 1, i < maxNumber, i+=1) { var chainLength := Hailstone(i, recursiveLengths); if (longestChain < chainLength) { longestChain := chainLength; longestNumber := i } };   console.printFormatted("max below {0}: {1} ({2} steps)", maxNumber, longestNumber, longestChain) }
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).
#PicoLisp
PicoLisp
(de hamming (N) (let (L (1) H) (do N (for (X L X (cadr X)) # Find smallest result (setq H (car X)) ) (idx 'L H NIL) # Remove it (for I (2 3 5) # Generate next results (idx 'L (* I H) T) ) ) H ) )   (println (make (for N 20 (link (hamming N))))) (println (hamming 1691)) # very fast (println (hamming 1000000)) # runtime about 13 minutes on i5-3570S
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
#Ruby
Ruby
  n = rand(1..10) puts 'Guess the number: ' puts 'Wrong! Guess again: ' until gets.to_i == n puts 'Well guessed!'  
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
#Run_BASIC
Run BASIC
while 1 choose = int(RND(0) * 9) + 1 while guess <> choose print "Guess a number between 1 and 10: ";: input guess if guess = choose THEN print "You guessed!" else print "Sorry, try again" end if wend wend
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#Ursala
Ursala
#import std #import int   max_subsequence = zleq$^l&r/&+ *aayK33PfatPRTaq ^/~& sum:-0   #cast %zL   example = max_subsequence <-1,-2,3,5,6,-2,-1,4,-4,2,-1>
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#XPL0
XPL0
include c:\cxpl\codes; int Array, Size, Sum, Best, I, Lo, Hi, BLo, BHi;   [Array:= [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]; Size:= 11; Best:= -100000; for Lo:= 0 to Size-1 do for Hi:= Lo to Size-1 do [Sum:= 0; for I:= Lo to Hi do Sum:= Sum + Array(I); if Sum > Best then [Best:= Sum; BLo:= Lo; BHi:= Hi]; ]; Text(0, "Sequence = "); for I:= 0 to Size-1 do [IntOut(0, Array(I)); Text(0, " ")]; CrLf(0); Text(0, "Greatest = "); for I:= BLo to BHi do [IntOut(0, Array(I)); Text(0, " ")]; CrLf(0); Text(0, "Sum = "); IntOut(0, Best); CrLf(0); ]
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)
#MAXScript
MAXScript
  Range = [1,100] randomNumber = (random Range.x Range.y) as integer clearListener() while true do ( userVal = getKBValue prompt:("Enter a number between "+(range[1] as integer) as string+" and "+(range[2] as integer) as string+": ") if userVal == randomNumber do (format "\nWell guessed!\n"; exit with OK) case of ( (classOf userVal != classof randomNumber): (format "\nBad number!\n") (userVal > Range[2] or userVal < Range[1]): (format "\nNumber out of range\n") (userVal > randomNumber): (format "\nToo high!\n") (userVal < randomNumber): (format "\nToo low!\n") ) )  
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)
#Mirah
Mirah
def getInput:int s = System.console.readLine() Integer.parseInt(s) end   number = int(Math.random() * 10 + 1)   puts "Guess the number between 1 and 10"   guessed = false   while !guessed do begin userNumber = getInput if userNumber == number guessed = true puts "You guessed it." elsif userNumber > number puts "Too high." else puts "Too low." end rescue NumberFormatException => e puts "Please enter an integer." end end
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
#Modula-2
Modula-2
MODULE HappyNumbers; FROM InOut IMPORT WriteCard, WriteLn;   CONST Amount = 8; VAR seen, num: CARDINAL;   PROCEDURE SumDigitSquares(n: CARDINAL): CARDINAL; VAR sum, digit: CARDINAL; BEGIN sum := 0; WHILE n>0 DO digit := n MOD 10; n := n DIV 10; sum := sum + digit * digit; END; RETURN sum; END SumDigitSquares;   PROCEDURE Happy(n: CARDINAL): BOOLEAN; VAR i: CARDINAL; seen: ARRAY [0..255] OF BOOLEAN; BEGIN FOR i := 0 TO 255 DO seen[i] := FALSE; END; REPEAT seen[n] := TRUE; n := SumDigitSquares(n); UNTIL seen[n]; RETURN seen[1]; END Happy;   BEGIN seen := 0; num := 0; WHILE seen < Amount DO IF Happy(num) THEN INC(seen); WriteCard(num,2); WriteLn(); END; INC(num); END; END HappyNumbers.
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
#Java
Java
public class HelloWorld { public static void main(String[] args) { System.out.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
#Smalltalk
Smalltalk
MessageBox show: '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
#SmileBASIC
SmileBASIC
DIALOG "Goodbye, world."
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] Reference Converting Between Gray and Binary Codes. It includes step-by-step animations.
#Sidef
Sidef
func bin2gray(n) { n ^ (n >> 1) }   func gray2bin(num) { var bin = num while (num >>= 1) { bin ^= num } return bin }   { |i| var gr = bin2gray(i) printf("%d\t%b\t%b\t%b\n", i, i, gr, gray2bin(gr)) } << ^32
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] Reference Converting Between Gray and Binary Codes. It includes step-by-step animations.
#SQL
SQL
  DECLARE @BINARY AS NVARCHAR(MAX) = '001010111' DECLARE @gray AS NVARCHAR(MAX) = ''   --Encoder SET @gray = LEFT(@BINARY, 1)   WHILE LEN(@BINARY) > 1 BEGIN IF LEFT(@BINARY, 1) != SUBSTRING(@BINARY, 2, 1) SET @gray = @gray + '1' ELSE SET @gray = @gray + '0'   SET @BINARY = RIGHT(@BINARY, LEN(@BINARY) - 1) END   SELECT @gray   --Decoder SET @BINARY = LEFT(@gray, 1)   WHILE LEN(@gray) > 1 BEGIN IF RIGHT(@BINARY, 1) != SUBSTRING(@gray, 2, 1) SET @BINARY = @BINARY + '1' ELSE SET @BINARY = @BINARY + '0'   SET @gray = RIGHT(@gray, LEN(@gray) - 1) END   SELECT @BINARY  
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!
#Delphi
Delphi
  procedure Swap_T(var a, b: T); var temp: T; begin temp := a; a := b; b := temp; 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.
#ECL
ECL
  MaxVal(SET OF INTEGER s) := MAX(s);   //example usage   SetVals := [4,8,16,2,1]; MaxVal(SetVals) //returns 16;  
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.
#Efene
Efene
list_max = fn ([Head:Rest]) { list_max(Rest, Head) }   list_max = fn ([], Res) { Res } fn ([Head:Rest], Max) when Head > Max { list_max(Rest, Head) } fn ([_Head:Rest], Max) { list_max(Rest, Max) }   list_max1 = fn ([H:T]) { lists.foldl(fn erlang.max:2, H, T) }   @public run = fn () { io.format("~p~n", [list_max([9, 4, 3, 8, 5])]) io.format("~p~n", [list_max1([9, 4, 3, 8, 5])]) }  
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.
#Delphi
Delphi
proc nonrec gcd(word m, n) word: word t; while n ~= 0 do t := m; m := n; n := t % n od; m corp   proc nonrec show(word m, n) void: writeln("gcd(", m, ", ", n, ") = ", gcd(m, n)) corp   proc nonrec main() void: show(18, 12); show(1071, 1029); show(3528, 3780) corp
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).
#Elixir
Elixir
defmodule Hailstone do require Integer   def step(1) , do: 0 def step(n) when Integer.is_even(n), do: div(n,2) def step(n) , do: n*3 + 1   def sequence(n) do Stream.iterate(n, &step/1) |> Stream.take_while(&(&1 > 0)) |> Enum.to_list end   def run do seq27 = sequence(27) len27 = length(seq27) repr = String.replace(inspect(seq27, limit: 4) <> inspect(Enum.drop(seq27,len27-4)), "][", ", ") IO.puts "Hailstone(27) has #{len27} elements: #{repr}"   {len, start} = Enum.map(1..100_000, fn(n) -> {length(sequence(n)), n} end) |> Enum.max IO.puts "Longest sequence starting under 100000 begins with #{start} and has #{len} elements." end end   Hailstone.run
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).
#PL.2FI
PL/I
(subscriptrange): Hamming: procedure options (main); /* 14 November 2013 with fixes 2021 */ declare (H(2000), p2, p3, p5, twoTo31, Hm, tenP(11)) decimal(12)fixed; declare (i, j, k, m, d, w) fixed binary;   /* Quicksorts in-place the array of integers H, from lb to ub */ quicksortH: procedure( lb, ub ) recursive; declare ( lb, ub )binary(15)fixed; declare ( left, right )binary(15)fixed; declare ( pivot, swap )decimal(12)fixed; declare sorting bit(1); if ub > lb then do /* more than one element, so must sort */ left = lb; right = ub; /* choosing the middle element of the array as the pivot */ pivot = H( left + ( ( right + 1 ) - left ) / 2 ); sorting = '1'b; do while( sorting ); do while( left <= ub & H( left ) < pivot ); left = left + 1; end; do while( right >= lb & H( right ) > pivot ); right = right - 1; end; sorting = ( left <= right ); if sorting then do; swap = H( left ); H( left ) = H( right ); H( right ) = swap; left = left + 1; right = right - 1; end; end; call quicksortH( lb, right ); call quicksortH( left, ub ); end; end quicksortH ;   /* find 2^31 - the limit for Hamming numbers we need to find */ twoTo31 = 2; do i = 2 to 31; twoTo31 = twoTo31 * 2; end; /* calculate powers of 10 so we can check the number of digits */ /* the numbers will have */ tenP( 1 ) = 10; do i = 2 to 11; tenP( i ) = 10 * tenP( i - 1 ); end;   /* find the numbers */ m = 0; p5 = 1; do k = 0 to 13; p3 = 1; do j = 0 to 19; Hm = 0; p2 = 1; do i = 0 to 31 while( Hm < twoTo31 ); /* count the number of digits p2 * p3 * p5 will have */ d = 0; do w = 1 to 11 while( tenP(w) < p2 ); d = d + 1; end; do w = 1 to 11 while( tenP(w) < p3 ); d = d + 1; end; do w = 1 to 11 while( tenP(w) < p5 ); d = d + 1; end; if d < 11 then do; /* the product will be small enough */ Hm = p2 * p3 * p5; if Hm < twoTo31 then do; m = m + 1; H(m) = Hm; end; end; p2 = p2 * 2; end; p3 = p3 * 3; end; p5 = p5 * 5; end;   /* sort the numbers */ call quicksortH( 1, m );   put skip list( 'The first 20 Hamming numbers:' ); do i = 1 to 20; put skip list (H(i)); end; put skip list( 'Hamming number 1691:' ); put skip list (H(1691));   end 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
#Rust
Rust
extern crate rand;   fn main() { println!("Type in an integer between 1 and 10 and press enter.");   let n = rand::random::<u32>() % 10 + 1; loop { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); let option: Result<u32,_> = line.trim().parse(); match option { Ok(guess) => { if guess < 1 || guess > 10 { println!("Guess is out of bounds; try again."); } else if guess == n { println!("Well guessed!"); break; } else { println!("Wrong! Try again."); } }, Err(_) => println!("Invalid input; try again.") } } }
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
#Scala
Scala
  val n = (math.random * 10 + 1).toInt print("Guess the number: ") while(readInt != n) print("Wrong! Guess again: ") println("Well guessed!")  
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#Wren
Wren
var gss = Fn.new { |s| var best = 0 var start = 0 var end = 0 var sum = 0 var sumStart = 0 var i = 0 for (x in s) { sum = sum + x if (sum > best) { best = sum start = sumStart end = i + 1 } else if (sum < 0) { sum = 0 sumStart = i + 1 } i = i + 1 } return [s[start...end], best] }   var tests = [ [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1], [-1, 1, 2, -5, -6], [], [-1, -2, -1] ] for (test in tests) { System.print("Input:  %(test)") var res = gss.call(test) var subSeq = res[0] var sum = res[1] System.print("Sub seq: %(subSeq)") System.print("Sum:  %(sum)\n") }
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)
#Modula-2
Modula-2
MODULE guessf;   IMPORT InOut, Random, NumConv, Strings;   VAR number, guess : CARDINAL; input : Strings.String; OK, Done : BOOLEAN;   BEGIN number := Random.nr (1000); InOut.WriteString ("I have chosen a number below 1000; please try to guess it."); InOut.WriteLn; REPEAT REPEAT InOut.WriteString ("Enter your guess : "); InOut.WriteBf; InOut.ReadString (input); NumConv.Str2Num (guess, 10, input, OK); IF NOT OK THEN InOut.WriteString (input); InOut.WriteString (" is not a valid number..."); InOut.WriteLn END UNTIL OK; InOut.WriteString ("Your guess is "); IF number = guess THEN Done := TRUE; InOut.WriteString ("spot on!") ELSE Done := FALSE; IF guess > number THEN InOut.WriteString ("too high.") ELSE InOut.WriteString ("too low.") END END; InOut.WriteLn UNTIL Done; InOut.WriteString ("Thank you for playing; have a nice day!"); InOut.WriteLn END guessf.
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
#MUMPS
MUMPS
ISHAPPY(N)  ;Determines if a number N is a happy number  ;Note that the returned strings do not have a leading digit unless it is a happy number IF (N'=N\1)!(N<0) QUIT "Not a positive integer" NEW SUM,I  ;SUM is the sum of the square of each digit  ;I is a loop variable  ;SEQ is the sequence of previously checked SUMs from the original N  ;If it isn't set already, initialize it to an empty string IF $DATA(SEQ)=0 NEW SEQ SET SEQ="" SET SUM=0 FOR I=1:1:$LENGTH(N) DO .SET SUM=SUM+($EXTRACT(N,I)*$EXTRACT(N,I)) QUIT:(SUM=1) SUM QUIT:$FIND(SEQ,SUM)>1 "Part of a sequence not containing 1" SET SEQ=SEQ_","_SUM QUIT $$ISHAPPY(SUM) HAPPY(C) ;Finds the first C happy numbers NEW I  ;I is a counter for what integer we're looking at WRITE !,"The first "_C_" happy numbers are:" FOR I=1:1 QUIT:C<1 SET Q=+$$ISHAPPY(I) WRITE:Q !,I SET:Q C=C-1 KILL I QUIT
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
#JavaScript
JavaScript
document.write("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
#SSEM
SSEM
01100000000001110000000000000000 10000000000001010000000000000000 10011101110111011101010111000000 10010101010101010101010101000000 10010101010101010101010111000000 10011101110111011100110100000010 10000000000000000000010011000010 10011000000000000000100000000100 01101000000000000001000000000000 00000000000000000000000000000000 00000000000000000000000000000000 00100100100000000010000100100000 00100100100000000010000100100000 00100100101110111010011100100000 00100100101010100010010100100000 00100100101010100010010100000000 00100100101110100011011100100000 00011011000000000000000000000000
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
#Standard_ML
Standard ML
open XWindows ; open Motif ;   val helloWindow = fn () =>   let val shell = XtAppInitialise "" "demo" "top" [] [XmNwidth 400, XmNheight 300 ] ; val main = XmCreateMainWindow shell "main" [XmNmappedWhenManaged true ] ; val text = XmCreateLabel main "show" [ XmNlabelString "Hello World!"] in   ( XtManageChildren [text]; XtManageChild main; XtRealizeWidget shell )   end;  
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] Reference Converting Between Gray and Binary Codes. It includes step-by-step animations.
#Standard_ML
Standard ML
fun gray_encode b = Word.xorb (b, Word.>> (b, 0w1))   fun gray_decode n = let fun aux (p, n) = if n = 0w0 then p else aux (Word.xorb (p, n), Word.>> (n, 0w1)) in aux (n, Word.>> (n, 0w1)) end;   val s = Word.fmt StringCvt.BIN; fun aux i = if i = 0w32 then () else let val g = gray_encode i val b = gray_decode g in print (Word.toString i ^ " :\t" ^ s i ^ " => " ^ s g ^ " => " ^ s b ^ "\t: " ^ Word.toString b ^ "\n"); aux (i + 0w1) end; aux 0w0
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] Reference Converting Between Gray and Binary Codes. It includes step-by-step animations.
#Swift
Swift
func grayEncode(_ i: Int) -> Int { return (i >> 1) ^ i }   func grayDecode(_ i: Int) -> Int { switch i { case 0: return 0 case _: return i ^ grayDecode(i >> 1) } }   for i in 0..<32 { let iStr = String(i, radix: 2) let encode = grayEncode(i) let encodeStr = String(encode, radix: 2) let decode = grayDecode(encode) let decodeStr = String(decode, radix: 2)   print("\(i) (\(iStr)) => \(encode) (\(encodeStr)) => \(decode) (\(decodeStr))") }
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!
#D.C3.A9j.C3.A0_Vu
Déjà Vu
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.
#Eiffel
Eiffel
  class GREATEST_ELEMENT [G -> COMPARABLE]   create make   feature {NONE} --Implementation   is_max (element: G maximum: G): BOOLEAN do Result := maximum >= element end   max (list: ARRAY [G]): G require not_empty: not list.is_empty do Result := list [list.lower] across list as i loop Result := i.item.max (Result) end ensure is_part_of_array: list.has (Result) is_maximum: list.for_all (agent is_max(?, Result)) end   feature -- Initialization   make do end   greatest_element (a: ARRAY [G]): G do Result := max (a) end   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.
#Draco
Draco
proc nonrec gcd(word m, n) word: word t; while n ~= 0 do t := m; m := n; n := t % n od; m corp   proc nonrec show(word m, n) void: writeln("gcd(", m, ", ", n, ") = ", gcd(m, n)) corp   proc nonrec main() void: show(18, 12); show(1071, 1029); show(3528, 3780) corp
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).
#Erlang
Erlang
-module(hailstone). -import(io). -export([main/0]).   hailstone(1) -> [1]; hailstone(N) when N band 1 == 1 -> [N|hailstone(N * 3 + 1)]; hailstone(N) when N band 1 == 0 -> [N|hailstone(N div 2)].   max_length(Start, Stop) -> F = fun (N) -> {length(hailstone(N)), N} end, Lengths = lists:map(F, lists:seq(Start, Stop)), lists:max(Lengths).   main() -> io:format("hailstone(4): ~w~n", [hailstone(4)]), Seq27 = hailstone(27), io:format("hailstone(27) length: ~B~n", [length(Seq27)]), io:format("hailstone(27) first 4: ~w~n", [lists:sublist(Seq27, 4)]), io:format("hailstone(27) last 4: ~w~n", [lists:nthtail(length(Seq27) - 4, Seq27)]), io:format("finding maximum hailstone(N) length for 1 <= N <= 100000..."), {Length, N} = max_length(1, 100000), io:format(" done.~nhailstone(~B) length: ~B~n", [N, Length]).
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).
#Prolog
Prolog
%% collect N elements produced by a generator in a row   take( 0, Next, Z-Z, Next). take( N, Next, [A|B]-Z, NZ):- N>0, !, next(Next,A,Next1), N1 is N-1, take(N1,Next1,B-Z,NZ).   %% a generator provides specific {next} implementation   next( hamm( A2,B,C3,D,E5,F,[H|G] ), H, hamm(X,U,Y,V,Z,W,G) ):- H is min(A2, min(C3,E5)), ( A2 =:= H -> B=[N2|U],X is N2*2 ; (X,U)=(A2,B) ), ( C3 =:= H -> D=[N3|V],Y is N3*3 ; (Y,V)=(C3,D) ), ( E5 =:= H -> F=[N5|W],Z is N5*5 ; (Z,W)=(E5,F) ).   mkHamm( hamm(1,X,1,X,1,X,X) ). % Hamming numbers generator init state   main(N) :- mkHamm(G),take(20,G,A-[],_), write(A), nl, take(1691-1,G,_,G2),take(2,G2,B-[],_), write(B), nl, take( N -1,G,_,G3),take(2,G3,[C1|_]-_,_), write(C1), nl.
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
#Scheme
Scheme
(define (guess) (define number (random 11)) (display "Pick a number from 1 through 10.\n> ") (do ((guess (read) (read))) ((= guess number) (display "Well guessed!\n")) (display "Guess again.\n")))
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
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var integer: number is 0; var integer: guess is 0; begin number := rand(1, 10); writeln("I'm thinking of a number between 1 and 10."); writeln("Try to guess it!"); readln(guess); while guess <> number do writeln("That's not my number."); writeln("Try another guess!"); readln(guess); end while; writeln("You have won!"); end func;
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#zkl
zkl
fcn maxsubseq(s){ s.reduce(fcn([(sum, seq, maxsum, maxseq)], x){ sum=sum+x; seq=T(x).extend(seq); if(sum < 0) return(0,T,maxsum,maxseq); if (sum>maxsum) return(sum, seq, sum, seq); return(sum, seq, maxsum, maxseq); }, T(0,T,0,T))[3].reverse(); // -->maxseq.reverse() }
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 DATA 12,0,1,2,-3,3,-1,0,-4,0,-1,-4,2 20 DATA 11,-1,-2,3,5,6,-2,-1,4,-4,2,-1 30 DATA 5,-1,-2,-3,-4,-5 40 FOR n=1 TO 3 50 READ l 60 DIM a(l) 70 FOR i=1 TO l 80 READ a(i) 90 PRINT a(i); 100 IF i<l THEN PRINT ", "; 110 NEXT i 120 PRINT 130 LET a=1: LET m=0: LET b=0 140 FOR i=1 TO l 150 LET s=0 160 FOR j=i TO l 170 LET s=s+a(j) 180 IF s>m THEN LET m=s: LET a=i: LET b=j 190 NEXT j 200 NEXT i 210 IF a>b THEN PRINT "[]": GO TO 280 220 PRINT "["; 230 FOR i=a TO b 240 PRINT a(i); 250 IF i<b THEN PRINT ", "; 260 NEXT i 270 PRINT "]" 280 NEXT n
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)
#Nanoquery
Nanoquery
import Nanoquery.Util   random = new(Random) inclusive_range = {1, 100}   print format("Guess my target number that is between %d and %d (inclusive).\n",\ inclusive_range[0], inclusive_range[1]) target = random.getInt(inclusive_range[1]) + inclusive_range[0] answer = 0 i = 0 while answer != target i += 1 print format("Your guess(%d): ", i) txt = input()   valid = true try answer = int(txt) catch println format(" I don't understand you input of '%s' ?", txt) value = false end   if valid if (answer < inclusive_range[0]) or (answer > inclusive_range[1]) println " Out of range!" else if answer = target println " Ye-Haw!!" else if answer < target println " Too low." else if answer > target println " Too high." end end end   println "\nThanks for playing."
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
#NetRexx
NetRexx
/*NetRexx program to display the 1st 8 (or specified arg) happy numbers*/ limit = arg[0] /*get argument for LIMIT. */ say limit if limit = null, limit ='' then limit=8 /*if not specified, set LIMIT to 8*/ haps = 0 /*count of happy numbers so far. */   loop n=1 while haps < limit /*search integers starting at one.*/ q=n /*Q may or may not be "happy". */ a=0   loop forever /*see if Q is a happy number. */ if q==1 then do /*if Q is unity, then it's happy*/ haps = haps + 1 /*bump the count of happy numbers.*/ say n /*display the number. */ iterate n /*and then keep looking for more. */ end   sum=0 /*initialize sum to zero. */   loop j=1 for q.length /*add the squares of the numerals.*/ sum = sum + q.substr(j,1) ** 2 end   if a[sum] then iterate n /*if already summed, Q is unhappy.*/ a[sum]=1 /*mark the sum as being found. */ q=sum /*now, lets try the Q sum. */ end 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
#JCL
JCL
/*MESSAGE 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
#Stata
Stata
window stopbox note "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
#Supernova
Supernova
I want window and the window title is "Goodbye, World".
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] Reference Converting Between Gray and Binary Codes. It includes step-by-step animations.
#Tcl
Tcl
namespace eval gray { proc encode n { expr {$n ^ $n >> 1} } proc decode n { # Compute some bit at least as large as MSB set i [expr {2**int(ceil(log($n+1)/log(2)))}] set b [set bprev [expr {$n & $i}]] while {[set i [expr {$i >> 1}]]} { set b [expr {$b | [set bprev [expr {$n & $i ^ $bprev >> 1}]]}] } return $b } }
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] Reference Converting Between Gray and Binary Codes. It includes step-by-step animations.
#TypeScript
TypeScript
// Gray code   function encode(v: number): number { return v ^ (v >> 1); }   function decode(v: number): number { var result = 0; while (v > 0) { result ^= v; v >>= 1; } return result; }   console.log("decimal binary gray decoded"); for (var i = 0; i <= 31; i++) { var g = encode(i); var d = decode(g); process.stdout.write( " " + i.toString().padStart(2, " ") + " " + i.toString(2).padStart(5, "0") + " " + g.toString(2).padStart(5, "0") + " " + d.toString(2).padStart(5, "0") + " " + d.toString().padStart(2, " ")); console.log(); }  
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!
#E
E
def swap(&left, &right) { def t := left left := right right := t }
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.
#Ela
Ela
open list   findBy p (x::xs) = foldl (\x y | p x y -> x | else -> y) x xs maximum = findBy (>)   maximum [1..10]
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.
#DWScript
DWScript
PrintLn(Gcd(231, 210));
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).
#ERRE
ERRE
  PROGRAM ULAM   !$DOUBLE   PROCEDURE HAILSTONE(X,PRT%->COUNT) COUNT=1 IF PRT% THEN PRINT(X,) END IF REPEAT IF X/2<>INT(X/2) THEN X=X*3+1 ELSE X=X/2 END IF IF PRT% THEN PRINT(X,) END IF COUNT=COUNT+1 UNTIL X=1 IF PRT% THEN PRINT END IF END PROCEDURE   BEGIN HAILSTONE(27,TRUE->COUNT) PRINT("Sequence length for 27:";COUNT) MAX_COUNT=2 NMAX=2 FOR I=3 TO 100000 DO HAILSTONE(I,FALSE->COUNT) IF COUNT>MAX_COUNT THEN NMAX=I MAX_COUNT=COUNT END IF END FOR PRINT("Max. number is";NMAX;" with";MAX_COUNT;"elements") 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).
#PureBasic
PureBasic
#X2 = 2 #X3 = 3 #X5 = 5   Macro Ham(w) PrintN("H("+Str(w)+") = "+Str(Hamming(w))) EndMacro   Procedure.i Hamming(l.i) Define.i i,j,k,n,m,x=#X2,y=#X3,z=#X5 Dim h.i(l) : h(0)=1 For n=1 To l-1 m=x If m>y : m=y : EndIf If m>z : m=z : EndIf h(n)=m If m=x : i+1 : x=#X2*h(i) : EndIf If m=y : j+1 : y=#X3*h(j) : EndIf If m=z : k+1 : z=#X5*h(k) : EndIf Next ProcedureReturn h(l-1) EndProcedure   OpenConsole("Hamming numbers") For h.i=1 To 20 Ham(h) Next Ham(1691) Input()
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
#Self
Self
(| parent* = traits clonable. copy = (resend.copy secretNumber: random integerBetween: 1 And: 10). secretNumber.   ask = ((userQuery askString: 'Guess the Number: ') asInteger). reportSuccess = (userQuery report: 'You got it!'). reportFailure = (userQuery report: 'Nope. Guess again.'). sayIntroduction = (userQuery report: 'Try to guess my secret number between 1 and 10.').   hasGuessed = ( [ask = secretNumber] onReturn: [|:r| r ifTrue: [reportSuccess] False: [reportFailure]] ). run = (sayIntroduction. [hasGuessed] whileFalse) |) copy run
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)
#Nemerle
Nemerle
using System; using System.Console;   module GuessHints { Main() : void { def rand = Random(); def secret = rand.Next(1, 101); mutable guess = 0;   def GetGuess() : int {Int32.Parse(ReadLine())}   WriteLine("Guess a number between 1 and 100:");   do { guess = GetGuess(); match(guess.CompareTo(secret)) { |(-1) => WriteLine("Too low! Guess again:") |1 => WriteLine("Too high! Guess again:") |0 => WriteLine("Well guessed!") } } while (guess != secret) } }
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
#Nim
Nim
import intsets   proc happy(n: int): bool = var n = n past = initIntSet() while n != 1: let s = $n n = 0 for c in s: let i = ord(c) - ord('0') n += i * i if n in past: return false past.incl(n) return true   for x in 0..31: if happy(x): echo x
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
#Jinja
Jinja
  from jinja2 import Template print(Template("Hello World!").render())  
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
#Swift
Swift
import Cocoa   let alert = NSAlert() alert.messageText = "Goodbye, World!" alert.runModal()
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
#Tcl
Tcl
pack [label .l -text "Goodbye, World"]
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] Reference Converting Between Gray and Binary Codes. It includes step-by-step animations.
#Ursala
Ursala
#import std #import nat   xor = ~&Y&& not ~&B # either and not both   btog = xor*+ zipp0@iitBX # map xor over the argument zipped with its shift   gtob = ~&y+ =><0> ^C/xor@lrhPX ~&r # fold xor over the next input with previous output   #show+   test = mat` * 2-$'01'***K7xSS pad0*K7 <.~&,btog,gtob+ btog>* iota32
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] Reference Converting Between Gray and Binary Codes. It includes step-by-step animations.
#VBScript
VBScript
Function Encoder(ByVal n) Encoder = n Xor (n \ 2) End Function   Function Decoder(ByVal n) Dim g : g = 0 Do While n > 0 g = g Xor n n = n \ 2 Loop Decoder = g End Function   ' Decimal to Binary Function Dec2bin(ByVal n, ByVal length) Dim i, strbin : strbin = "" For i = 1 to 5 strbin = (n Mod 2) & strbin n = n \ 2 Next Dec2Bin = strbin End Function   WScript.StdOut.WriteLine("Binary -> Gray Code -> Binary") For i = 0 to 31 encoded = Encoder(i) decoded = Decoder(encoded) WScript.StdOut.WriteLine(Dec2Bin(i, 5) & " -> " & Dec2Bin(encoded, 5) & " -> " & Dec2Bin(decoded, 5)) Next
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!
#EchoLisp
EchoLisp
  ;; 1) ;; a macro will do it, as shown in Racket (same syntax) (define-syntax-rule (swap a b) (let ([tmp a]) (set! a b) (set! b tmp)))   (define A 666) (define B "simon") (swap A B) A → "simon" B → 666   ;; 2) ;; The list-swap! function allows to swap two items inside a list, regardless of their types ;; This physically alters the list   (define L ' ( 1 2 3 4 🎩 )) (list-swap! L 1 ' 🎩 ) → (🎩 2 3 4 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.
#Elena
Elena
import extensions;   extension op { get Maximal() { auto en := cast Enumerator(self.enumerator());   object maximal := nil; while (en.next()) { var item := en.get(); if (nil == maximal) { maximal := item } else if (maximal < item) { maximal := item } };   ^ maximal } }   public program() { console.printLine(new int[]{1,2,3,4,20,10,9,8}.Maximal) }
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.
#Dyalect
Dyalect
func gcd(a, b) { func bgcd(a, b, res) { if a == b { return res * a } else if a % 2 == 0 && b % 2 == 0 { return bgcd(a/2, b/2, 2*res) } else if a % 2 == 0 { return bgcd(a/2, b, res) } else if b % 2 == 0 { return bgcd(a, b/2, res) } else if a > b { return bgcd(a-b, b, res) } else { return bgcd(a, b-a, res) } } return bgcd(a, b, 1) }   var testdata = [ (a: 33, b: 77), (a: 49865, b: 69811) ]   for v in testdata { print("gcd(\(v.a), \(v.b)) = \(gcd(v.a, v.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).
#Euler_Math_Toolbox
Euler Math Toolbox
  >function hailstone (n) ... $ v=[n]; $ repeat $ if mod(n,2) then n=3*n+1; $ else n=n/2; $ endif; $ v=v|n; $ until n==1; $ end; $ return v; $ endfunction >hailstone(27), length(%) [ 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 ] 112 >function hailstonelength (n) ... $ v=zeros(1,n); $ v[1]=4; v[2]=2; $ loop 3 to n; $ count=1; $ n=#; $ repeat $ if mod(n,2) then n=3*n+1; $ else n=n/2; $ endif; $ if n<=cols(v) and v[n] then $ v[#]=v[n]+count; $ break; $ endif; $ count=count+1; $ end; $ end; $ return v; $ endfunction >h=hailstonelength(100000); >ex=extrema(h); ex[3], ex[4] 351 77031  
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).
#Python
Python
from itertools import islice   def hamming2(): '''\ This version is based on a snippet from: https://web.archive.org/web/20081219014725/http://dobbscodetalk.com:80 /index.php?option=com_content&task=view&id=913&Itemid=85 http://www.drdobbs.com/architecture-and-design/hamming-problem/228700538 Hamming problem Written by Will Ness December 07, 2008   When expressed in some imaginary pseudo-C with automatic unlimited storage allocation and BIGNUM arithmetics, it can be expressed as: hamming = h where array h; n=0; h[0]=1; i=0; j=0; k=0; x2=2*h[ i ]; x3=3*h[j]; x5=5*h[k]; repeat: h[++n] = min(x2,x3,x5); if (x2==h[n]) { x2=2*h[++i]; } if (x3==h[n]) { x3=3*h[++j]; } if (x5==h[n]) { x5=5*h[++k]; } ''' h = 1 _h=[h] # memoized multipliers = (2, 3, 5) multindeces = [0 for i in multipliers] # index into _h for multipliers multvalues = [x * _h[i] for x,i in zip(multipliers, multindeces)] yield h while True: h = min(multvalues) _h.append(h) for (n,(v,x,i)) in enumerate(zip(multvalues, multipliers, multindeces)): if v == h: i += 1 multindeces[n] = i multvalues[n] = x * _h[i] # cap the memoization mini = min(multindeces) if mini >= 1000: del _h[:mini] multindeces = [i - mini for i in multindeces] # yield h
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
#Sidef
Sidef
var n = irand(1, 10) var msg = 'Guess the number: ' while (n != read(msg, Number)) { msg = 'Wrong! Guess again: ' } say 'Well guessed!'
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
#Small_Basic
Small Basic
number=Math.GetRandomNumber(10) TextWindow.WriteLine("I just thought of a number between 1 and 10. What is it?") While guess<>number guess=TextWindow.ReadNumber() TextWindow.WriteLine("Guess again! ") EndWhile TextWindow.WriteLine("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)
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   parse arg lo hi . if lo = '' | lo = '.' then lo = 1 if hi = '' | hi = '.' then hi = 100 if lo > hi then parse (hi lo) lo hi -- make sure lo is < hi rg = Random() tries = 0 guessThis = rg.nextInt(hi - lo) + lo   say say 'Rules: Guess a number between' lo 'and' hi say ' Use QUIT or . to stop the game' say ' Use TELL to get the game to tell you the answer.' say say 'Starting...' say   loop label g_ forever say 'Try guessing a number between' lo 'and' hi parse ask guess . select when guess.upper = 'QUIT' | guess = '.' then do say 'You asked to leave the game. Goodbye...' leave g_ end when guess.upper = 'TELL' | guess = '.' then do say 'The number you were looking for is' guessThis end when \guess.datatype('w') then do say guess 'is not a whole number. Try again.' end when guess = guessThis then do tries = tries + 1 say 'Well guessed!' guess 'is the correct number.' say 'It took you' tries 'tries.' leave g_ end when guess < lo then do tries = tries + 1 say guess 'is below the lower limit of' lo end when guess > hi then do tries = tries + 1 say guess 'is above the upper limit of' hi end when guess < guessThis then do tries = tries + 1 say guess 'is too low. Try again.' end when guess > guessThis then do tries = tries + 1 say guess 'is too high. Try again.' end otherwise do say guess 'is an unexpected value.' end end end g_   return  
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
#Objeck
Objeck
use IO; use Structure;   bundle Default { class HappyNumbers { function : native : IsHappy(n : Int) ~ Bool { cache := IntVector->New(); sum := 0; while(n <> 1) { if(cache->Has(n)) { return false; };   cache->AddBack(n); while(n <> 0) { digit := n % 10; sum += (digit * digit); n /= 10; };   n := sum; sum := 0; };   return true; }   function : Main(args : String[]) ~ Nil { num := 1; happynums := IntVector->New();   while(happynums->Size() < 8) { if(IsHappy(num)) { happynums->AddBack(num); };   num += 1; };   Console->Print("First 8 happy numbers: "); each(i : happynums) { Console->Print(happynums->Get(i))->Print(","); }; Console->PrintLine(""); } } }
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
#Joy
Joy
"Hello world!" putchars.
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
#TI-83_BASIC
TI-83 BASIC
PROGRAM:GUIHELLO :Text(0,0,"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
#TI-89_BASIC
TI-89 BASIC
Dialog Text "Goodbye, World!" EndDlog
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] Reference Converting Between Gray and Binary Codes. It includes step-by-step animations.
#Verilog
Verilog
  `timescale 1ns/10ps `default_nettype wire   module graytestbench;   localparam aw = 8;   function [aw:0] binn_to_gray; input [aw:0] binn; begin :b2g binn_to_gray = binn ^ (binn >> 1); end endfunction   function [aw:0] gray_to_binn; input [aw:0] gray; begin :g2b reg [aw:0] binn; integer i;   for(i=0; i <= aw; i = i+1) begin binn[i] = ^(gray >> i); end gray_to_binn = binn; end endfunction   initial begin :test_graycode integer ii; reg[aw:0] gray; reg[aw:0] binn;   for(ii=0; ii < 10; ii=ii+1) begin gray = binn_to_gray(ii[aw:0]); binn = gray_to_binn(gray);   $display("test_graycode: i:%x gray:%x:%b binn:%x", ii[aw:0], gray, gray, binn); end   $stop; end   endmodule   `default_nettype none    
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!
#Elena
Elena
import extensions;   swap(ref object v1, ref object v2) { var tmp := v1;   v1 := v2; v2 := tmp }   public program() { var n := 2; var s := "abc";   console.printLine(n," ",s);   swap(ref n, ref s);   console.printLine(n," ",s) }
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.
#Elixir
Elixir
iex(1)> Enum.max([3,1,4,1,5,9,2,6,5,3]) 9
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.
#Emacs_Lisp
Emacs Lisp
(defun find-maximum (items) (let (max) (dolist (item items) (when (or (not max) (> item max)) (setq max item))) max))   (find-maximum '(2 7 5)) ;=> 7
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.
#E
E
def gcd(var u :int, var v :int) { while (v != 0) { def r := u %% v u := v v := r } return u.abs() }
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).
#Euphoria
Euphoria
function hailstone(atom n) sequence s s = {n} while n != 1 do if remainder(n,2)=0 then n /= 2 else n = 3*n + 1 end if s &= n end while return s end function   function hailstone_count(atom n) integer count count = 1 while n != 1 do if remainder(n,2)=0 then n /= 2 else n = 3*n + 1 end if count += 1 end while return count end function   sequence s s = hailstone(27) puts(1,"hailstone(27) =\n") ? s printf(1,"len = %d\n\n",length(s))   integer max,imax,count max = 0 for i = 2 to 1e5-1 do count = hailstone_count(i) if count > max then max = count imax = i end if end for   printf(1,"The longest hailstone sequence under 100,000 is %d with %d elements.\n", {imax,max})