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/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 follow...
#Pascal
Pascal
sub bin2gray { return $_[0] ^ ($_[0] >> 1); }   sub gray2bin { my ($num)= @_; my $bin= $num; while( $num >>= 1 ) { # a bit ends up flipped iff an odd number of bits to its left is set. $bin ^= $num; # different from the suggested algorithm; } # avoids using bit ma...
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 t...
#Burlesque
Burlesque
  \/  
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.
#CoffeeScript
CoffeeScript
  # using Math library max1 = (list) -> Math.max.apply null, list   # using no libraries max2 = (list) -> maxVal = list[0] for value in list maxVal = value if value > maxVal maxVal       # Test it a = [0,1,2,5,4]; alert(max1(a)+". The answer is "+max2(a));  
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 tas...
#Befunge
Befunge
#v&< @.$< :<\g05%p05:_^#
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 conje...
#CoffeeScript
CoffeeScript
hailstone = (n) -> if n is 1 [n]   else if n % 2 is 0 [n].concat hailstone n/2   else [n].concat hailstone (3*n) + 1   h27 = hailstone 27 console.log "hailstone(27) = #{h27[0..3]} ... #{h27[-4..]} (length: #{h27.length})"   maxlength = 0 maxnums = []   for i in [1..100000] seq = hailstone i   if s...
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 ...
#Logo
Logo
to init.ham  ; queues make "twos [1] make "threes [1] make "fives [1] end to next.ham localmake "ham first :twos if less? first :threes :ham [make "ham first :threes] if less? first :fives  :ham [make "ham first :fives]   if equal? :ham first :twos [ignore dequeue "twos] if...
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,   a...
#Perl
Perl
my $number = 1 + int rand 10; do { print "Guess a number between 1 and 10: " } until <> == $number; print "You got it!\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,   a...
#Phix
Phix
-- -- demo\rosetta\Guess_the_number.exw -- with javascript_semantics include pGUI.e integer secret = rand(10) function valuechanged_cb(Ihandle guess) integer n = IupGetInt(guess,"VALUE") if n=secret then Ihandle lbl = IupGetBrother(guess,true) IupSetAttribute(lbl,"TITLE","Your guess was correc...
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 th...
#PL.2FI
PL/I
*process source attributes xref; ss: Proc Options(Main); /* REXX *************************************************************** * 26.08.2013 Walter Pachl translated from REXX version 3 **********************************************************************/ Dcl HBOUND builtin; Dcl SYSPRINT Print; Dcl (I,J,LB,...
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...
#Julia
Julia
function guesswithfeedback(n::Integer) number = rand(1:n) print("I choose a number between 1 and $n\nYour guess? ") while (guess = readline()) != dec(number) if all(isdigit, guess) print("Too ", parse(Int, guess) < number ? "small" : "big") else print("Enter an intege...
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 inclu...
#Liberty_BASIC
Liberty BASIC
ct = 0 n = 0 DO n = n + 1 IF HappyN(n, sqrInt$) = 1 THEN ct = ct + 1 PRINT ct, n END IF LOOP UNTIL ct = 8 END   FUNCTION HappyN(n, sqrInts$) n$ = Str$(n) sqrInts = 0 FOR i = 1 TO Len(n$) sqrInts = sqrInts + Val(Mid$(n$, i, 1)) ^ 2 N...
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#Vlang
Vlang
import math   fn haversine(h f64) f64 { return .5 * (1 - math.cos(h)) }   struct Pos { lat f64 // latitude, radians long f64 // longitude, radians }   fn deg_pos(lat f64, lon f64) Pos { return Pos{lat * math.pi / 180, lon * math.pi / 180} }   const r_earth = 6372.8 // km   fn hs_dist(p1 Pos, p2 Pos) f64...
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#Wren
Wren
var R = 6372.8 // Earth's approximate radius in kilometers.   /* Class containing trig methods which work with degrees rather than radians. */ class D { static deg2Rad(deg) { (deg*Num.pi/180 + 2*Num.pi) % (2*Num.pi) } static sin(d) { deg2Rad(d).sin } static cos(d) { deg2Rad(d).cos } }   var haversine = Fn...
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
#IDL
IDL
print,'Hello world!'
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#Whitespace
Whitespace
                   
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
#Python
Python
import bpy   # select default cube bpy.data.objects['Cube'].select_set(True)   # delete default cube bpy.ops.object.delete(True)   # add text to Blender scene bpy.data.curves.new(type="FONT", name="Font Curve").body = "Hello World" font_obj = bpy.data.objects.new(name="Font Object", object_data=bpy.data.curves["Font ...
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 follow...
#Perl
Perl
sub bin2gray { return $_[0] ^ ($_[0] >> 1); }   sub gray2bin { my ($num)= @_; my $bin= $num; while( $num >>= 1 ) { # a bit ends up flipped iff an odd number of bits to its left is set. $bin ^= $num; # different from the suggested algorithm; } # avoids using bit ma...
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 t...
#C
C
void swap(void *va, void *vb, size_t s) { char t, *a = (char*)va, *b = (char*)vb; while(s--) t = a[s], a[s] = b[s], b[s] = t; }
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#ColdFusion
ColdFusion
  <Cfset theList = '1, 1000, 250, 13'> <Cfparam name="maxNum" default=0> <Cfloop list="#theList#" index="i"> <Cfif i gt maxNum><Cfset maxNum = i></Cfif> </Cfloop> <Cfoutput>#maxNum#</Cfoutput>  
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 tas...
#BQN
BQN
Gcd ← {𝕨(|𝕊⍟(>⟜0)⊣)𝕩}
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 conje...
#Common_Lisp
Common Lisp
(defun hailstone (n) (cond ((= n 1) '(1)) ((evenp n) (cons n (hailstone (/ n 2)))) (t (cons n (hailstone (+ (* 3 n) 1))))))   (defun longest (n) (let ((k 0) (l 0)) (loop for i from 1 below n do (let ((len (length (hailstone i)))) (when (> len l) (setq l len k i))) finally (format t "Longest 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 ...
#Lua
Lua
function hiter() hammings = {1} prev, vals = {1, 1, 1} index = 1 local function nextv() local n, v = 1, hammings[prev[1]]*2 if hammings[prev[2]]*3 < v then n, v = 2, hammings[prev[2]]*3 end if hammings[prev[3]]*5 < v then n, v = 3, hammings[prev[3]]*5 end prev[n] = prev[n] + 1 if hammings[index] == v th...
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,   a...
#PHP
PHP
  <?php   session_start();   if(isset($_SESSION['number'])) { $number = $_SESSION['number']; } else { $_SESSION['number'] = rand(1,10); }     if(isset($_POST["guess"])){ if($_POST["guess"]){ $guess = htmlspecialchars($_POST['guess']);   echo $guess . "<br />"; if ($guess != $number) { ec...
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 th...
#Potion
Potion
gss = (lst) : # Find discrete integral integral = (0) accum = 0 lst each (n): accum = accum + n, integral append(accum). # Check integral[b + 1] - integral[a] for all 0 <= a <= b < N max = -1 max_a = 0 max_b = 0 lst length times (b) : b times (a) : if (integral(b + 1) - integra...
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 th...
#Prolog
Prolog
:- use_module(library(chr)).   :- chr_constraint init_chr/2, seq/2, % gss(Deb, Len, TT) gss/3, % gsscur(Deb, Len, TT, IdCur) gsscur/4, memoseq/3, clean/0, greatest_subsequence/0.     greatest_subsequence <=> L = [-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1], init_chr(1, L), find_chr_constraint(gss(Deb, ...
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...
#Kotlin
Kotlin
import kotlin.random.Random   fun main() { val n = 1 + rand.nextInt(20) println("Guess which number I've chosen in the range 1 to 20\n") while (true) { print(" Your guess : ") val guess = readLine()?.toInt() when (guess) { n -> { println("Correct, well guess...
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#Locomotive_Basic
Locomotive Basic
10 mode 1:defint a-z 20 for i=1 to 100 30 i2=i 40 for l=1 to 20 50 a$=str$(i2) 60 i2=0 70 for j=1 to len(a$) 80 d=val(mid$(a$,j,1)) 90 i2=i2+d*d 100 next j 110 if i2=1 then print i;"is a happy number":n=n+1:goto 150 120 if i2=4 then 150 ' cycle found 130 next l 140 ' check if we have reached 8 numbers yet 150 if n=8 th...
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#X86_Assembly
X86 Assembly
0000 .model tiny 0000 .code .486 org 100h ;.com files start here 0100 9B DB E3 start: finit ;initialize floating-point unit (FPU) ...
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
#Idris
Idris
module Main   main : IO () main = putStrLn "Hello world!"
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#Wren
Wren
var niven = Fiber.new { var n = 1 while (true) { var i = n var sum = 0 while (i > 0) { sum = sum + i%10 i = (i/10).floor } if (n%sum == 0) Fiber.yield(n) n = n + 1 } }   System.print("The first 20 Niven numbers are:") for (i in 1..20) { ...
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
#R
R
library(RGtk2) # bindings to Gtk w <- gtkWindowNew() l <- gtkLabelNew("Goodbye, World!") w$add(l)
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
#Racket
Racket
#lang racket/gui (require racket/gui/base)   ; Make a frame by instantiating the frame% class (define frame (new frame% [label "Goodbye, World!"]))   ; Make a static text message in the frame (define msg (new message% [parent frame] [label "No events so far..."]))   ; Make a button in the fra...
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 follow...
#Phix
Phix
with javascript_semantics function gray_encode(integer n) return xor_bits(n,floor(n/2)) end function function gray_decode(integer n) integer r = 0 while n>0 do r = xor_bits(r,n) n = floor(n/2) end while return r end function integer e,d puts(1," N Binary Gray Decoded\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 t...
#C.23
C#
static void Swap<T>(ref T a, ref T b) { T temp = a; a = b; 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.
#Common_Lisp
Common Lisp
(max 1 2 3 4) (reduce #'max values) ; find max of a list (loop for x in values maximize x) ; alternative way to find max of a list
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 tas...
#Bracmat
Bracmat
(gcd=a b.!arg:(?a.?b)&!b*den$(!a*!b^-1)^-1);
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 conje...
#Cowgol
Cowgol
include "cowgol.coh";   # Generate the hailstone sequence for the given N and return the length. # If a non-NULL pointer to a buffer is given, then store the sequence there. sub hailstone(n: uint32, buf: [uint32]): (len: uint32) is len := 0; loop if buf != 0 as [uint32] then [buf] := n; ...
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 ...
#M2000_Interpreter
M2000 Interpreter
  Module hamming_long { function hamming(l as long, &h(),&last()) { l=if(l<1->1&, l) long oldlen=len(h()) if oldlen<l then dim h(l) else =h(l-1): exit def long i, j, k, n, m, x2, x3, x5, ll stock last(0) out x2,x3,x5,i,j,k n=oldlen : ll=l-1 { m=x2 if m>x3 then m=x3 if m>x5 then m=x5 h(n)=m ...
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,   a...
#Picat
Picat
go => N = random(1,10), do print("Guess a number: ") while (read_int() != N), println("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,   a...
#PicoLisp
PicoLisp
(de guessTheNumber () (let Number (rand 1 9) (loop (prin "Guess the number: ") (T (= Number (read)) (prinl "Well guessed!") ) (prinl "Sorry, this was wrong") ) ) )
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 th...
#PureBasic
PureBasic
If OpenConsole() Define s$, a, b, p1, p2, sum, max, dm=(?EndOfMyData-?MyData) Dim Seq.i(dm/SizeOf(Integer)) CopyMemory(?MyData,@seq(),dm)   For a=0 To ArraySize(seq()) sum=0 For b=a To ArraySize(seq()) sum+seq(b) If sum>max max=sum p1=a p2=b EndIf Next Nex...
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...
#Lambdatalk
Lambdatalk
  {def game   {def game.rec // recursive part {lambda {:n :l :h} {let { {:n :n} {:l :l} {:h :h} // :n, :l, :h redefined {:g {round {/ {+ :l :h} 2}}}} // :g is the middle {if {< :g :n} then {br}:g too low! {game.rec :n {+ :g 1} :h}...
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 inclu...
#Logo
Logo
to sum_of_square_digits :number output (apply "sum (map [[d] d*d] ` :number)) end   to is_happy? :number [:seen []] output cond [ [ [:number = 1] "true ] [ [member? :number :seen] "false ] [ else (is_happy? (sum_of_square_digits :number) (lput :number :seen))] ] end   to n_happy :count [:start 1] [:r...
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   func real Haversine(Ang); real Ang; return (1.0-Cos(Ang)) / 2.0;   func real Dist(Lat1, Lat2, Lon1, Lon2); \Great circle distance real Lat1, Lat2, Lon1, Lon2; def R = 6372.8; \average radius of Earth (km) return 2.0*R * ASi...
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#XQuery
XQuery
declare namespace xsd = "http://www.w3.org/2001/XMLSchema"; declare namespace math = "http://www.w3.org/2005/xpath-functions/math";   declare function local:haversine($lat1 as xsd:float, $lon1 as xsd:float, $lat2 as xsd:float, $lon2 as xsd:float) as xsd:float { let $dlat  := ($lat2 - $lat1) * math:pi() div 180 ...
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
#Inform_6
Inform 6
[Main; print "Hello world!^"; ];
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations int H, C, N, S; \Harshad number, Counter, Number, Sum [H:= 1; C:= 0; loop [N:= H; S:= 0; \sum digits repeat N:= N/10; S:= S + rem(0); until N = 0; if rem(H/S) = 0 then \Harshad no.is...
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
#Raku
Raku
use GTK::Simple; use GTK::Simple::App;   my GTK::Simple::App $app .= new; $app.border-width = 20; $app.set-content( GTK::Simple::Label.new(text => "Goodbye, World!") ); $app.run;
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
#RapidQ
RapidQ
MessageBox("Goodbye, World!", "RapidQ example", 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 follow...
#PHP
PHP
  <?php   /** * @author Elad Yosifon */   /** * @param int $binary * @return int */ function gray_encode($binary){ return $binary ^ ($binary >> 1); }   /** * @param int $gray * @return int */ function gray_decode($gray){ $binary = $gray; while($gray >>= 1) $binary ^= $gray; return $binary; }   for($i=0;$i<3...
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 t...
#C.2B.2B
C++
template<typename T> void swap(T& left, T& right) { T tmp(left); left = right; right = tmp; }
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.
#Component_Pascal
Component Pascal
  MODULE Operations; IMPORT StdLog,Args,Strings;   PROCEDURE Max(s: ARRAY OF INTEGER): INTEGER; VAR i: INTEGER; max: INTEGER; BEGIN max := MIN(INTEGER); FOR i := 0 TO LEN(s) - 1 DO max := MAX(max,s[i]); END; RETURN max END Max;   PROCEDURE DoMax*; VAR sq: POINTER TO ARRAY OF INTEGER; p: Args.Params; i,n,don...
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 tas...
#C
C
int gcd_iter(int u, int v) { if (u < 0) u = -u; if (v < 0) v = -v; if (v) while ((u %= v) && (v %= u)); return (u + v); }
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 conje...
#Crystal
Crystal
  def hailstone(n) seq = [n] until n == 1 n = n.even? ? n // 2 : n * 3 + 1 seq << n end seq end   max_len = (1...100_000).max_by{|n| hailstone(n).size } max = hailstone(max_len) puts ([max_len, max.size, max.max, max.first(4), max.last(4)]) # => [77031, 351, 21933016, [77031, 231094, 115...
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 ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
HammingList[N_] := Module[{A, B, C}, {A, B, C} = (N^(1/3))*{2.8054745679851933, 1.7700573778298891, 1.2082521307023026} - {1, 1, 1}; Take[ Sort@Flatten@Table[ 2^x * 3^y * 5^z , {x, 0, A}, {y, 0, (-B/A)*x + B}, {z, 0, C - (C/A)*x - (C/B)*y}], 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,   a...
#Plain_English
Plain English
To run: Start up. Play guess the number. Wait for the escape key. Shut down.   To play guess the number: Pick a secret number between 1 and 10. Write "I picked a secret number between 1 and 10." to the console. Loop. Write "What is your guess? " to the console without advancing. Read a number from the console. If the 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,   a...
#Plain_TeX
Plain TeX
\newlinechar`\^^J \edef\tagetnumber{\number\numexpr1+\pdfuniformdeviate9}% \message{^^JI'm thinking of a number between 1 and 10, try to guess it!}% \newif\ifnotguessed \notguessedtrue \loop \message{^^J^^JYour try: }\read -1 to \useranswer \ifnum\useranswer=\tagetnumber\relax \message{You win!^^J}\notguessedfalse ...
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 th...
#Python
Python
def maxsubseq(seq): return max((seq[begin:end] for begin in xrange(len(seq)+1) for end in xrange(begin, len(seq)+1)), key=sum)
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 th...
#R
R
max.subseq <- function(x) { cumulative <- cumsum(x) min.cumulative.so.far <- Reduce(min, cumulative, accumulate=TRUE) end <- which.max(cumulative-min.cumulative.so.far) begin <- which.min(c(0, cumulative[1:end])) if (end >= begin) x[begin:end] else x[c()] }
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...
#Lasso
Lasso
#!/usr/bin/lasso9   local( lower = integer_random(10, 1), higher = integer_random(100, 20), number = integer_random(#higher, #lower), status = false, guess )   // prompt for a number stdout('Guess a number: ')   while(not #status) => { #guess = null   // the following bits wait until the terminal gives you back ...
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 inclu...
#LOLCODE
LOLCODE
OBTW Happy Numbers Rosetta Code task in LOLCODE Requires 1.3 for BUKKIT availability TLDR HAI 1.3 CAN HAS STDIO?   BTW Simple list implementation. BTW Used for the list of numbers already seen in IZHAPPY   BTW Create a list HOW IZ I MAEKLIST I HAS A LIST ITZ A BUKKIT LIST HAS A LENGTH ITZ 0 FOUND YR LIST ...
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#Yabasic
Yabasic
  //pi está predefinido en Yabasic deg2rad = pi / 180 // define grados a radianes 0.01745.. radioTierra = 6372.8 // radio de la tierra en km   sub Haversine(lat1, long1, lat2, long2 , radio) d_long = deg2rad * (long1 - long2) theta1 = deg2rad * lat1 theta2 = deg2rad * lat2 dx = cos(d_long) * cos(...
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#zkl
zkl
haversine(36.12, -86.67, 33.94, -118.40).println();   fcn haversine(Lat1, Long1, Lat2, Long2){ const R = 6372.8; // In kilometers; Diff_Lat  := (Lat2 - Lat1) .toRad(); Diff_Long := (Long2 - Long1).toRad(); NLat  := Lat1.toRad(); NLong  := Lat2.toRad(); A  := (Diff_Lat/2) .sin().pow(2) + ...
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
#Inko
Inko
import std::stdio::stdout   stdout.print('Hello, world!')
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#Yabasic
Yabasic
  sub sumDigits(n) if n < 0 then return 0 : endif local sum while n > 0 sum = sum + mod(n, 10) n = int(n / 10) wend return sum end sub   sub isHarshad(n) return mod(n, sumDigits(n)) = 0 end sub   print "Los primeros 20 numeros de Harshad o Niven son:" contar = 0 i = 1   repeat ...
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
#Rascal
Rascal
  import vis::Figure; import vis::Render;   public void GoodbyeWorld() = render(box(text("Goodbye World")));  
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#REALbasic
REALbasic
  MsgBox("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 follow...
#Picat
Picat
go => foreach(I in 0..2**5-1) G = gray_encode1(I), E = gray_decode1(G), printf("%2d %6w %2d %6w %6w %2d\n",I,I.to_binary_string, G, G.to_binary_string, E.to_binary_string, E) end, nl, println("Checking 2**13...
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 follow...
#PicoLisp
PicoLisp
(de grayEncode (N) (bin (x| N (>> 1 N))) )   (de grayDecode (G) (bin (pack (let X 0 (mapcar '((C) (setq X (x| X (format C)))) (chop G) ) ) ) ) )
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 t...
#Chapel
Chapel
a <=> b
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Crystal
Crystal
values.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 tas...
#C.23
C#
  static void Main() { Console.WriteLine("GCD of {0} and {1} is {2}", 1, 1, gcd(1, 1)); Console.WriteLine("GCD of {0} and {1} is {2}", 1, 10, gcd(1, 10)); Console.WriteLine("GCD of {0} and {1} is {2}", 10, 100, gcd(10, 100)); Console.WriteLine("GCD of {0} and {1} is {2}", 5, 50, gcd(5, 50)); Console.WriteLine("GCD...
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#D
D
import std.stdio, std.algorithm, std.range, std.typecons;   auto hailstone(uint n) pure nothrow { auto result = [n]; while (n != 1) { n = (n & 1) ? (n * 3 + 1) : (n / 2); result ~= n; } return result; }   void main() { enum M = 27; immutable h = M.hailstone; writeln("hailstone(", M, ")= ", h[0 .. ...
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 ...
#MATLAB_.2F_Octave
MATLAB / Octave
n = 40;   powers_2 = 2.^[0:n-1]; powers_3 = 3.^[0:n-1]; powers_5 = 5.^[0:n-1];   matrix = powers_2' * powers_3; powers_23 = sort(reshape(matrix,n*n,1));     matrix = powers_23 * powers_5; powers_235 = sort(reshape(matrix,n*n*n,1));   % % Remove the integer overflow values. % powers_235 = powers_235(powers_235 > 0);   d...
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,   a...
#PowerShell
PowerShell
Function GuessNumber($Guess) { $Number = Get-Random -min 1 -max 11 Write-Host "What number between 1 and 10 am I thinking of?" Do { Write-Warning "Try again!" $Guess = Read-Host "What's the number?" } While ($Number -ne $Guess) Write-Host "Well done! You succe...
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,   a...
#ProDOS
ProDOS
:a editvar /modify /value=-random-= <10 editvar /newvar /value=-random- /title=a editvar /newvar /value=b /userinput=1 /title=Guess a number: if -b- /hasvalue=-a- printline You guessed correctly! else printline Your guess was wrong & goto :a
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 th...
#Racket
Racket
  (define (max-subseq l) (define-values (_ result _1 max-sum) (for/fold ([seq '()] [max-seq '()] [sum 0] [max-sum 0]) ([i l]) (cond [(> (+ sum i) max-sum) (values (cons i seq) (cons i seq) (+ sum i) (+ sum i))] [(< (+ sum i) 0) (values '() max-seq 0 max-sum)] ...
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 th...
#Raku
Raku
sub max-subseq (*@a) { my ($start, $end, $sum, $maxsum) = -1, -1, 0, 0; for @a.kv -> $i, $x { $sum += $x; if $maxsum < $sum { ($maxsum, $end) = $sum, $i; } elsif $sum < 0 { ($sum, $start) = 0, $i; } } return @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...
#LFE
LFE
  (defmodule guessing-game (export (main 0)))   (defun get-player-guess () (let (((tuple 'ok (list guessed)) (: io fread '"Guess number: " '"~d"))) guessed))   (defun check-guess (answer guessed) (cond ((== answer guessed) (: io format '"Well-guessed!!~n")) ((/= answer guessed) (...
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 inclu...
#Lua
Lua
function digits(n) if n > 0 then return n % 10, digits(math.floor(n/10)) end end function sumsq(a, ...) return a and a ^ 2 + sumsq(...) or 0 end local happy = setmetatable({true, false, false, false}, { __index = function(self, n) self[n] = self[sumsq(digits(n))] return self[n] end } )...
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET diam=2*6372.8 20 LET Lg1m2=FN r((-86.67)-(-118.4)) 30 LET Lt1=FN r(36.12) 40 LET Lt2=FN r(33.94) 50 LET dz=SIN (Lt1)-SIN (Lt2) 60 LET dx=COS (Lg1m2)*COS (Lt1)-COS (Lt2) 70 LET dy=SIN (Lg1m2)*COS (Lt1) 80 LET hDist=ASN ((dx*dx+dy*dy+dz*dz)^0.5/2)*diam 90 PRINT "Haversine distance: ";hDist;" km." 100 STOP 1000 DE...
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
#Intercal
Intercal
DO ,1 <- #13 PLEASE DO ,1 SUB #1 <- #238 DO ,1 SUB #2 <- #108 DO ,1 SUB #3 <- #112 DO ,1 SUB #4 <- #0 DO ,1 SUB #5 <- #64 DO ,1 SUB #6 <- #194 PLEASE DO ,1 SUB #7 <- #48 DO ,1 SUB #8 <- #26 DO ,1 SUB #9 <- #244 PLEASE DO ,1 SUB #10 <- #168 DO ,1 SUB #11 <- #24 DO ,1 SUB #12 <- #16 DO ,1 SUB #13 <- #162 PLEASE READ OUT ...
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#zkl
zkl
fcn harshad(n){ 0==n%(n.split().sum(0)) } [1..].tweak(fcn(n){ if(not harshad(n)) return(Void.Skip); n }) .walk(20).println(); [1..].filter(20,harshad).println(); [1001..].filter1(harshad).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
#REBOL
REBOL
alert "Goodbye, World!"
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Red
Red
>> view [ text "Hello 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 follow...
#PL.2FI
PL/I
(stringrange, stringsize): Gray_code: procedure options (main); /* 15 November 2013 */ declare (bin(0:31), g(0:31), b2(0:31)) bit (5); declare (c, carry) bit (1); declare (i, j) fixed binary (7);   bin(0) = '00000'b; do i = 0 to 31; if i > 0 then do; carry = '1'b; ...
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The follow...
#PowerBASIC
PowerBASIC
function gray%(byval n%) gray%=n% xor (n%\2) end function   function igray%(byval n%) r%=0 while n%>0 r%=r% xor n% shift right n%,1 wend igray%=r% end function   print " N GRAY INV" for n%=0 to 31 g%=gray%(n%) print bin$(n%);" ";bin$(g%);" ";bin$(igray%(g%)) next
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#Clojure
Clojure
  (defn swap [pair] (reverse pair)) ; returns a list (defn swap [[a b]] '(b a)) ; returns a list (defn swap [[a b]] [b a]) ; returns a vector  
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
D
void main() { import std.algorithm.searching : maxElement; import std.stdio : writeln;   [9, 4, 3, 8, 5].maxElement.writeln; }
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 tas...
#C.2B.2B
C++
#include <iostream> #include <numeric>   int main() { std::cout << "The greatest common divisor of 12 and 18 is " << std::gcd(12, 18) << " !\n"; }
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 conje...
#Dart
Dart
List<int> hailstone(int n) { if(n<=0) { throw new IllegalArgumentException("start value must be >=1)"); } Queue<int> seq=new Queue<int>(); seq.add(n); while(n!=1) { n=n%2==0?(n/2).toInt():3*n+1; seq.add(n); } return new List<int>.from(seq); }   // apparently List is missing toString() String 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 ...
#MUMPS
MUMPS
Hamming(n) New count,ok,next,number,which For which=2,3,5 Set number=1 For count=1:1:n Do . Set ok=0 Set:count<21 ok=1 Set:count=1691 ok=1 Set:count=n ok=1 . Write:ok !,$Justify(count,5),": ",number . For which=2,3,5 Set next(number*which)=which . Set number=$Order(next("")) . Kill next(number) . Quit Quit Do ...
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,   a...
#Prolog
Prolog
main :- random_between(1, 10, N), repeat, prompt1('Guess the number: '), read(N), writeln('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,   a...
#PureBasic
PureBasic
If OpenConsole() Define TheNumber=Random(9)+1   PrintN("I've picked a number from 1 to 10." + #CRLF$) Repeat Print("Guess the number: ") Until TheNumber=Val(Input())   PrintN("Well guessed!")   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole() EndIf
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 th...
#Raven
Raven
[ -1 -2 3 5 6 -2 -1 4 -4 2 -1 ] as $seq   1 31 shl as $max   0 $seq length 1 range each as $i 0 as $sum $i $seq length 1 range each as $j $seq $j get $sum + as $sum $sum $max > if $sum as $max $i as $i1 $j as $j1   "Sum: " print $i1 $j1 1 range each ...
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 th...
#REXX
REXX
/*REXX program finds and displays the longest greatest continuous subsequence sum. */ parse arg @; w= words(@); p= w + 1 /*get arg list; number words in list. */ say 'words='w " list="@ /*show number words & LIST to terminal,*/ do #=1 for w; @.#= word(@, #); 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...
#Liberty_BASIC
Liberty BASIC
  [start] target = int( rnd( 1) * 100) +1   while 1 do input "Guess a whole number between 1 and 100. To finish, type 'exit' "; b$ if b$ ="exit" then print "Thank you for playing!": end c = val( b$) ok =( c =int( c)) and ( c >=1) and ( c <=100) if ok =0 then notice "Inval...
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 inclu...
#M2000_Interpreter
M2000 Interpreter
  Function FactoryHappy { sumOfSquares= lambda (n) ->{ k$=str$(abs(n),"") Sum=0 For i=1 to len(k$) sum+=val(mid$(k$,i,1))**2 Next i =sum } IsHappy=Lambda sumOfSquares (n) ->{ I...
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Integer_BASIC
Integer BASIC
10 PRINT "Hello world!" 20 END
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET k=0: LET n=0 20 IF k=20 THEN GO TO 60 30 LET n=n+1: GO SUB 1000 40 IF isHarshad THEN PRINT n;" ";: LET k=k+1 50 GO TO 20 60 LET n=1001 70 GO SUB 1000: IF NOT isHarshad THEN LET n=n+1: GO TO 70 80 PRINT '"First Harshad number larger than 1000 is ";n 90 STOP 1000 REM is Harshad? 1010 LET s=0: LET n$=STR$ n 1020 F...