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
#REXX
REXX
/*REXX (using PC/REXX) to display a message in a window (which is bordered). */ if fcnPkg('rxWindow') ¬== 1 then do say 'RXWINDOW function package not loaded.' exit 13 end if pcVideo()==3 then normal= 7 else normal=13   window#=w_open(1, 1, 3, 80, normal) call w_border window# call w_put window#, 2, 2, center("Goodbye, World!", 80-2)   /*stick a fork in it, all we're done. */
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
#Ring
Ring
  Load "guilib.ring" New qApp { new qWidget() { setwindowtitle("Hello World") show() } exec() }  
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.
#Prolog
Prolog
to_gray(N, G) :- N0 is N >> 1, G is N xor N0.   from_gray(G, N) :- ( G > 0 -> S is G >> 1, from_gray(S, N0), N is G xor N0 ; N is 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.
#PureBasic
PureBasic
Procedure.i gray_encode(n) ProcedureReturn n ! (n >> 1) EndProcedure   Procedure.i gray_decode(g) Protected bit = 1 << (8 * SizeOf(Integer) - 2) Protected b = g & bit, p = b >> 1   While bit > 1 bit >> 1 b | (p ! (g & bit)) p = (b & bit) >> 1 Wend ProcedureReturn b EndProcedure   If OpenConsole() PrintN("Number Gray Binary Decoded") Define i, n For i = 0 To 31 g = gray_encode(i) Print(RSet(Str(i), 2, "0") + Space(5)) Print(RSet(Bin(g, #PB_Byte), 5, "0") + Space(2)) n = gray_decode(g) Print(RSet(Bin(n, #PB_Byte), 5, "0") + Space(3)) PrintN(RSet(Str(n), 2, "0")) Next   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole() EndIf
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!
#CMake
CMake
function(swap var1 var2) set(_SWAP_TEMPORARY "${${var1}}") set(${var1} "${${var2}}" PARENT_SCOPE) set(${var2} "${_SWAP_TEMPORARY}" PARENT_SCOPE) endfunction(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.
#Dart
Dart
/*This is a function which returns the greatest element in a list of numbers */ num findGreatestElement(List<num> list){ num greatestElement = list[0]; for (num element in list){ if (element>greatestElement) { greatestElement = element; } } return greatestElement; } /* and this is a shorter version */ import 'dart:math'; num findGreatestElement(List<num> list){ return list.reduce(max); }  
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#Clojure
Clojure
(defn gcd "(gcd a b) computes the greatest common divisor of a and b." [a b] (if (zero? b) a (recur b (mod a b))))
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):   hailstone sequence,   hailstone numbers   3x + 2 mapping,   3n + 1 problem   Collatz sequence   Hasse's algorithm   Kakutani's problem   Syracuse algorithm,   Syracuse problem   Thwaites conjecture   Ulam's problem The hailstone sequence is also known as   hailstone numbers   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). Task Create a routine to generate the hailstone sequence for a number. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.   (But don't show the actual sequence!) See also   xkcd (humourous).   The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).   The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
#Dc
Dc
27 [[--: ]nzpq]sq [d 2/ p]se [d 3*1+ p]so [d2% 0=e d1=q d2% 1=o d1=q lxx]dsxx
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).
#Nim
Nim
import bigints   proc min(a: varargs[BigInt]): BigInt = result = a[0] for i in 1..a.high: if a[i] < result: result = a[i]   proc hamming(limit: int): BigInt = var h = newSeq[BigInt](limit) x2 = initBigInt(2) x3 = initBigInt(3) x5 = initBigInt(5) i, j, k = 0 for i in 0..h.high: h[i] = initBigInt(1)   for n in 1 ..< limit: h[n] = min(x2, x3, x5) if x2 == h[n]: inc i x2 = h[i] * 2 if x3 == h[n]: inc j x3 = h[j] * 3 if x5 == h[n]: inc k x5 = h[k] * 5   result = h[h.high]   for i in 1 .. 20: stdout.write hamming(i), " " echo "" echo hamming(1691) echo hamming(1_000_000)
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
#Python
Python
import random t,g=random.randint(1,10),0 g=int(input("Guess a number that's between 1 and 10: ")) while t!=g:g=int(input("Guess again! ")) print("That's right!")
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.
#Ring
Ring
  # Project : Greatest subsequential sum   aList1 = [0, 1, 2, -3, 3, -1, 0, -4, 0, -1, -4, 2] see "[0, 1, 2, -3, 3, -1, 0, -4, 0, -1, -4, 2] -> " + sum(aList1) + nl aList2 = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1] see "[-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1] -> " + sum(aList2) + nl aList3 = [-1, -2, -3, -4, -5] see "[-1, -2, -3, -4, -5] -> " + sum(aList3) + nl aList4 = [] see "[] - > " + sum(aList4) + nl   func sum aList sumold = [] sumnew = [] snew = 0 flag = 0 if len(aList) = 0 return 0 ok for s=1 to len(aList) if aList[s] > -1 flag = 1 ok next if flag = 0 return "[]" ok for n=1 to len(aList) sumold = [] sold = 0 for m=n to len(aList) add(sumold, aList[m]) sold = sold + aList[m] if sold > snew snew = sold sumnew = sumold ok next next return showarray(sumnew)   func showarray(a) conv = "[" for i = 1 to len(a) conv = conv + string(a[i]) + ", " next conv = left(conv, len(conv) - 2) + "]" return conv  
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.
#Ruby
Ruby
def subarray_sum(arr) max, slice = 0, [] arr.each_index do |i| (i...arr.length).each do |j| sum = arr[i..j].inject(0, :+) max, slice = sum, arr[i..j] if sum > max end end [max, slice] end
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)
#LiveCode
LiveCode
command guessTheNumber lowN highN local tNumber, tguess, tmin, tmax if lowN is empty or lowN < 1 then put 1 into tmin else put lowN into tmin end if if highN is empty then put 10 into tmax else put highN into tmax end if put random(tmax - tmin + 1) + tmin - 1 into tNumber repeat until tguess is tNumber ask question "Please enter a number between" && tmin && "and" && tmax titled "Guess the number" if it is not empty then put it into tguess if tguess is tNumber then answer "Well guessed!" else if tguess < tNumber then answer "too low" else answer "too high" end if else exit repeat end if end repeat end guessTheNumber
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
#MAD
MAD
NORMAL MODE IS INTEGER BOOLEAN CYCLE DIMENSION CYCLE(200) VECTOR VALUES OUTFMT = $I2*$   SEEN = 0 I = 0   NEXNUM THROUGH ZERO, FOR K=0, 1, K.G.200 ZERO CYCLE(K) = 0B I = I + 1 SUMSQR = I CHKLP N = SUMSQR SUMSQR = 0 SUMLP DIG = N-N/10*10 SUMSQR = SUMSQR + DIG*DIG N = N/10 WHENEVER N.NE.0, TRANSFER TO SUMLP WHENEVER SUMSQR.E.1, TRANSFER TO HAPPY WHENEVER CYCLE(SUMSQR), TRANSFER TO NEXNUM CYCLE(SUMSQR) = 1B TRANSFER TO CHKLP   HAPPY PRINT FORMAT OUTFMT,I SEEN = SEEN+1 WHENEVER SEEN.L.8, TRANSFER TO NEXNUM   END OF PROGRAM  
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
#Io
Io
"Hello world!" println
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
#Robotic
Robotic
require 'gtk2'   window = Gtk::Window.new window.title = 'Goodbye, World' window.signal_connect(:delete-event) { Gtk.main_quit } window.show_all   Gtk.main
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.
#Python
Python
def gray_encode(n): return n ^ n >> 1   def gray_decode(n): m = n >> 1 while m: n ^= m m >>= 1 return n     if __name__ == '__main__': print("DEC, BIN => GRAY => DEC") for i in range(32): gray = gray_encode(i) dec = gray_decode(gray) print(f" {i:>2d}, {i:>05b} => {gray:>05b} => {dec:>2d}")
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.
#Quackery
Quackery
[ dup 1 >> ^ ] is encodegray ( n --> n )   [ dup [ dip [ 1 >> ] over ^ over 0 = until ] nip ] is decodegray ( n --> n )   [ [] unrot times [ 2 /mod char 0 + rot join swap ] drop echo$ ] is echobin ( n n --> )     say "number encoded decoded" cr say "------ ------- -------" cr 32 times [ sp i^ 5 echobin say " -> " i^ encodegray dup 5 echobin say " -> " decodegray 5 echobin cr ]
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!
#COBOL
COBOL
  PROGRAM-ID. SWAP-DEMO. AUTHOR. Bill Gunshannon. INSTALLATION. Home. DATE-WRITTEN. 16 December 2021. ************************************************************ ** Program Abstract: ** A simple program to demonstrate the SWAP subprogram. ** ************************************************************   DATA DIVISION.   WORKING-STORAGE SECTION.   01 Val1 PIC X(72). 01 Val2 PIC X(72).   PROCEDURE DIVISION.   Main-Program.   DISPLAY 'Enter a Value: ' WITH NO ADVANCING. ACCEPT Val1. DISPLAY 'Enter another Value: ' WITH NO ADVANCING. ACCEPT Val2. DISPLAY ' ' . DISPLAY 'First value: ' FUNCTION TRIM(Val1) . DISPLAY 'Second value: ' FUNCTION TRIM(Val2) .   CALL "SWAP" USING BY REFERENCE Val1, BY REFERENCE Val2.   DISPLAY ' '. DISPLAY 'After SWAP '. DISPLAY ' '. DISPLAY 'First value: ' FUNCTION TRIM(Val1). DISPLAY 'Second value: ' FUNCTION TRIM(Val2).   STOP RUN.   END PROGRAM SWAP-DEMO.   IDENTIFICATION DIVISION. PROGRAM-ID. SWAP. AUTHOR. Bill Gunshannon. INSTALLATION. Home. DATE-WRITTEN. 16 December 2021. ************************************************************ ** Program Abstract: ** SWAP any Alphanumeric value. Only limit is 72 ** character size. But that can be adjusted for ** whatever use one needs. ************************************************************   DATA DIVISION.   WORKING-STORAGE SECTION.   01 TEMP PIC X(72).   LINKAGE SECTION.   01 Field1 PIC X(72). 01 Field2 PIC X(72).   PROCEDURE DIVISION USING BY REFERENCE Field1, BY REFERENCE Field2.   MOVE Field1 to TEMP. MOVE Field2 to Field1. MOVE TEMP to Field2.   GOBACK.   END PROGRAM 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.
#dc
dc
[sm llx] sg [lm p q] sq [d lm <u s_ z 0 =q llx] sl [d sm] su   ["Put list of numbers on the stack starting here, then execute g"] s_   3.14159265358979 sp   _275.0 _111.19 0.0 _1234568.0 lp lp _1 *   lgx
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.
#CLU
CLU
gcd = proc (a, b: int) returns (int) while b~=0 do a, b := b, a//b end return(a) end gcd   start_up = proc() po: stream := stream$primary_input() as: array[int] := array[int]$[18, 1071, 3528] bs: array[int] := array[int]$[12, 1029, 3780] for i: int in array[int]$indexes(as) do stream$putl(po, "gcd(" || int$unparse(as[i]) || ", " || int$unparse(bs[i]) || ") = " || int$unparse(gcd(as[i], bs[i]))) end end start_up
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).
#DCL
DCL
$ n = f$integer( p1 ) $ i = 1 $ loop: $ if p2 .nes. "QUIET" then $ s'i = n $ if n .eq. 1 then $ goto done $ i = i + 1 $ if .not. n $ then $ n = n / 2 $ else $ if n .gt. 715827882 then $ exit ! avoid overflowing $ n = 3 * n + 1 $ endif $ goto loop $ done: $ if p2 .nes. "QUIET" $ then $ penultimate_i = i - 1 $ antepenultimate_i = i - 2 $ preantepenultimate_i = i - 3 $ write sys$output "sequence has ", i, " elements starting with ", s1, ", ", s2, ", ", s3, ", ", s4, " and ending with ", s'preantepenultimate_i, ", ", s'antepenultimate_i, ", ", s'penultimate_i, ", ", s'i $ endif $ sequence_length == i
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).
#OCaml
OCaml
module ISet = Set.Make(struct type t = int let compare=compare end)   let pq = ref (ISet.singleton 1)   let next () = let m = ISet.min_elt !pq in pq := ISet.(remove m !pq |> add (2*m) |> add (3*m) |> add (5*m)); m   let () =   print_string "The first 20 are: ";   for i = 1 to 20 do Printf.printf "%d " (next ()) done;   for i = 21 to 1690 do ignore (next ()) done;   Printf.printf "\nThe 1691st is %d\n" (next ());
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
#QB64_2
QB64
START: CLS RANDOMIZE TIMER num = INT(RND * 10) + 1 DO INPUT "Enter a number between 1 and 10: ", n IF n = num THEN EXIT DO PRINT "Nope." LOOP UNTIL n = num INPUT "Well guessed! Go again"; a$ IF LEFT$(LCASE$(a$), 1) = "y" THEN GOTO START
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
#QB64_3
QB64
  'Task 'Plus features: 1) AI gives suggestions about your guess ' 2) AI controls wrong input by user (numbers outer 1 and 10). ' 3) player can choose to replay the game   Randomize Timer Dim As Integer Done, Guess, Number   Done = 1 Guess = 0 While Done Cls Number = Rnd * 10 + 1 Do While Number <> Guess Cls Locate 2, 1 Input "What number have I thought? (1-10)", Guess If Guess > 0 And Guess < 11 Then If Guess = Number Then Locate 4, 1: Print "Well done, you win!"; Space$(20) Exit Do ElseIf Guess > Number Then Locate 4, 1: Print "Too high, try lower"; Space$(20) ElseIf Guess < Number Then Locate 4, 1: Print "Too low, try higher"; Space$(20) End If Else Print "Wrong input data! Try again"; Space$(20) End If _Delay 1 If Done = 11 Then Exit Do Else Done = Done + 1 Loop If Done = 11 Then Locate 4, 1: Print "Ah ah ah, I win and you loose!"; Space$(20) Else Locate 4, 1: Print " Sigh, you win!"; Space$(20) End If Locate 6, 1: Input "Another play? 1 = yes, others values = no ", Done If Done <> 1 Then Done = 0 Wend 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.
#Run_BASIC
Run BASIC
seq$ = "-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1" max = -999 for i = 1 to 11 sum = 0 for j = i to 11 sum = sum + val(word$(seq$,j,",")) If sum > max then max = sum i1 = i j1 = j end if next j next i print "Sum:"; for i = i1 to j1 print word$(seq$,i,",");","; next i print " = ";max
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.
#Rust
Rust
fn main() { let nums = [1,2,39,34,20, -20, -16, 35, 0];   let mut max = 0; let mut boundaries = 0..0;   for length in 0..nums.len() { for start in 0..nums.len()-length { let sum = (&nums[start..start+length]).iter() .fold(0, |sum, elem| sum+elem); if sum > max { max = sum; boundaries = start..start+length; } } }   println!("Max subsequence sum: {} for {:?}", max, &nums[boundaries]);; }
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)
#Locomotive_Basic
Locomotive Basic
10 CLS:RANDOMIZE TIME 20 PRINT "Please specify lower and upper limits":guess=0 30 INPUT " (must be positive integers) :", first, last 40 IF first<1 OR last<1 THEN 20 50 num=INT(RND*(last-first+1)+first) 60 WHILE num<>guess 70 INPUT "Your guess? ", guess 80 IF guess<num THEN PRINT "too small!" 90 IF guess>num THEN PRINT "too large!" 100 WEND 110 INPUT "That's correct! Another game (y/n)? ", yn$ 120 IF yn$="y" THEN 20  
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
#Maple
Maple
SumSqDigits := proc( n :: posint ) local s := 0; local m := n; while m <> 0 do s := s + irem( m, 10, 'm' )^2 end do; s end proc:
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
#Ioke
Ioke
"Hello world!" println
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
#Ruby
Ruby
require 'gtk2'   window = Gtk::Window.new window.title = 'Goodbye, World' window.signal_connect(:delete-event) { Gtk.main_quit } window.show_all   Gtk.main
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.
#R
R
  GrayEncode <- function(binary) { gray <- substr(binary,1,1) repeat { if (substr(binary,1,1) != substr(binary,2,2)) gray <- paste(gray,"1",sep="") else gray <- paste(gray,"0",sep="") binary <- substr(binary,2,nchar(binary)) if (nchar(binary) <=1) { break } } return (gray) } GrayDecode <- function(gray) { binary <- substr(gray,1,1) repeat { if (substr(binary,nchar(binary),nchar(binary)) != substr(gray,2,2)) binary <- paste(binary ,"1",sep="") else binary <- paste(binary ,"0",sep="") gray <- substr(gray,2,nchar(gray))   if (nchar(gray) <=1) { break } } return (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!
#ColdFusion
ColdFusion
<cfset temp = a /> <cfset a = b /> <cfset b = temp />
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.
#DCL
DCL
$ list = "45,65,81,12,0,13,-56,123,-123,888,12,0" $ max = f$integer( f$element( 0, ",", list )) $ i = 1 $ loop: $ element = f$element( i, ",", list ) $ if element .eqs. "," then $ goto done $ element = f$integer( element ) $ if element .gt. max then $ max = element $ i = i + 1 $ goto loop $ done: $ show symbol max
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. GCD.   DATA DIVISION. WORKING-STORAGE SECTION. 01 A PIC 9(10) VALUE ZEROES. 01 B PIC 9(10) VALUE ZEROES. 01 TEMP PIC 9(10) VALUE ZEROES.   PROCEDURE DIVISION. Begin. DISPLAY "Enter first number, max 10 digits." ACCEPT A DISPLAY "Enter second number, max 10 digits." ACCEPT B IF A < B MOVE B TO TEMP MOVE A TO B MOVE TEMP TO B END-IF   PERFORM UNTIL B = 0 MOVE A TO TEMP MOVE B TO A DIVIDE TEMP BY B GIVING TEMP REMAINDER B END-PERFORM DISPLAY "The gcd is " A STOP RUN.
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).
#Delphi
Delphi
program ShowHailstoneSequence;   {$APPTYPE CONSOLE}   uses SysUtils, Generics.Collections;   procedure GetHailstoneSequence(aStartingNumber: Integer; aHailstoneList: TList<Integer>); var n: Integer; begin aHailstoneList.Clear; aHailstoneList.Add(aStartingNumber); n := aStartingNumber;   while n <> 1 do begin if Odd(n) then n := (3 * n) + 1 else n := n div 2; aHailstoneList.Add(n); end; end;   var i: Integer; lList: TList<Integer>; lMaxSequence: Integer; lMaxLength: Integer; begin lList := TList<Integer>.Create; try GetHailstoneSequence(27, lList); Writeln(Format('27: %d elements', [lList.Count])); Writeln(Format('[%d,%d,%d,%d ... %d,%d,%d,%d]', [lList[0], lList[1], lList[2], lList[3], lList[lList.Count - 4], lList[lList.Count - 3], lList[lList.Count - 2], lList[lList.Count - 1]])); Writeln;   lMaxSequence := 0; lMaxLength := 0; for i := 1 to 100000 do begin GetHailstoneSequence(i, lList); if lList.Count > lMaxLength then begin lMaxSequence := i; lMaxLength := lList.Count; end; end; Writeln(Format('Longest sequence under 100,000: %d with %d elements', [lMaxSequence, lMaxLength])); finally lList.Free; end;   Readln; 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).
#Oz
Oz
declare fun lazy {HammingFun} 1|{FoldL1 [{MultHamming 2} {MultHamming 3} {MultHamming 5}] LMerge} end   Hamming = {HammingFun}   fun {MultHamming N} {LMap Hamming fun {$ X} N*X end} end   fun lazy {LMap Xs F} case Xs of nil then nil [] X|Xr then {F X}|{LMap Xr F} end end   fun lazy {LMerge Xs=X|Xr Ys=Y|Yr} if X < Y then X|{LMerge Xr Ys} elseif X > Y then Y|{LMerge Xs Yr} else X|{LMerge Xr Yr} end end   fun {FoldL1 X|Xr F} {FoldL Xr F X} end in {ForAll {List.take Hamming 20} System.showInfo} {System.showInfo {Nth Hamming 1690}} {System.showInfo {Nth Hamming 1000000}}
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
#Quackery
Quackery
randomise 10 random 1+ number$ say 'I chose a number between 1 and 10.' cr [ $ 'Your guess? ' input over = if done again ] drop 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
#R
R
f <- function() { print("Guess a number between 1 and 10 until you get it right.") n <- sample(10, 1) while (as.numeric(readline()) != n) { print("Try again.") } print("You got it!") }
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.
#Scala
Scala
def maxSubseq(l: List[Int]) = l.scanRight(Nil : List[Int]) { case (el, acc) if acc.sum + el < 0 => Nil case (el, acc) => el :: acc } max Ordering.by((_: List[Int]).sum)   def biggestMaxSubseq(l: List[Int]) = l.scanRight(Nil : List[Int]) { case (el, acc) if acc.sum + el < 0 => Nil case (el, acc) => el :: acc } max Ordering.by((ss: List[Int]) => (ss.sum, ss.length))   def biggestMaxSubseq[N](l: List[N])(implicit n: Numeric[N]) = { import n._ l.scanRight(Nil : List[N]) { case (el, acc) if acc.sum + el < zero => Nil case (el, acc) => el :: acc } max Ordering.by((ss: List[N]) => (ss.sum, ss.length)) }   def linearBiggestMaxSubseq[N](l: List[N])(implicit n: Numeric[N]) = { import n._ l.scanRight((zero, Nil : List[N])) { case (el, (acc, _)) if acc + el < zero => (zero, Nil) case (el, (acc, ss)) => (acc + el, el :: ss) } max Ordering.by((t: (N, List[N])) => (t._1, t._2.length)) _2 }
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)
#Logo
Logo
to guess [:max 100] local "number make "number random :max local "guesses make "guesses 0   local "guess forever [ (type [Guess my number! \(range 1 -\ ] :max "\):\ ) make "guess first readlist ifelse (or (not numberp :guess) (lessp :guess 1) (greaterp :guess :max)) [ print sentence [Guess must be a number between 1 and] (word :max ".) ] [ make "guesses (:guesses + 1) ifelse lessp :guess :number [ print [Too low!] ] [ifelse equalp :guess :number [ (print [You got it in] :guesses "guesses!) stop ] [ print [Too high!] ]] ] ] end  
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
AddSumSquare[input_]:=Append[input,Total[IntegerDigits[Last[input]]^2]] NestUntilRepeat[a_,f_]:=NestWhile[f,{a},!MemberQ[Most[Last[{##}]],Last[Last[{##}]]]&,All] HappyQ[a_]:=Last[NestUntilRepeat[a,AddSumSquare]]==1
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
#IS-BASIC
IS-BASIC
PRINT "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
#Run_BASIC
Run BASIC
' do it with javascript html "<script>alert('Goodbye, World!');</script>"
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.
#Racket
Racket
  #lang racket   (define (gray-encode n) (bitwise-xor n (arithmetic-shift n -1)))   (define (gray-decode n) (letrec ([loop (lambda(g bits) (if (> bits 0) (loop (bitwise-xor g bits) (arithmetic-shift bits -1)) g))]) (loop 0 n)))   (define (to-bin n) (format "~b" n)) (define (show-table) (for ([i (in-range 1 32)]) (printf "~a | ~a | ~a ~n" (~r i #:min-width 2 #:pad-string "0") (~a (to-bin(gray-encode i)) #:width 5 #:align 'right #:pad-string "0") (~a (to-bin (gray-decode(gray-encode i))) #:width 5 #:align 'right #:pad-string "0"))))  
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.
#Raku
Raku
sub gray_encode ( Int $n --> Int ) { return $n +^ ( $n +> 1 ); }   sub gray_decode ( Int $n is copy --> Int ) { my $mask = 1 +< (32-2); $n +^= $mask +> 1 if $n +& $mask while $mask +>= 1; return $n; }   for ^32 -> $n { my $g = gray_encode($n); my $d = gray_decode($g); printf "%2d: %5b => %5b => %5b: %2d\n", $n, $n, $g, $d, $d; die if $d != $n; }
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#Common_Lisp
Common Lisp
(rotatef a b)   (psetq a b b a)
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.
#Delphi
Delphi
  program GElemLIst; {$IFNDEF FPC} {$Apptype Console} {$ENDIF}   uses math; const MaxCnt = 10000; var IntArr : array of integer; fltArr : array of double; i: integer; begin setlength(fltArr,MaxCnt); //filled with 0 setlength(IntArr,MaxCnt); //filled with 0.0 randomize; i := random(MaxCnt); //choose a random place IntArr[i] := 1; fltArr[i] := 1.0; writeln(Math.MaxIntValue(IntArr)); // Array of Integer writeln(Math.MaxValue(fltArr)); 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.
#Cobra
Cobra
  class Rosetta def gcd(u as number, v as number) as number u, v = u.abs, v.abs while v > 0 u, v = v, u % v return u   def main print "gcd of [12] and [8] is [.gcd(12, 8)]" print "gcd of [12] and [-8] is [.gcd(12, -8)]" print "gcd of [96] and [27] is [.gcd(27, 96)]" print "gcd of [51] and [34] is [.gcd(34, 51)]"  
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).
#D.C3.A9j.C3.A0_Vu
Déjà Vu
local hailstone: swap [ over ] while < 1 dup: if % over 2: #odd ++ * 3 else: #even / swap 2 swap push-through rot dup drop   if = (name) :(main): local :h27 hailstone 27 !. = 112 len h27 !. = 27 h27! 0 !. = 82 h27! 1 !. = 41 h27! 2 !. = 124 h27! 3 !. = 8 h27! 108 !. = 4 h27! 109 !. = 2 h27! 110 !. = 1 h27! 111   local :max 0 local :maxlen 0 for i range 1 99999: dup len hailstone i if < maxlen: set :maxlen set :max i else: drop !print( "number: " to-str max ", length: " to-str maxlen ) else: @hailstone
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).
#PARI.2FGP
PARI/GP
Hupto(n)={ my(v=vector(n),x2=2,x3=3,x5=5,i=1,j=1,k=1,t); v[1]=1; for(m=2,n, v[m]=t=min(x2,min(x3,x5)); if(x2 == t, x2 = v[i++] << 1); if(x3 == t, x3 = 3 * v[j++]); if(x5 == t, x5 = 5 * v[k++]); ); v }; H(n)=Hupto(n)[n];   Hupto(20) H(1691) H(10^6)
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
#Racket
Racket
#lang racket (define (guess-number) (define number (add1 (random 10))) (let loop () (define guess (read)) (if (equal? guess number) (display "Well guessed!\n") (loop))))
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
#Raku
Raku
my $number = (1..10).pick; repeat {} until prompt("Guess a number: ") == $number; say "Guessed right!";
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.
#Scheme
Scheme
(define (maxsubseq in) (let loop ((_sum 0) (_seq (list)) (maxsum 0) (maxseq (list)) (l in)) (if (null? l) (cons maxsum (reverse maxseq)) (let* ((x (car l)) (sum (+ _sum x)) (seq (cons x _seq))) (if (> sum 0) (if (> sum maxsum) (loop sum seq sum seq (cdr l)) (loop sum seq maxsum maxseq (cdr l))) (loop 0 (list) maxsum maxseq (cdr l)))))))
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)
#Lua
Lua
math.randomseed(os.time()) me_win=false my_number=math.random(1,10) while me_win==false do print "Guess my number from 1 to 10:" your_number = io.stdin:read'*l' if type(tonumber(your_number))=="number" then your_number=tonumber(your_number) if your_number>10 or your_number<1 then print "Your number was not between 1 and 10, try again." elseif your_number>my_number then print "Your number is greater than mine, try again." elseif your_number<my_number then print "Your number is smaller than mine, try again." elseif your_number==my_number then print "That was correct." me_win=true end else print "Your input was not a number, try again." end end  
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
#MATLAB
MATLAB
function findHappyNumbers nHappy = 0; k = 1; while nHappy < 8 if isHappyNumber(k, []) fprintf('%d ', k) nHappy = nHappy+1; end k = k+1; end fprintf('\n') end   function hap = isHappyNumber(k, prev) if k == 1 hap = true; elseif ismember(k, prev) hap = false; else hap = isHappyNumber(sum((sprintf('%d', k)-'0').^2), [prev k]); 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
#Isabelle
Isabelle
theory Scratch imports Main begin value ‹''Hello world!''› end
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Rust
Rust
// cargo-deps: gtk extern crate gtk; use gtk::traits::*; use gtk::{Window, WindowType, WindowPosition}; use gtk::signal::Inhibit;   fn main() { gtk::init().unwrap(); let window = Window::new(WindowType::Toplevel).unwrap();   window.set_title("Goodbye, World!"); window.set_border_width(10); window.set_window_position(WindowPosition::Center); window.set_default_size(350, 70); window.connect_delete_event(|_,_| { gtk::main_quit(); Inhibit(false) });   window.show_all(); gtk::main(); }
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
#Scala
Scala
swing.Dialog.showMessage(message = "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.
#REXX
REXX
/*REXX program converts decimal number ───► binary ───► gray code ───► binary.*/ parse arg N . /*get the optional argument from the CL*/ if N=='' | N=="," then N=31 /*Not specified? Then use the default.*/ L=max(1,length(strip(x2b(d2x(N)),'L',0))) /*find the max binary length of N.*/ w=14 /*used for the formatting of cell width*/ _=center('binary',w,'─') /*the 2nd and 4th part of the header.*/ say center('decimal', w, "─")'►' _"►" center('gray code', w, '─')"►" _ /* [+] the output header*/ do j=0 to N; b=right(x2b(d2x(j)),L,0) /*process 0 ──► N. */ g=b2gray(b) /*convert binary number to gray code. */ a=gray2b(g) /*convert the gray code to binary. */ say center(j,w+1) center(b,w+1) center(g,w+1) center(a,w+1) end /*j*/ exit /*stick a fork in it, we're all done. */ /*────────────────────────────────────────────────────────────────────────────*/ b2gray: procedure; parse arg x 1 $ 2; do b=2 to length(x) $=$||(substr(x,b-1,1) && substr(x,b,1)) end /*b*/ return $ /*────────────────────────────────────────────────────────────────────────────*/ gray2b: procedure; parse arg x 1 $ 2; do g=2 to length(x) $=$ || (right($,1) && substr(x,g,1)) end /*g*/ /* ↑ */ /* │ */ return $ /*this is an eXclusive OR ►─────────┘ */
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!
#Computer.2Fzero_Assembly
Computer/zero Assembly
LDA 29 STA 31 LDA 30 STA 29 LDA 31 STA 30 STP --- org 29 byte $0F byte $E0 byte $00
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.
#Dyalect
Dyalect
func max(xs) { var y for x in xs { if y == nil || x > y { y = x } } y }   var xs = [1..10] max(xs)
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#CoffeeScript
CoffeeScript
  gcd = (x, y) -> if y == 0 then x else gcd y, x % y  
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).
#EchoLisp
EchoLisp
  (lib 'hash) (lib 'sequences) (lib 'compile)   (define (hailstone n) (when (> n 1) (if (even? n) (/ n 2) (1+ (* n 3)))))   (define H (make-hash))   ;; (iterator/f seed f) returns seed, (f seed) (f(f seed)) ...   (define (hlength seed) (define collatz (iterator/f hailstone seed)) (or (hash-ref H seed) ;; known ? (hash-set H seed (for ((i (in-naturals)) (h collatz)) ;; add length of subsequence if already known #:break (hash-ref H h) => (+ i (hash-ref H h)) (1+ i)))))   (define (task (nmax 100000)) (for ((n [1 .. nmax])) (hlength n)) ;; fill hash table   (define hmaxlength (apply max (hash-values H))) (define hmaxseed (hash-get-key H hmaxlength)) (writeln 'maxlength= hmaxlength 'for hmaxseed))    
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).
#Pascal
Pascal
  program HammNumb; {$IFDEF FPC} {$MODE DELPHI} {$OPTIMIZATION ON} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF} { type NativeUInt = longWord; } var pot : array[0..2] of NativeUInt;   function NextHammNumb(n:NativeUInt):NativeUInt; var q,p,nr : NativeUInt; begin repeat nr := n+1; n := nr;   p := 0; while NOT(ODD(nr)) do begin inc(p); nr := nr div 2; end; Pot[0]:= p;   p := 0; q := nr div 3; while q*3=nr do Begin inc(P); nr := q; q := nr div 3; end; Pot[1] := p;   p := 0; q := nr div 5; while q*5=nr do Begin inc(P); nr := q; q := nr div 5; end; Pot[2] := p;   until nr = 1; result:= n; end;   procedure Check; var i,n: NativeUint; begin n := 1; for i := 1 to 20 do begin n := NextHammNumb(n); write(n,' '); end; writeln; writeln; n := 1; for i := 1 to 1690 do n := NextHammNumb(n); writeln('No ',i:4,' | ',n,' = 2^',Pot[0],' 3^',Pot[1],' 5^',Pot[2]); end;   Begin Check; 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
#RapidQ
RapidQ
  RANDOMIZE number = rnd(10) + 1 Print "I selected a number between 1 and 10, try to find it:" + chr$(10)   while Guess <> Number input "Your guess: "; Guess wend   print "You guessed right, well done !" input "Press enter to quit";a$  
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
#Rascal
Rascal
import vis::Render; import vis::Figure; import util::Math;   public void Guess(){ random = arbInt(10); entered = ""; guess = false; figure = box(vcat([ text("Try to guess the number from 0 to 9."), textfield("Put your guess here", void(str s){guess = (toInt(s)==random); entered = s; }, fillColor("white")), text(str(){return guess ? "Correct answer!" : "This is false, the number is not <entered>.";}), button("Start over", void(){random = arbInt(10);}) ])); render(figure); }
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.
#Seed7
Seed7
$ include "seed7_05.s7i";   const func array integer: maxSubseq (in array integer: sequence) is func result var array integer: maxSequence is 0 times 0; local var integer: number is 0; var integer: index is 0; var integer: currentSum is 0; var integer: currentStart is 1; var integer: maxSum is 0; var integer: startPos is 0; var integer: endPos is 0; begin for number key index range sequence do currentSum +:= number; if currentSum < 0 then currentStart := succ(index); currentSum := 0; elsif currentSum > maxSum then maxSum := currentSum; startPos := currentStart; endPos := index; end if; end for; if startPos <= endPos and startPos >= 1 and endPos >= 1 then maxSequence := sequence[startPos .. endPos]; end if; end func;   const proc: main is func local const array integer: a1 is [] (-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1); const array integer: a2 is [] (-1, -2, -3, -5, -6, -2, -1, -4, -4, -2, -1); var integer: number is 0; begin write("Maximal subsequence:"); for number range maxSubseq(a1) do write(" " <& number); end for; writeln; write("Maximal subsequence:"); for number range maxSubseq(a2) do write(" " <& number); end for; writeln; 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.
#Sidef
Sidef
func maxsubseq(*a) { var (start, end, sum, maxsum) = (-1, -1, 0, 0); a.each_kv { |i, x| sum += x; if (maxsum < sum) { maxsum = sum; end = i; } elsif (sum < 0) { sum = 0; start = i; } }; a.ft(start+1, end); }   say maxsubseq(-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1); say maxsubseq(-2, -2, -1, 3, 5, 6, -1, 4, -4, 2, -1); say maxsubseq(-2, -2, -1, -3, -5, -6, -1, -4, -4, -2, -1);
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#M2000_Interpreter
M2000 Interpreter
  Module GuessNumber { Read Min, Max chosen = Random(Min, Max) print "guess a whole number between ";Min;" and ";Max do { \\ we use guess so Input get integer value \\ if we press enter without a number we get error do { \\ if we get error then we change line, checking the cursor position If Pos>0 then Print Try ok { input "Enter your number " , guess% } } until ok Select Case guess% case min to chosen-1 print "Sorry, your number was too low" case chosen+1 to max print "Sorry, your number was too high" case chosen print "Well guessed!" else case print "That was an invalid number" end select } until guess% = chosen } GuessNumber 5, 15  
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
#MAXScript
MAXScript
  fn isHappyNumber n = ( local pastNumbers = #() while n != 1 do ( n = n as string local newNumber = 0 for i = 1 to n.count do ( local digit = n[i] as integer newNumber += pow digit 2 ) n = newNumber if (finditem pastNumbers n) != 0 do return false append pastNumbers newNumber ) n == 1 ) printed = 0 for i in (for h in 1 to 500 where isHappyNumber h collect h) do ( if printed == 8 do exit print i as string printed += 1   )  
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
#IWBASIC
IWBASIC
  OPENCONSOLE   PRINT"Hello world!"   'This line could be left out. PRINT:PRINT:PRINT"Press any key to end."   'Keep the console from closing right away so the text can be read. DO:UNTIL INKEY$<>""   CLOSECONSOLE   END  
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Scheme
Scheme
  #!r6rs   ;; PS-TK example: display frame + label   (import (rnrs) (lib pstk main) ; change this to refer to your PS/Tk installation )   (define tk (tk-start)) (tk/wm 'title tk "PS-Tk Example: Label")   (let ((label (tk 'create-widget 'label 'text: "Goodbye, world"))) (tk/place label 'height: 20 'width: 50 'x: 10 'y: 20))   (tk-event-loop tk)  
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
#Scilab
Scilab
messagebox("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.
#Ring
Ring
  # Project : Gray code   pos = 5 see "0 : 00000 => 00000 => 00000" + nl for n = 1 to 31 res1 = tobase(n, 2, pos) res2 = tobase(grayencode(n), 2, pos) res3 = tobase(graydecode(n), 2, pos) see "" + n + " : " + res1 + " => " + res2 + " => " + res3 + nl next   func grayencode(n) return n ^ (n >> 1)   func graydecode(n) p = n while (n = n >> 1) p = p ^ n end return p   func tobase(nr, base, pos) binary = 0 i = 1 while(nr != 0) remainder = nr % base nr = floor(nr/base) binary= binary + (remainder*i) i = i*10 end result = "" for nr = 1 to pos - len(string(binary)) result = result + "0" next result = result + string(binary) return result  
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.
#Ruby
Ruby
class Integer # Converts a normal integer to a Gray code. def to_gray raise Math::DomainError, "integer is negative" if self < 0 self ^ (self >> 1) end   # Converts a Gray code to a normal integer. def from_gray raise Math::DomainError, "integer is negative" if self < 0 recurse = proc do |i| next 0 if i == 0 o = recurse[i >> 1] << 1 o | (i[0] ^ o[1]) end recurse[self] end end   (0..31).each do |number| encoded = number.to_gray decoded = encoded.from_gray printf "%2d : %5b => %5b => %5b : %2d\n", number, number, encoded, decoded, decoded end
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#Crystal
Crystal
a, b = b, a
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.
#D.C3.A9j.C3.A0_Vu
Déjà Vu
max lst: lst! 0 for item in copy lst: if > item dup: item drop   !. max [ 10 300 999 9 ]
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.
#Common_Lisp
Common Lisp
CL-USER> (gcd 2345 5432) 7
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).
#EDSAC_order_code
EDSAC order code
  [Hailstone (or Collatz) task for Rosetta Code. EDSAC program, Initial Orders 2.]   [This program shows how subroutines can be called via the phi, H, N, ..., V parameters, so that the code doesn't have to be changed if the subroutines are moved about in store. See Wilkes, Wheeler and Gill, 1951 edition, page 18.]   [Library subroutine P7, prints long strictly positive integer; 10 characters, right justified, padded left with spaces. Input: 0D = integer to be printed. Closed, even; 35 storage locations; working position 4D.] T 55 K [call subroutine via V parameter] P 56 F [address of subroutine] E 25 K T V GKA3FT26@H28#@NDYFLDT4DS27@TFH8@S8@T1FV4DAFG31@SFLDUFOFFFSFL4F T4DA1FA27@G11@XFT28#ZPFT27ZP1024FP610D@524D!FO30@SFL8FE22@   [Subroutine to print a string placed after the subroutine call. One location per character, with character in top 5 bits. Last character flagged by having bit 0 set. 17 locations, workspace 0F.] T 54 K [call subroutine via C parameter] P 91 F [address of subroutine] E 25 K T C GKH16@A2FG4@A6@A2FT6@AFTFOFCFSFE3@A6@A3FT15@EFV2047F   [************ Rosetta Code task ************ Subroutine to generate and optionally store the hailstone (Collatz) sequence for the passed-in initial term n. Input: 4D = n, 35-bit positive integer 6F = start address of sequence if stored; must be even; 0 = don't store Output: 7F = number of terms in sequence, or -1 if error Workspace: 0D (general), 8D (term of sequence) Must be loaded at an even address.] T 45 K [call subroutine via H parameter] P 108 F [address of subroutine] E 25 K T H G K A 3 F T 46 @ H 54#@ [mult reg := 1 to test odd/even] A 4 D [load n passed in by caller] T 8 D [term := n] A 54 @ [load 1 (single)] T 7 F [include initial term in count] A 6 F [load address for store] S 56 @ [test for 0; allow for pre-inc] G 11 @ [skip next if storing not wanted] A 12 @ [make 'T addr D' order] [11] T 21 @ [plant T order, or -ve value if not storing (note that a T order is +ve as an integer)] [Loop: deal with current term in sequence First store it, if user requested that] [12] T D [clear acc; also serves to make 'T addr D' order] A 21 @ [load T order to store term] G 22 @ [jump if caller doesn't want store] A 56 @ [pre-inc the address] U 21 @ [update T order] S 51 @ [check not gone beyond max EDSAC address] E 47 @ [error exit if it has] T F [clear acc] A 8 D [load term] [21] T D [store] [22] T F [clear acc] A 54#@ [load 1 (double)] S 8 D [1 - term] E 46 @ [if term = 1, jump out with acc = 0] T F [clear acc] C 8 D [acc := term AND 1] S 54#@ [test whether 0 or 1] G 38 @ [jump if term is even] [Here if term is odd; acc = 0] A 8 D [load term] S 52#@ [guard against numeric overflow] E 47 @ [jump if overflow] A 52#@ [restore term after test] L D [term*2] A 8 D [term*3] A 54#@ [plus 1] E 41 @ [join common code] [Here if term is even] [38] T F [clear acc] A 8 D [load term] R D [term/2] [Common code, acc = new term] [41] T 8 D [store new term] A 7 F [load count] A 54 @ [add 1] T 7 F [update count] E 12 @ [loop back] [Here when sequence has reached 1 Assume jump here with acc = 0] [46] E F [return with acc = 0] [47] T F [here on error] S 54 F [acc := -1] T 7 F [return that as count] E 46 @ [Arrange the following to ensure even addresses for 35-bit values] [51] T 1024 F [for checking valid address] [52] H 682 DT 682 D [(2^34 - 1)/3] [54] P DP F [1] [56] P 2 F [to change addresses by 2]   [Program to demonstrate Rosetta Code subroutine] T 180 K G K [Double constants] [P 500 F P F] [maximum n = 1000"] [0] & 848 F PF [maximum n = 100000] [2] P 13 D PF [n = 27 as demo of sequence] [4] P D PF [1] [Double variables] [6] P F P F [n, start of Collatz sequence] [8] P F P F [n with maximum count] [Single constants] [10] P 400 F [where to store sequence] [11] P 2 F [to change addresses by 2] [12] @ F [carriage return] [13] & F [line feed] [14] K 4096 F [null char] [15] A D [used for maiking 'A addr D' order] [16] P 8 F [ used for adding 8 to address] [Single variables] [17] P F [maximum number of terms] [18] P F [temporary store] [19] P F [marks end of printing]   [Subroutine to print 4 numbers starting at address in 6F. Prints new line (CR, LF) at end.] [20] A 3 F [plant link for return] T 40 @ A 6 F [load start address] A 15 @ [make 'A addr D' order] A 16 @ [inc address by 8 (4 double values)] U 19 @ [store as test for end] S 16 @ [restore 'A addr D' order for start] [27] U 31 @ [plant 'A addr D' order in code] S 19 @ [test for end] E 38 @ [out if so] T F [clear acc] [31] A D [load number] T D [to 0D for printing] [33] A 33 @ [call print subroutine] G V A 31 @ [load 'A addr D' order] A 11 @ [inc address to next double value] G 27 @ [loop back] [38] O 12 @ [here when done, print CR LF] O 13 @ [40] E F [return]   [Enter with acc = 0] [PART 1] [41] A 2#@ [load demo value of n] T 4 D [to 4D for subroutine] A 10 @ [address to store sequence] T 6 F [to 6F for subroutine] [45] A 45 @ [call subroutine to generate sequence] G H A 7 F [load length of sequence] G 198 @ [out if error] T 18 @ [Print result] [50] A 50 @ [print 'start' message] G C K2048F SF TF AF RF TF !F !F #D A 2#@ [load demo value of n] T D [to 0D for printing] [63] A 63 @ [print demo n] G V [65] A 65 @ [print 'length' string] G C K2048F @F &F LF EF NF GF TF HF !F #D T D [ensure 1F and sandwich bit are 0] A 18 @ [load length] T F [to 0F (effectively 0D) for printing] [81] A 81 @ G V [83] A 83 @ [print 'first and last four' string] G C K2048F @F &F FF IF RF SF TF !F AF NF DF !F LF AF SF TF !F FF OF UF RF @F &F #D A 18 @ [load length of sequence] L 1 F [times 4] A 6 F [make address of last 4] S 16 @ T 18 @ [store address of last 4] [115] A 115 @ [print first 4 terms] G 20 @ A 18 @ [retrieve address of last 4] T 6 F [pass as parameter] [119] A 119 @ [print last 4 terms] G 20 @   [PART 2] T F T 17 @ [max count := 0] T 6#@ [n := 0] [Loop: update n, start new sequence] [124] T F [clear acc] A 6#@ [load n] A 4#@ [add 1 (double)] U 6#@ [update n] T 4 D [n to 4D for subroutine] T 6 F [say no store] [130] A 130 @ [call subroutine to generate sequence] G H A 7 F [load count returned by subroutine] G 198 @ [out if error] S 17 @ [compare with max count so far] G 140 @ [skip if less] A 17 @ [restore count after test] T 17 @ [update max count] A 6#@ [load n] T 8#@ [remember n that gave max count] [140] T F [clear acc] A 6#@ [load n just done] S #@ [compare with max(n)] G 124 @ [loop back if n < max(n) else fall through with acc = 0] [Here whan reached maximum n. Print result.] [144] A 144 @ [print 'max n' message] G C K2048F MF AF XF !F NF !F !F #D A #@ [load maximum n] T D [to 0D for printing] [157] A 157 @ [call print subroutine] G V [159] A 159 @ [print 'max len' message] G C K2048F @F &F MF AF XF !F LF EF NF #D T D [clear 1F and sandwich bit] A 17 @ [load max count (single)] T F [to 0F, effectively to 0D] [175] A 175 @ [call print subroutine] G V [177] A 177 @ [print 'at n =' message] G C K2048F @F &F AF TF !F NF !F #F VF !D A 8#@ [load n for which max count occurred] T D [to 0D for printing] [192] A 192 @ [call print subroutine] G V [194] O 12 @ [print CR, LF] O 13 @ O 14 @ [print null to flush teleprinter buffer] Z F [stop] [Here if term would overflow EDSAC 35-bit value. With a maximum n of 100,000 this doesn't happen.] [198] A 198 @ [print 'overflow' message] G C K2048F @F &F OF VF EF RF FF LF OF WD E 194 @ [jump to exit]   E 41 Z [define entry point] P F [acc = 0 on entry]  
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).
#Perl
Perl
use strict; use warnings; use List::Util 'min';   # If you want the large output, uncomment either the one line # marked (1) or the two lines marked (2) #use Math::GMP qw/:constant/; # (1) uncomment this to use Math::GMP #use Math::GMPz; # (2) uncomment this plus later line for Math::GMPz   sub ham_gen { my @s = ([1], [1], [1]); my @m = (2, 3, 5); #@m = map { Math::GMPz->new($_) } @m; # (2) uncomment for Math::GMPz   return sub { my $n = min($s[0][0], $s[1][0], $s[2][0]); for (0 .. 2) { shift @{$s[$_]} if $s[$_][0] == $n; push @{$s[$_]}, $n * $m[$_] } return $n } }   my $h = ham_gen; my $i = 0; ++$i, print $h->(), " " until $i > 20; print "...\n";   ++$i, $h->() until $i == 1690; print ++$i, "-th: ", $h->(), "\n";   # You will need to pick one of the bigint choices #++$i, $h->() until $i == 999999; #print ++$i, "-th: ", $h->(), "\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
#Red
Red
  Red [] #include %environment/console/CLI/input.red random/seed now print "I have thought of a number between 1 and 10. Try to guess it." number: random 10 while [(to integer! input) <> number][ print "Your guess was wrong. Try again." ] print "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.
#SQL
SQL
  /* This is a code implementation for finding one or more contiguous subsequences in a general sequence with the maximum sum of its elements. p_list -- List of elements of the general sequence of integers separated by a delimiter. p_delimiter -- proper delimiter */   WITH FUNCTION greatest_subsequential_sum(p_list IN varchar2, p_delimiter IN varchar2) RETURN varchar2 IS -- Variablen v_list varchar2(32767) := TRIM(BOTH p_delimiter FROM p_list); v_substr_i varchar2(32767); v_substr_j varchar2(32767); v_substr_out varchar2(32767); v_res INTEGER := 0; v_res_out INTEGER := 0; -- BEGIN -- v_list := regexp_replace(v_list,''||chr(92)||p_delimiter||'{2,}',p_delimiter); -- FOR i IN 1..nvl(regexp_count(v_list,'[^'||p_delimiter||']+'),0) loop v_substr_i := substr(v_list,regexp_instr(v_list,'[^'||p_delimiter||']+',1,i)); -- FOR j IN reverse 1..regexp_count(v_substr_i,'[^'||p_delimiter||']+') loop -- v_substr_j := TRIM(BOTH p_delimiter FROM substr(v_substr_i,1,regexp_instr(v_substr_i,'[^'||p_delimiter||']+',1,j,1))); EXECUTE immediate 'select sum('||REPLACE(v_substr_j,p_delimiter,'+')||') from dual' INTO v_res; -- IF v_res > v_res_out THEN v_res_out := v_res; v_substr_out := '{'||v_substr_j||'}'; elsif v_res = v_res_out THEN v_res_out := v_res; v_substr_out := v_substr_out||',{'||v_substr_j||'}'; END IF; -- END loop; -- END loop; -- v_substr_out := TRIM(BOTH ',' FROM nvl(v_substr_out,'{}')); v_substr_out := CASE WHEN regexp_count(v_substr_out,'},{')>0 THEN 'subsequences '||v_substr_out ELSE 'a subsequence '||v_substr_out END; RETURN 'The maximum sum '||v_res_out||' belongs to '||v_substr_out||' of the main sequence {'||p_list||'}'; END;   --Test SELECT greatest_subsequential_sum('-1|-2|-3|-4|-5|', '|') AS "greatest subsequential sum" FROM dual UNION ALL SELECT greatest_subsequential_sum('', '') FROM dual UNION ALL SELECT greatest_subsequential_sum(' ', ' ') FROM dual UNION ALL SELECT greatest_subsequential_sum(';;;;;;+1;;;;;;;;;;;;;2;+3;4;;;;-5;;;;', ';') FROM dual UNION ALL SELECT greatest_subsequential_sum('-1,-2,+3,,,,,,,,,,,,+5,+6,-2,-1,+4,-4,+2,-1', ',') FROM dual UNION ALL SELECT greatest_subsequential_sum(',+7,-6,-8,+5,-2,-6,+7,+4,+8,-9,-3,+2,+6,-4,-6,,', ',') FROM dual UNION ALL SELECT greatest_subsequential_sum('01 +2 3 +4 05 -8 -9 -20 40 25 -5', ' ') FROM dual UNION ALL SELECT greatest_subsequential_sum('1 2 3 0 0 -99 02 03 00001 -99 3 2 1 -99 3 1 2 0', ' ') FROM dual UNION ALL SELECT greatest_subsequential_sum('0,0,1,0', ',') FROM dual UNION ALL SELECT greatest_subsequential_sum('0,0,0', ',') FROM dual UNION ALL SELECT greatest_subsequential_sum('1,-1,+1', ',') FROM dual;    
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)
#Maple
Maple
GuessANumber := proc(low, high) local number, input; randomize(): printf( "Guess a number between %d and %d:\n:> ", low, high ); number := rand(low..high)(); do input := parse(readline()); if input > number then printf("Too high, try again!\n:> "); elif input < number then printf("Too low, try again!\n:> "); else printf("Well guessed! The answer was %d.\n", number); break; end if; end do: end proc:
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
#Mercury
Mercury
:- module happy. :- interface. :- import_module io.   :- pred main(io::di, io::uo) is det.   :- implementation. :- import_module int, list, set_tree234.   main(!IO) :- print_line(get_n_happy_numbers(8, 1), !IO).   :- func get_n_happy_numbers(int, int) = list(int).   get_n_happy_numbers(NumToFind, N) = ( if NumToFind > 0 then ( if is_happy(N, init) then [N | get_n_happy_numbers(NumToFind - 1, N + 1)] else get_n_happy_numbers(NumToFind, N + 1) ) else [] ).   :- pred is_happy(int::in, set_tree234(int)::in) is semidet.   is_happy(1, _). is_happy(N, !.Seen) :- not member(N, !.Seen), insert(N, !Seen), is_happy(sum_sqr_digits(N), !.Seen).   :- func sum_sqr_digits(int) = int.   sum_sqr_digits(N) = ( if N < 10 then sqr(N) else sqr(N mod 10) + sum_sqr_digits(N div 10) ).   :- func sqr(int) = int.   sqr(X) = X * 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
#J
J
'Hello world!' 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
#Scratch
Scratch
pos -100 70 print "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.
#Rust
Rust
fn gray_encode(integer: u64) -> u64 { (integer >> 1) ^ integer }   fn gray_decode(integer: u64) -> u64 { match integer { 0 => 0, _ => integer ^ gray_decode(integer >> 1) } }   fn main() { for i in 0..32 { println!("{:2} {:0>5b} {:0>5b} {:2}", i, i, gray_encode(i), gray_decode(i)); }   }
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
D
import std.algorithm: swap; // from Phobos standard library   // The D solution uses templates and it's similar to the C++ one: void mySwap(T)(ref T left, ref T right) { auto temp = left; left = right; right = temp; }   void main() { import std.stdio;   int[] a = [10, 20]; writeln(a);   // The std.algorithm standard library module // contains a generic swap: swap(a[0], a[1]); writeln(a);   // Using mySwap: mySwap(a[0], a[1]); writeln(a); }
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.
#Draco
Draco
/* Find the greatest element in an array of ints */ proc nonrec max([*] int a) int: int INT_MIN = ~((~0) >> 1); int nmax, i; nmax := INT_MIN; for i from 0 upto dim(a,1)-1 do if a[i] > nmax then nmax := a[i] fi od; nmax corp   /* Test on an array */ proc nonrec main() void: type arr = [8] int; writeln("Maximum: ", max(arr(1,5,17,2,53,99,61,3))) corp
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.
#Component_Pascal
Component Pascal
  MODULE Operations; IMPORT StdLog,Args,Strings;   PROCEDURE Gcd(a,b: LONGINT):LONGINT; VAR r: LONGINT; BEGIN LOOP r := a MOD b; IF r = 0 THEN RETURN b END; a := b;b := r END END Gcd;   PROCEDURE DoGcd*; VAR x,y,done: INTEGER; p: Args.Params; BEGIN Args.Get(p); IF p.argc >= 2 THEN Strings.StringToInt(p.args[0],x,done); Strings.StringToInt(p.args[1],y,done); StdLog.String("gcd("+p.args[0]+","+p.args[1]+")=");StdLog.Int(Gcd(x,y));StdLog.Ln END END DoGcd;   END Operations.  
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).
#Egel
Egel
  import "prelude.eg"   namespace Hailstone (   using System using List   def even = [ N -> (N%2) == 0 ]   def hailstone = [ 1 -> {1} | N -> if even N then cons N (hailstone (N/2)) else cons N (hailstone (N * 3 + 1)) ]   def hailpair = [ N -> (N, length (hailstone N)) ]   def hailmax = [ (N, NMAX), (M, MMAX) -> if (NMAX < MMAX) then (M, MMAX) else (N, NMAX) ]   def largest = [ 1 -> (1, 1) | N -> let M0 = hailpair N in let M1 = largest (N - 1) in hailmax M0 M1 ] )   using System using List using Hailstone   def task0 = let H27 = hailstone 27 in length H27   def task1 = let H27 = hailstone 27 in let L = length H27 in (take 4 H27, drop (L - 4) H27)   def task2 = largest 100000   def main = (task0, task1, task2)  
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).
#Phix
Phix
with javascript_semantics function hamming(integer N) sequence h = repeat(1,N) atom x2 = 2, x3 = 3, x5 = 5, hn integer i = 1, j = 1, k = 1 for n=2 to N do hn = min(x2,min(x3,x5)) h[n] = hn if hn==x2 then i += 1 x2 = 2*h[i] end if if hn==x3 then j += 1 x3 = 3*h[j] end if if hn==x5 then k += 1 x5 = 5*h[k] end if end for return h[N] end function include builtins\mpfr.e function mpz_hamming(integer N) sequence h = mpz_inits(N,1) mpz x2 = mpz_init(2), x3 = mpz_init(3), x5 = mpz_init(5), hn = mpz_init() integer i = 1, j = 1, k = 1 for n=2 to N do mpz_set(hn,mpz_min({x2,x3,x5})) mpz_set(h[n],hn) if mpz_cmp(hn,x2)=0 then i += 1 mpz_mul_si(x2,h[i],2) end if if mpz_cmp(hn,x3)=0 then j += 1 mpz_mul_si(x3,h[j],3) end if if mpz_cmp(hn,x5)=0 then k += 1 mpz_mul_si(x5,h[k],5) end if end for return h[N] end function sequence s = {} for i=1 to 20 do s = append(s,hamming(i)) end for ?s printf(1,"%d\n",hamming(1691)) printf(1,"%d (wrong!)\n",hamming(1000000)) --(the hn==x2 etc fail, so multiplies are all wrong) printf(1,"%s\n",{mpz_get_str(mpz_hamming(1691))}) printf(1,"%s\n",{mpz_get_str(mpz_hamming(1000000))})
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
#Retro
Retro
: checkGuess ( gn-gf || f ) over = [ drop 0 ] [ "Sorry, try again!\n" puts -1 ] if ;   : think ( -n ) random abs 10 mod 1+ ;   : guess ( - ) "I'm thinking of a number between 1 and 10.\n" puts "Try to guess it!\n" puts think [ getToken toNumber checkGuess ] while "You got it!\n" puts ;  
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
#REXX
REXX
#!/usr/bin/rexx /*REXX program to play: Guess the number */   number = random(1,10) say "I have thought of a number. Try to guess it!"   guess=0 /* We don't want a valid guess, before we start */   do while guess \= number pull guess if guess \= number then say "Sorry, the guess was wrong. Try again!" /* endif - There is no endif in rexx. */ end   say "Well done! You guessed it!"  
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.
#Standard_ML
Standard ML
val maxsubseq = let fun loop (_, _, maxsum, maxseq) [] = (maxsum, rev maxseq) | loop (sum, seq, maxsum, maxseq) (x::xs) = let val sum = sum + x val seq = x :: seq in if sum < 0 then loop (0, [], maxsum, maxseq) xs else if sum > maxsum then loop (sum, seq, sum, seq) xs else loop (sum, seq, maxsum, maxseq) xs end in loop (0, [], 0, []) end;   maxsubseq [~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.
#Swift
Swift
func maxSubseq(sequence: [Int]) -> (Int, Int, Int) { var maxSum = 0, thisSum = 0, i = 0 var start = 0, end = -1 for (j, seq) in sequence.enumerated() { thisSum += seq if thisSum < 0 { i = j + 1 thisSum = 0 } else if (thisSum > maxSum) { maxSum = thisSum start = i end = j } } return start <= end && start >= 0 && end >= 0  ? (start, end + 1, maxSum) : (0, 0, 0) }   let a = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1] let (start, end, maxSum) = maxSubseq(sequence: a) print("Max sum = \(maxSum)") print(a[start..<end])
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)
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
guessnumber[min_, max_] := Module[{number = RandomInteger[{min, max}], guess}, While[guess =!= number, guess = Input[ If[guess > number, "Too high.Guess again.", "Too low.Guess again.", "Guess a number between " <> ToString@min <> " and " <> ToString@max <> "."]]]; CreateDialog[{"Well guessed!", DefaultButton[]}]]; guessnumber[1, 10]
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
#MiniScript
MiniScript
isHappy = function(x) while true if x == 89 then return false sum = 0 while x > 0 sum = sum + (x % 10)^2 x = floor(x / 10) end while if sum == 1 then return true x = sum end while end function   found = [] i = 1 while found.len < 8 if isHappy(i) then found.push i i = i + 1 end while print "First 8 happy numbers: " + found
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
#Jack
Jack
class Main { function void main () { do Output.printString("Hello world!"); do Output.println(); return; } }