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/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
#HQ9.2B
HQ9+
H
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/...
#Tcl
Tcl
# Determine if the given number is a member of the class of Harshad numbers proc isHarshad {n} { if {$n < 1} {return false} set sum [tcl::mathop::+ {*}[split $n ""]] return [expr {$n%$sum == 0}] }   # Get the first 20 numbers that satisfy the condition for {set n 1; set harshads {}} {[llength $harshads] < 2...
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
#PHP
PHP
if (!class_exists('gtk')) { die("Please load the php-gtk2 module in your php.ini\r\n"); }   $wnd = new GtkWindow(); $wnd->set_title('Goodbye world'); $wnd->connect_simple('destroy', array('gtk', 'main_quit'));   $lblHello = new GtkLabel("Goodbye, World!"); $wnd->add($lblHello);   $wnd->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 follow...
#Logo
Logo
to gray_encode :number output bitxor :number lshift :number -1 end   to gray_decode :code local "value make "value 0 while [:code > 0] [ make "value bitxor :code :value make "code lshift :code -1 ] output :value end
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The follow...
#Lua
Lua
local _M = {}   local bit = require('bit') local math = require('math')   _M.encode = function(number) return bit.bxor(number, bit.rshift(number, 1)); end   _M.decode = function(gray_code) local value = 0 while gray_code > 0 do gray_code, value = bit.rshift(gray_code, 1), bit.bxor(gray_code, value) end r...
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...
#BASIC256
BASIC256
global a, b a = "one" b = "two"   print a, b call swap(a, b) print a, b end   subroutine swap(a, b) temp = a : a = b : b = temp end subroutine
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.
#CFEngine
CFEngine
  bundle agent __main__ { vars: "number_of_list_elements" int => randomint( "0", 100 ), unless => isvariable( "$(this.promiser)" );   "idx" slist => expandrange( "[0-$(number_of_list_elements)]", 1 ), unless => isvariable( "$(this.promiser)" );   "number[$(idx)]" ...
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...
#BASIC256
BASIC256
  function gcdI(x, y) while y t = y y = x mod y x = t end while   return x end function   # ------ test ------ a = 111111111111111 b = 11111   print : print "GCD(";a;", ";b;") = "; gcdI(a, b) print : print "GCD(";a;", 111) = "; gcdI(a, 111) end
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT files="a.txt'b.txt'c.txt"   BUILD S_TABLE search = ":Goodbye London!:"   LOOP file=files ERROR/STOP OPEN (file,WRITE,-std-) ERROR/STOP CREATE ("scratch",FDF-o,-std-) ACCESS q: READ/STREAM/RECORDS/UTF8 $file s,aken+text/search+eken ACCESS s: WRITE/ERASE/STREAM/UTF8 "scratch" s,aken+text+eken ...
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#TXR
TXR
@(next :args) @(repeat) @file @(next `@file`) @(freeform) @(coll :gap 0)@notmatch@{match /Goodbye, London!/}@(end)@*tail@/\n/ @(output `@file.tmp`) @(rep)@{notmatch}Hello, New York!@(end)@tail @(end) @(do @(rename-path `@file.tmp` file)) @(end)
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#UNIX_Shell
UNIX Shell
replace() { local search=$1 replace=$2 local file lines line shift 2 for file in "$@"; do lines=() while IFS= read -r line; do lines+=( "${line//$search/$replace}" ) done < "$file" printf "%s\n" "${lines[@]}" > "$file" done } replace "Goodbye London!" "Hel...
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...
#Ceylon
Ceylon
shared void run() {   {Integer*} hailstone(variable Integer n) { variable [Integer*] stones = [n]; while(n != 1) { n = if(n.even) then n / 2 else 3 * n + 1; stones = stones.append([n]); } return stones; }   value hs27 = hailstone(27); print("hailstone sequence for 27 is ``hs27.take(3)``...``hs27.skip(...
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 ...
#JavaScript
JavaScript
function hamming() { var queues = {2: [], 3: [], 5: []}; var base; var next_ham = 1; while (true) { yield next_ham;   for (base in queues) {queues[base].push(next_ham * base)}   next_ham = [ queue[0] for each (queue in queues) ].reduce(function(min, val) { return Math...
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...
#Nim
Nim
import strutils, random   randomize() var chosen = rand(1..10) echo "I have thought of a number. Try to guess it!"   var guess = parseInt(readLine(stdin))   while guess != chosen: echo "Your guess was wrong. Try again!" guess = parseInt(readLine(stdin))   echo "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...
#NS-HUBASIC
NS-HUBASIC
10 NUMBER=RND(10)+1 20 INPUT "I'M THINKING OF A NUMBER BETWEEN 1 AND 10. WHAT IS IT? ",GUESS 30 IF GUESS<>NUMBER THEN PRINT "INCORRECT GUESS. TRY AGAIN.": GOTO 20 40 PRINT "CORRECT NUMBER."
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...
#Pascal
Pascal
Program GreatestSubsequentialSum(output);   var a: array[1..11] of integer = (-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1); i, j: integer; seqStart, seqEnd: integer; maxSum, seqSum: integer;   begin maxSum := 0; seqStart := 0; seqEnd := -1; for i := low(a) to high(a) do begin seqSum := 0; for j ...
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...
#HolyC
HolyC
U8 n, *g; U8 min = 1, max = 100;   n = min + RandU16 % max;   Print("Guess the number between %d and %d: ", min, max);   while(1) { g = GetStr;   if (Str2I64(g) == n) { Print("You guessed correctly!\n"); break; }   if (Str2I64(g) < n) Print("Your guess was too low.\nTry again: "); if (Str2I64(g) >...
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...
#jq
jq
def is_happy_number: def next: tostring | explode | map( (. - 48) | .*.) | add; def last(g): reduce g as $i (null; $i); # state: either 1 or [i, o] # where o is an an object with the previously encountered numbers as keys def loop: recurse( if . == 1 then empty # all done elif .[0] == ...
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...
#TechBASIC
TechBASIC
  {{trans|BASIC}} FUNCTION HAVERSINE !--------------------------------------------------------------- !*** Haversine Formula - Calculate distances by LAT/LONG !   !*** LAT/LON of the two locations and Unit of measure are GLOBAL !*** as they are defined in the main logic of the program, so they !*** available for use in...
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...
#Teradata_Stored_Procedure
Teradata Stored Procedure
  # syntax: CALL SP_HAVERSINE(36.12,33.94,-86.67,-118.40,x);   CREATE PROCEDURE SP_HAVERSINE ( IN lat1 FLOAT, IN lat2 FLOAT, IN lon1 FLOAT, IN lon2 FLOAT, OUT distance FLOAT)   BEGIN DECLARE dLat FLOAT; DECLARE dLon FLOAT; DECLARE c FLOAT; DECLARE a FLOAT; DECLARE km FLOAT;   SET dLat = RAD...
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
#Huginn
Huginn
#! /bin/sh exec huginn --no-argv -E "${0}" "${@}" #! huginn   main() { print( "Hello World!\n" ); return ( 0 ); }
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/...
#uBasic.2F4tH
uBasic/4tH
C=0   For I = 1 Step 1 Until C = 20 ' First 20 Harshad numbers If FUNC(_FNHarshad(I)) Then Print I;" "; : C = C + 1 Next   For I = 1001 Step 1 ' First Harshad greater than 1000 If FUNC(_FNHarshad(I)) Then Print I;" " : Break Next   End   _FNHarshad Param(1) Local(2)   c@ = a@ b@ = ...
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
#PicoLisp
PicoLisp
(call 'dialog "--msgbox" "Goodbye, World!" 5 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
#Plain_English
Plain English
To run: Start up. Clear the screen. Write "Goodbye, World!". Refresh the screen. Wait for the escape key. Shut down.
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...
#M2000_Interpreter
M2000 Interpreter
  Module Code32 (&code(), &decode()){ Const d$="{0::-2} {1:-6} {2:-6} {3:-6} {4::-2}" For i=0 to 32 g=code(i) b=decode(g) Print format$(d$, i, @bin$(i), @bin$(g), @bin$(b), b) Next // static function Function bin$(a) a$="" Do n= ...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
graycode[n_]:=BitXor[n,BitShiftRight[n]] graydecode[n_]:=Fold[BitXor,0,FixedPointList[BitShiftRight,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...
#BBC_BASIC
BBC BASIC
a = 1.23 : b = 4.56 SWAP a,b PRINT a,b   a$ = "Hello " : b$ = "world!" SWAP a$,b$ PRINT 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.
#Clojure
Clojure
(max 1 2 3 4) ; evaluates to 4 ;; If the values are already in a collection, use apply: (apply max [1 2 3 4]) ; evaluates to 4
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...
#Batch_File
Batch File
:: gcd.cmd @echo off :gcd if "%2" equ "" goto :instructions if "%1" equ "" goto :instructions   if %2 equ 0 ( set final=%1 goto :done ) set /a res = %1 %% %2 call :gcd %2 %res% goto :eof   :done echo gcd=%final% goto :eof   :instructions echo Syntax: echo GCD {a} {b} echo.
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#VBScript
VBScript
  Const ForReading = 1 Const ForWriting = 2   strFiles = Array("test1.txt", "test2.txt", "test3.txt")   With CreateObject("Scripting.FileSystemObject") For i = 0 To UBound(strFiles) strText = .OpenTextFile(strFiles(i), ForReading).ReadAll() With .OpenTextFile(strFiles(i), ForWriting) .Write Replace(strText, "Go...
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#Vedit_macro_language
Vedit macro language
File_Open("files.lst") // list of files to process #20 = Reg_Free // text register for filename   While(!At_EOF) { Reg_Copy_Block(#20, Cur_Pos, EOL_Pos) File_Open(@(#20)) Replace("Goodbye London!", "Hello New York!", BEGIN+ALL+NOERR) Buf_Close(NOMSG) Line(1, ERRBREAK) }   R...
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#Wren
Wren
import "io" for File   var files = ["file1.txt", "file2.txt"] for (file in files) { var text = File.read(file) System.print("%(file) contains: %(text)") text = text.replace("Goodbye London!", "Hello New York!") File.create(file) { |f| // overwrites existing file f.writeBytes(text) } Sys...
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...
#CLIPS
CLIPS
(deftemplate longest (slot bound)  ; upper bound for the range of values to check (slot next (default 2))  ; next value that needs to be checked (slot start (default 1)) ; starting value of longest sequence (slot len (default 1))  ; length of longest sequence )   (deffacts startup (query 27) (lo...
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 ...
#jq
jq
# Return the index in the input array of the min_by(f) value def index_min_by(f): . as $in | if length == 0 then null else .[0] as $first | reduce range(0; length) as $i ([0, $first, ($first|f)]; # state: [ix; min; f|min] ($in[$i]|f) as $v | if $v < .[2] then [ $i, $in[$i], $v ]...
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...
#Oberon-2
Oberon-2
  MODULE GuessTheNumber; IMPORT RandomNumbers, In, Out;   PROCEDURE Do; VAR n,guess: LONGINT; BEGIN n := RandomNumbers.RND(10); Out.String("Guess a number between 1 and 10: ");Out.Flush(); LOOP In.LongInt(guess); IF guess = n THEN Out.String("You guessed!!"); Out.Ln;...
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...
#Objeck
Objeck
  use IO;   bundle Default { class GuessNumber { function : Main(args : String[]) ~ Nil { done := false; "Guess the number which is between 1 and 10 or 'q' to quite: "->PrintLine(); rand_num := (Float->Random() * 10.0)->As(Int) + 1; while(done = false) { guess := Console->ReadStrin...
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...
#Perl
Perl
use strict;   sub max_sub(\@) { my ($a, $maxs, $maxe, $s, $sum, $maxsum) = shift; foreach (0 .. $#$a) { my $t = $sum + $a->[$_]; ($s, $sum) = $t > 0 ? ($s, $t) : ($_ + 1, 0);   if ($maxsum < $sum) { $maxsum = $sum; ($maxs, $maxe) = ($s, $_ + 1) } } @$a[$maxs .. $maxe - 1] }   my @a = map { int(rand(20...
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...
#Icon_and_Unicon
Icon and Unicon
  procedure main() smallest := 5 highest := 25 n := smallest-1 + ?(1+highest-smallest) repeat { writes("Pick a number from ", smallest, " through ", highest, ": ") guess := read ()   if n = numeric(guess) then { write ("Well guessed!") exit () } ...
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...
#Julia
Julia
  function happy(x) happy_ints = ref(Int) int_try = 1 while length(happy_ints) < x n = int_try past = ref(Int) while n != 1 n = sum([y^2 for y in digits(n)]) contains(past,n) ? break : push!(past,n) end n == 1 && push!(happy_ints,int_try) int_try += 1 end return happy_ints 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...
#Transact-SQL
Transact-SQL
CREATE FUNCTION [dbo].[Haversine](@Lat1 AS DECIMAL(9,7), @Lon1 AS DECIMAL(10,7), @Lat2 AS DECIMAL(9,7), @Lon2 AS DECIMAL(10,7)) RETURNS DECIMAL(12,7) AS BEGIN DECLARE @R DECIMAL(11,7); DECLARE @dLat DECIMAL(9,7); DECLARE @dLon DECIMAL(10,7); DECLARE @a DECIMAL(10,7); DECLARE @c DECIMAL(10,7);   SET @R = 6372.8; ...
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
#HTML5
HTML5
  <!DOCTYPE html> <html> <body> <h1>Hello world!</h1> </body> </html>  
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/...
#VBA
VBA
Option Explicit   Sub Main() Dim i As Long, out As String, Count As Integer Do i = i + 1 If IsHarshad(i) Then out = out & i & ", ": Count = Count + 1 Loop While Count < 20 Debug.Print "First twenty Harshad numbers are : " & vbCrLf & out & "..."   i = 1000 Do i = i + 1 Loop While Not ...
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
#Portugol
Portugol
  programa { // includes graphics library and use an alias inclua biblioteca Graficos --> g   // define WIDTH and HEIGHT integer constants const inteiro WIDTH = 200 const inteiro HEIGHT = 100   // main entry funcao inicio() { // begin graphical mode (verdadeiro = true) g.inic...
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
#PostScript
PostScript
%!PS % render in Helvetica, 12pt: /Helvetica findfont 12 scalefont setfont % somewhere in the lower left-hand corner: 50 dup moveto % render text (Goodbye, World!) show % wrap up page display: showpage
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...
#MATLAB
MATLAB
  %% Gray Code Generator % this script generates gray codes of n bits % total 2^n -1 continuous gray codes will be generated. % this code follows a recursive approach. therefore, % it can be slow for large n       clear all; clc;   bits = input('Enter the number of bits: '); if (bits<1) disp('Sorry, number of bits...
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...
#Beads
Beads
beads 1 program 'Generic swap'   var a = [1 2 "Beads" 3 4] b = [1 2 "Language" 4 5]   calc main_init swap a[4] <=> b[3]
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.
#CLU
CLU
% This "maximum" procedure is fully general, as long as % the container type has an elements iterator and the % data type is comparable. % It raises an exception ("empty") if there are no elements.   maximum = proc [T,U: type] (a: T) returns (U) signals (empty) where T has elements: itertype (T) y...
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...
#BBC_BASIC
BBC BASIC
DEF FN_GCD_Iterative_Euclid(A%, B%) LOCAL C% WHILE B% C% = A% A% = B% B% = C% MOD B% ENDWHILE = ABS(A%)
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations string 0; \use zero-terminated strings   func StrLen(A); \Return number of characters in an ASCIIZ string char A; int I; for I:= 0 to -1>>1-1 do if A(I) = 0 then return I;   func StrFind(A, B); \Search ...
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#zkl
zkl
fcn sed(data,src,dst){ srcSz:=src.len(); dstSz:=dst.len(); md5:=Utils.MD5.calc(data); n:=0; while(Void!=(n:=data.find(src,n))) { data.del(n,srcSz); data.insert(n,dst); n+= dstSz; } return(md5!=Utils.MD5.calc(data)); // changed? } fcn sedFile(fname,src,dst){ f:=File(fname,"r"); data:=f.read(); f.c...
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...
#Clojure
Clojure
(defn hailstone-seq [n] {:pre [(pos? n)]} (lazy-seq (cond (= n 1) '(1) (even? n) (cons n (hailstone-seq (/ n 2)))  :else (cons n (hailstone-seq (+ (* n 3) 1))))))   (let [hseq (hailstone-seq 27)] (-> hseq count (= 112) assert) (->> hseq (take 4) (= [27 82 41 124]) a...
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 ...
#Julia
Julia
function hammingsequence(N) if N < 1 throw("Hamming sequence exponent must be a positive integer") end ham = N > 4000 ? Vector{BigInt}([1]) : Vector{Int}([1]) base2, base3, base5 = (1, 1, 1) for i in 1:N-1 x = min(2ham[base2], 3ham[base3], 5ham[base5]) push!(ham, x) i...
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...
#Objective-C
Objective-C
  #import <Foundation/Foundation.h>   int main(int argc, const char * argv[]) {   @autoreleasepool {   NSLog(@"I'm thinking of a number between 1 - 10. Can you guess what it is?\n");   int rndNumber = arc4random_uniform(10) + 1;   // Debug (Show rndNumber in console) //NSLog(@"Random...
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...
#OCaml
OCaml
#!/usr/bin/env ocaml   let () = Random.self_init(); let n = if Random.bool () then let n = 2 + Random.int 8 in print_endline "Please guess a number between 1 and 10 excluded"; (n) else let n = 1 + Random.int 10 in print_endline "Please guess a number between 1 and 10 included";...
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...
#Phix
Phix
with javascript_semantics function maxSubseq(sequence s) integer maxsum = 0, first = 1, last = 0 for i=1 to length(s) do integer sumsij = 0 for j=i to length(s) do sumsij += s[j] if sumsij>maxsum then {maxsum,first,last} = {sumsij,i,j} end if ...
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...
#J
J
require 'misc' game=: verb define assert. y -: 1 >. <.{.y n=: 1 + ?y smoutput 'Guess my integer, which is bounded by 1 and ',":y whilst. -. x -: n do. x=. {. 0 ". prompt 'Guess: ' if. 0 -: x do. 'Giving up.' return. end. smoutput (*x-n){::'You win.';'Too high.';'Too low.' end. )
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...
#K
K
hpy: {x@&1={~|/x=1 4}{_+/_sqr 0$'$x}//:x}   hpy 1+!100 1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100   8#hpy 1+!100 1 7 10 13 19 23 28 31
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...
#True_BASIC
True BASIC
  DEF Haversine (lat1, long1, lat2, long2) OPTION ANGLE RADIANS LET R = 6372.8  !radio terrestre en km. LET dLat = RAD(lat2-lat1) LET dLong = RAD(long2-long1) LET lat1 = RAD(lat1) LET lat2 = RAD(lat2) LET Haversine = R *2 * ASIN(SQR(SIN(dLat/2)^2 + SIN(dLong/2)^2 *COS(lat1) * C...
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...
#TypeScript
TypeScript
  let radians = function (degree: number) {   // degrees to radians let rad: number = degree * Math.PI / 180;   return rad; }   export const haversine = (lat1: number, lon1: number, lat2: number, lon2: number) => {   // var dlat: number, dlon: number, a: number, c: number, R: number; let dlat, dlon,...
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
#Hy
Hy
(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/...
#VBScript
VBScript
n = 0 m = 1 first20 = "" after1k = ""   Do If IsHarshad(m) And n <= 20 Then first20 = first20 & m & ", " n = n + 1 m = m + 1 ElseIf IsHarshad(m) And m > 1000 Then after1k = m Exit Do Else m = m + 1 End If Loop   WScript.StdOut.Write "First twenty Harshad numbers are: " WScript.StdOut.WriteLine WScript.S...
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
#PowerBASIC
PowerBASIC
FUNCTION PBMAIN() AS LONG MSGBOX "Goodbye, World!" END FUNCTION
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
#PowerShell
PowerShell
New-Label "Goodbye, World!" -FontSize 24 -Show
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...
#Mercury
Mercury
:- module gray.   :- interface. :- import_module int.   :- type gray.   % VALUE conversion functions :- func gray.from_int(int) = gray. :- func gray.to_int(gray) = int.   % REPRESENTATION conversion predicate :- pred gray.coerce(gray, int). :- mode gray.coerce(in, out) is det. :- mode gray.coerce(out, in) is det.  ...
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...
#Nim
Nim
proc grayEncode(n: int): int = n xor (n shr 1)   proc grayDecode(n: int): int = result = n var t = n while t > 0: t = t shr 1 result = result xor t
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...
#BQN
BQN
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.
#CMake
CMake
# max(var [value1 value2...]) sets var to the maximum of a list of # integers. If list is empty, sets var to NO. function(max var) set(first YES) set(choice NO) foreach(item ${ARGN}) if(first) set(choice ${item}) set(first NO) elseif(choice LESS ${item}) set(choice ${item}) endif() ...
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...
#Bc
Bc
define even(a) { if ( a % 2 == 0 ) { return(1); } else { return(0); } }   define abs(a) { if (a<0) { return(-a); } else { return(a); } }
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...
#CLU
CLU
% Generate the hailstone sequence for a number hailstone = iter (n: int) yields (int) while true do yield(n) if n=1 then break end if n//2 = 0 then n := n/2 else n := 3*n + 1 end end end hailstone   % Make an array from an iterator iter_array = pro...
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 ...
#Kotlin
Kotlin
import java.math.BigInteger import java.util.*   val Three = BigInteger.valueOf(3)!! val Five = BigInteger.valueOf(5)!!   fun updateFrontier(x : BigInteger, pq : PriorityQueue<BigInteger>) { pq.add(x.shiftLeft(1)) pq.add(x.multiply(Three)) pq.add(x.multiply(Five)) }   fun hamming(n : Int) : BigInteger { ...
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...
#Oforth
Oforth
import: console   : guess 10 rand doWhile: [ "Guess :" . System.Console askln asInteger over <> ] drop "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...
#Ol
Ol
  (import (otus random!))   (define number (+ 1 (rand! 10))) (let loop () (display "Pick a number from 1 through 10: ") (if (eq? (read) number) (print "Well guessed!") (loop)))  
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...
#PHP
PHP
  <?php   function max_sum_seq($sequence) { // This runs in linear time. $sum_start = 0; $sum = 0; $max_sum = 0; $max_start = 0; $max_len = 0; for ($i = 0; $i < count($sequence); $i += 1) { $n = $sequence[$i]; $sum += $n; if ($sum > $max_sum) { $max_sum = $sum; $max_start = $sum_st...
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...
#Java
Java
import java.util.Random; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); Random random = new Random(); long from = 1; long to = 100; int randomNumber = random.nextInt(to - from + 1) + from; ...
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...
#Kotlin
Kotlin
// version 1.0.5-2   fun isHappy(n: Int): Boolean { val cache = mutableListOf<Int>() var sum = 0 var nn = n var digit: Int while (nn != 1) { if (nn in cache) return false cache.add(nn) while (nn != 0) { digit = nn % 10 sum += digit * digit ...
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...
#UBASIC
UBASIC
  10 Point 7 'Sets decimal display to 32 places (0+.1^56) 20 Rf=#pi/180 'Degree -> Radian Conversion 100 ?Using(,7),.DxH(36+7.2/60,-(86+40.2/60),33+56.4/60,-(118+24/60));" km" 999 End 1000 '*** Haversine Distance Function *** 1010 .DxH(Lat_s,Long_s,Lat_f,Long_f) 1020 L_s=Lat_s*rf:L_f=Lat_f*rf:LD=L_f...
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...
#VBA
VBA
Const MER = 6371 '-- mean earth radius(km) Public DEG_TO_RAD As Double   Function haversine(lat1 As Double, long1 As Double, lat2 As Double, long2 As Double) As Double lat1 = lat1 * DEG_TO_RAD lat2 = lat2 * DEG_TO_RAD long1 = long1 * DEG_TO_RAD long2 = long2 * DEG_TO_RAD haversine = MER * Wo...
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
#i
i
software { 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/...
#Visual_FoxPro
Visual FoxPro
  LOCAL lnCount As Integer, k As Integer CLEAR lnCount = 0 k = 0 *!* First 20 numbers ? "First 20 numbers:" DO WHILE lnCount < 20 k = k + 1 IF Harshad(k) lnCount = lnCount + 1 ? lnCount, k ENDIF ENDDO *!* First such number > 1000 k = 1001 DO WHILE NOT Harshad(k) k = k + 1 ENDDO ? "First such number...
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
#Processing
Processing
  fill(0, 0, 0); text("Goodbye, World!",0,height/2);  
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
#Prolog
Prolog
send(@display, inform, '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...
#NOWUT
NOWUT
; link with PIOxxx.OBJ   sectiondata   output: db " : " inbinary: db "00000 => " graybinary: db "00000 => " outbinary: db "00000" db 13,10,0  ; carriage return and null terminator   sectioncode   start! gosub initplatform   beginfunc l...
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...
#OCaml
OCaml
let gray_encode b = b lxor (b lsr 1)   let gray_decode n = let rec aux p n = if n = 0 then p else aux (p lxor n) (n lsr 1) in aux n (n lsr 1)   let bool_string len n = let s = Bytes.make len '0' in let rec aux i n = if n land 1 = 1 then Bytes.set s i '1'; if i <= 0 then (Bytes.to_string s) ...
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...
#Bracmat
Bracmat
(!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.
#COBOL
COBOL
DISPLAY FUNCTION MAX(nums (ALL))
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...
#BCPL
BCPL
get "libhdr"   let gcd(m,n) = n=0 -> m, gcd(n, m rem n)   let show(m,n) be writef("gcd(%N, %N) = %N*N", m, n, gcd(m, n))   let start() be $( show(18,12) show(1071,1029) show(3528,3780) $)
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...
#COBOL
COBOL
identification division. program-id. hailstones. remarks. cobc -x hailstones.cob.   data division. working-storage section. 01 most constant as 1000000. 01 coverage constant as 100000. 01 stones usage binary-long. ...
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 ...
#Liberty_BASIC
Liberty BASIC
  dim h( 1000000)   for i =1 to 20 print hamming( i); " "; next i   print print "H( 1691)", hamming( 1691) print "H( 1000000)", hamming( 1000000)   end   function hamming( limit) h( 0) =1 x2 =2: x3 =3: x5 =5 i =0: j =0: k =0 for n =1 to limit h( n) = min( x2, min( x3, x5)) if x2 =...
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...
#PARI.2FGP
PARI/GP
guess()=my(r=random(10)+1);while(input()!=r,); "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...
#Pascal
Pascal
Program GuessTheNumber(input, output);   var number, guess: integer;   begin randomize; number := random(10) + 1; writeln ('I''m thinking of a number between 1 and 10, which you should guess.'); write ('Enter your guess: '); readln (guess); while guess <> number do begin writeln ('Sorry, but your...
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...
#Picat
Picat
greatest_subsequential_sum_it([]) = [] => true. greatest_subsequential_sum_it(A) = Seq => P = allcomb(A), Total = max([Tot : Tot=_T in P]), Seq1 = [], if Total > 0 then [B,E] = P.get(Total), Seq1 := [A[I] : I in B..E] else Seq1 := [] end, Seq = Seq1.   allcomb(A) = Comb ...
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...
#PicoLisp
PicoLisp
(maxi '((L) (apply + L)) (mapcon '((L) (maplist reverse (reverse L))) (-1 -2 3 5 6 -2 -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...
#JavaScript
JavaScript
<p>Pick a number between 1 and 100.</p> <form id="guessNumber"> <input type="text" name="guess"> <input type="submit" value="Submit Guess"> </form> <p id="output"></p> <script type="text/javascript">
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...
#Lasso
Lasso
#!/usr/bin/lasso9   define isHappy(n::integer) => { local(past = set) while(#n != 1) => { #n = with i in string(#n)->values sum math_pow(integer(#i), 2) #past->contains(#n) ? return false | #past->insert(#n) } return true }   with x in generateSeries(1, 500) where isHappy(#x) take 8 select #x
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...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Math   Module Module1   Const deg2rad As Double = PI / 180   Structure AP_Loc Public IATA_Code As String, Lat As Double, Lon As Double   Public Sub New(ByVal iata_code As String, ByVal lat As Double, ByVal lon As Double) Me.IATA_Code = iata_code : Me.Lat = lat * deg2rad : Me.Lon = lon *...
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
#Icon_and_Unicon
Icon and Unicon
procedure main() write( "Hello world!" ) 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/...
#VTL-2
VTL-2
10 ?="First 20: "; 20 N=0 30 I=0 40 #=200 50 ?=N 60 $=32 70 I=I+1 80 #=I<20*40 90 ?="" 100 ?="First above 1000: "; 110 N=1000 120 #=200 130 ?=N 140 #=999 200 ;=! 210 N=N+1 220 K=N 230 S=0 240 K=K/10 250 S=S+% 260 #=0<K*240 270 #=N/S*0+0<%*210 280 #=;
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
#Pure_Data
Pure Data
#N canvas 321 432 450 300 10; #X obj 100 52 loadbang; #X msg 100 74 Goodbye\, World!; #X obj 100 96 print -n; #X connect 0 0 1 0; #X connect 1 0 2 0;
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#PureBasic
PureBasic
MessageRequester("Hello","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...
#PARI.2FGP
PARI/GP
toGray(n)=bitxor(n,n>>1); fromGray(n)=my(k=1,m=n);while(m>>k,n=bitxor(n,n>>k);k+=k);n; bin(n)=concat(apply(k->Str(k),binary(n)))   for(n=0,31,print(n"\t"bin(n)"\t"bin(g=toGray(n))"\t"fromGray(g)))