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/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, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles". Task Implement a great-circle distance function, or use a library function, to show the great-circle distance between: Nashville International Airport (BNA)   in Nashville, TN, USA,   which is: N 36°7.2', W 86°40.2' (36.12, -86.67) -and- Los Angeles International Airport (LAX)  in Los Angeles, CA, USA,   which is: N 33°56.4', W 118°24.0' (33.94, -118.40) User Kaimbridge clarified on the Talk page: -- 6371.0 km is the authalic radius based on/extracted from surface area; -- 6372.8 km is an approximation of the radius of the average circumference (i.e., the average great-elliptic or great-circle radius), where the boundaries are the meridian (6367.45 km) and the equator (6378.14 km). Using either of these values results, of course, in differing distances: 6371.0 km -> 2886.44444283798329974715782394574671655 km; 6372.8 km -> 2887.25995060711033944886005029688505340 km; (results extended for accuracy check: Given that the radii are only approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km, practical precision required is certainly no greater than about .0000001——i.e., .1 mm!) As distances are segments of great circles/circumferences, it is recommended that the latter value (r = 6372.8 km) be used (which most of the given solutions have already adopted, anyways). Most of the examples below adopted Kaimbridge's recommended value of 6372.8 km for the earth radius. However, the derivation of this ellipsoidal quadratic mean radius is wrong (the averaging over azimuth is biased). When applying these examples in real applications, it is better to use the mean earth radius, 6371 km. This value is recommended by the International Union of Geodesy and Geophysics and it minimizes the RMS relative error between the great circle and geodesic distance.
#Oforth
Oforth
import: math   : haversine(lat1, lon1, lat2, lon2) | lat lon |   lat2 lat1 - asRadian ->lat lon2 lon1 - asRadian ->lon   lon 2 / sin sq lat1 asRadian cos * lat2 asRadian cos * lat 2 / sin sq + sqrt asin 2 * 6372.8 * ;   haversine(36.12, -86.67, 33.94, -118.40) println
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, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles". Task Implement a great-circle distance function, or use a library function, to show the great-circle distance between: Nashville International Airport (BNA)   in Nashville, TN, USA,   which is: N 36°7.2', W 86°40.2' (36.12, -86.67) -and- Los Angeles International Airport (LAX)  in Los Angeles, CA, USA,   which is: N 33°56.4', W 118°24.0' (33.94, -118.40) User Kaimbridge clarified on the Talk page: -- 6371.0 km is the authalic radius based on/extracted from surface area; -- 6372.8 km is an approximation of the radius of the average circumference (i.e., the average great-elliptic or great-circle radius), where the boundaries are the meridian (6367.45 km) and the equator (6378.14 km). Using either of these values results, of course, in differing distances: 6371.0 km -> 2886.44444283798329974715782394574671655 km; 6372.8 km -> 2887.25995060711033944886005029688505340 km; (results extended for accuracy check: Given that the radii are only approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km, practical precision required is certainly no greater than about .0000001——i.e., .1 mm!) As distances are segments of great circles/circumferences, it is recommended that the latter value (r = 6372.8 km) be used (which most of the given solutions have already adopted, anyways). Most of the examples below adopted Kaimbridge's recommended value of 6372.8 km for the earth radius. However, the derivation of this ellipsoidal quadratic mean radius is wrong (the averaging over azimuth is biased). When applying these examples in real applications, it is better to use the mean earth radius, 6371 km. This value is recommended by the International Union of Geodesy and Geophysics and it minimizes the RMS relative error between the great circle and geodesic distance.
#ooRexx
ooRexx
/*REXX pgm calculates distance between Nashville & Los Angles airports. */ say " Nashville: north 36º 7.2', west 86º 40.2' = 36.12º, -86.67º" say "Los Angles: north 33º 56.4', west 118º 24.0' = 33.94º, -118.40º" say dist=surfaceDistance(36.12, -86.67, 33.94, -118.4) kdist=format(dist/1 ,,2) /*show 2 digs past decimal point.*/ mdist=format(dist/1.609344,,2) /* " " " " " " */ ndist=format(mdist*5280/6076.1,,2) /* " " " " " " */ say ' distance between= ' kdist " kilometers," say ' or ' mdist " statute miles," say ' or ' ndist " nautical or air miles." exit /*stick a fork in it, we're done.*/ /*----------------------------------SURFACEDISTANCE subroutine----------*/ surfaceDistance: arg th1,ph1,th2,ph2 /*use haversine formula for dist.*/ radius = 6372.8 /*earth's mean radius in km */ ph1 = ph1-ph2 x = cos(ph1) * cos(th1) - cos(th2) y = sin(ph1) * cos(th1) z = sin(th1) - sin(th2) return radius * 2 * aSin(sqrt(x**2+y**2+z**2)/2 )   cos: Return RxCalcCos(arg(1)) sin: Return RxCalcSin(arg(1)) asin: Return RxCalcArcSin(arg(1),,'R') sqrt: Return RxCalcSqrt(arg(1)) ::requires rxMath library
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
#GLBasic
GLBasic
STDOUT "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/procedure to generate successive members of the Harshad sequence. Use it to:   list the first 20 members of the sequence,   and   list the first Harshad number greater than 1000. Show your output here. Related task   Increasing gaps between consecutive Niven numbers See also   OEIS: A005349
#PicoLisp
PicoLisp
  #if niven number, return it. (de niven (N) (if (=0 (% N (apply + (getN N)))) N) )   #function which creates a list of numbers from input (de getN (N) (mapcar format (chop N)) )   #This function generates niven number list (de nivGen (R N) (extract niven (range R N)) )   #print 1st 20 niven numbers and 1st niven number greater than 1000 (printsp ~(list ~(head 20 (nivGen 1 1000) ) (max ~(nivGen 1001 1010)) ) )  
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
#Just_Basic
Just Basic
  print "Goodbye, World!" 'Prints in the upper left corner of the default text window: mainwin, a window with scroll bars.  
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
#KonsolScript
KonsolScript
function main() { Konsol:Message("Goodbye, World!", "") }
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dialogs to query the user for further information Task For a minimal "application", write a program that presents a form with three components to the user: a numeric input field ("Value") a button ("increment") a button ("random") The field is initialized to zero. The user may manually enter a new value into the field, or increment its value with the "increment" button. Entering a non-numeric value should be either impossible, or issue an error message. Pressing the "random" button presents a confirmation dialog, and resets the field's value to a random value if the answer is "Yes". (This task may be regarded as an extension of the task Simple windowed application).
#Ring
Ring
  Load "guilib.ring"   MyApp = New qApp { num = 0 win1 = new qWidget() { setwindowtitle("Hello World") setGeometry(100,100,370,250)   btn1 = new qpushbutton(win1) { setGeometry(200,200,100,30) settext("Random") setclickevent("Rand()")}   btn2 = new qpushbutton(win1) { setGeometry(50,200,100,30) settext("Increment") setclickevent("Increment()")}   lineedit1 = new qlineedit(win1) { setGeometry(10,100,350,30)} show()} exec()}   func Rand num = string(random(10000)) lineedit1.settext(num)   func Increment lineedit1{ num = text()} num = string(number(num)+1) lineedit1.settext(num)  
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dialogs to query the user for further information Task For a minimal "application", write a program that presents a form with three components to the user: a numeric input field ("Value") a button ("increment") a button ("random") The field is initialized to zero. The user may manually enter a new value into the field, or increment its value with the "increment" button. Entering a non-numeric value should be either impossible, or issue an error message. Pressing the "random" button presents a confirmation dialog, and resets the field's value to a random value if the answer is "Yes". (This task may be regarded as an extension of the task Simple windowed application).
#Ruby
Ruby
Shoes.app(title: "GUI component interaction") do stack do textbox = edit_line   textbox.change do textbox.text = textbox.text.gsub(/[^\d]/, '') and alert "Input must be a number!" if textbox.text !~ /^\d*$/ end   flow do button "Increment" do textbox.text = textbox.text.to_i + 1 end   button "Random" do textbox.text = rand 5000 if confirm "Do you want a random number?" end end end end
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] Reference Converting Between Gray and Binary Codes. It includes step-by-step animations.
#Batch_File
Batch File
:: Gray Code Task from Rosetta Code :: Batch File Implementation   @echo off rem -------------- define batch file macros with parameters appended rem more info: https://www.dostips.com/forum/viewtopic.php?f=3&t=2518 setlocal disabledelayedexpansion % == required for macro ==% (set \n=^^^ %== this creates escaped line feed for macro ==% ) rem convert to binary (unsigned) rem argument: natnum bitlength outputvar rem note: if natnum is negative, then !outputvar! is empty set tobinary=for %%# in (1 2) do if %%#==2 ( %\n% for /f "tokens=1,2,3" %%a in ("!args!") do ( %\n% set "natnum=%%a"^&set "bitlength=%%b"^&set "outputvar=%%c") %\n% set "!outputvar!=" %\n% if !natnum! geq 0 ( %\n% set "currnum=!natnum!" %\n% for /l %%m in (1,1,!bitlength!) do ( %\n% set /a "bit=!currnum!%%2" %\n% for %%v in (!outputvar!) do set "!outputvar!=!bit!!%%v!" %\n% set /a "currnum/=2" %\n% ) %\n% ) %\n% ) else set args=   goto :main-thing %== jump to the main thing ==% rem -------------- usual "call" sections rem the sad disadvantage of using these is that they are slow (TnT) rem gray code encoder rem argument: natnum outputvar :encoder set /a "%~2=%~1^(%~1>>1)" goto :eof rem gray code decoder rem argument: natnum outputvar :decoder set "inp=%~1" & set "%~2=0" :while-loop-1 if %inp% gtr 0 ( set /a "%~2^=%inp%, inp>>=1" goto while-loop-1 ) goto :eof rem -------------- main thing :main-thing setlocal enabledelayedexpansion echo(# -^> bin -^> enc -^> dec for /l %%n in (0,1,31) do ( %tobinary% %%n 5 bin call :encoder "%%n" "enc" %tobinary% !enc! 5 gray call :decoder "!enc!" "dec" %tobinary% !dec! 5 rebin echo(%%n -^> !bin! -^> !gray! -^> !rebin! ) exit /b 0
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#Arturo
Arturo
print split.lines execute "ls"
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#AWK
AWK
  BEGIN {   # For Windows out = system2var("dir") print out   # Non-Windows out = getline2var("ls -l") print out }   # For a Windows environment using system() method function system2var(command ,tempfile, cmd, out, rec, data, i) { tempfile = "C:\\TEMP\\TMP.TMP" cmd = command " > " tempfile system(cmd) close(cmd) while (getline rec < tempfile > 0) { if ( ++i == 1 ) data = rec else data = data "\n" rec } return(data) }   # If command returns an ERRNO function returns null string function getline2var(command ,fish, scale, ship) { command = command " 2>/dev/null" while ( (command | getline fish) > 0 ) { if ( ++scale == 1 ) ship = fish else ship = ship "\n" fish } close(command) return ship }
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#BaCon
BaCon
' Get system command result$ = EXEC$("fortune") PRINT CHOP$(result$) PRINT "First word: " & TOKEN$(result$, 1)
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#11l
11l
F swap(&a, &b) (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.
#Amazing_Hopper
Amazing Hopper
  #include <hopper.h> main: lst=0 max=0 file="datos.txt"   {","} toksep {file} statsfile {file} load mov (lst) {0} reshape (lst) {lst} array (SORT) [end] get (lst) mov (max) {"Maximo = "} {max} {"\n"} print exit(0)  
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.
#AntLang
AntLang
max|range[10]
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#ACL2
ACL2
(include-book "arithmetic-3/floor-mod/floor-mod" :dir :system)   (defun gcd$ (x y) (declare (xargs :guard (and (natp x) (natp y)))) (cond ((or (not (natp x)) (< y 0)) nil) ((zp y) x) (t (gcd$ y (mod x y)))))
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.
#C
C
#include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <sys/types.h> #include <fcntl.h> #include <sys/stat.h> #include <unistd.h> #include <err.h> #include <string.h>   char * find_match(const char *buf, const char * buf_end, const char *pat, size_t len) { ptrdiff_t i; char *start = buf; while (start + len < buf_end) { for (i = 0; i < len; i++) if (start[i] != pat[i]) break;   if (i == len) return (char *)start; start++; } return 0; }   int replace(const char *from, const char *to, const char *fname) { #define bail(msg) { warn(msg" '%s'", fname); goto done; } struct stat st; int ret = 0; char *buf = 0, *start, *end; size_t len = strlen(from), nlen = strlen(to); int fd = open(fname, O_RDWR);   if (fd == -1) bail("Can't open"); if (fstat(fd, &st) == -1) bail("Can't stat"); if (!(buf = malloc(st.st_size))) bail("Can't alloc"); if (read(fd, buf, st.st_size) != st.st_size) bail("Bad read");   start = buf; end = find_match(start, buf + st.st_size, from, len); if (!end) goto done; /* no match found, don't change file */   ftruncate(fd, 0); lseek(fd, 0, 0); do { write(fd, start, end - start); /* write content before match */ write(fd, to, nlen); /* write replacement of match */ start = end + len; /* skip to end of match */ /* find match again */ end = find_match(start, buf + st.st_size, from, len); } while (end);   /* write leftover after last match */ if (start < buf + st.st_size) write(fd, start, buf + st.st_size - start);   done: if (fd != -1) close(fd); if (buf) free(buf); return ret; }   int main() { const char *from = "Goodbye, London!"; const char *to = "Hello, New York!"; const char * files[] = { "test1.txt", "test2.txt", "test3.txt" }; int i;   for (i = 0; i < sizeof(files)/sizeof(char*); i++) replace(from, to, files[i]);   return 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 conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):   hailstone sequence,   hailstone numbers   3x + 2 mapping,   3n + 1 problem   Collatz sequence   Hasse's algorithm   Kakutani's problem   Syracuse algorithm,   Syracuse problem   Thwaites conjecture   Ulam's problem The hailstone sequence is also known as   hailstone numbers   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). Task Create a routine to generate the hailstone sequence for a number. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.   (But don't show the actual sequence!) See also   xkcd (humourous).   The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).   The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
#ALGOL_68
ALGOL 68
MODE LINT = # LONG ... # INT;   PROC hailstone = (INT in n, REF[]LINT array)INT: ( INT hs := 1; INT index := 0; LINT n := in n;   WHILE n /= 1 DO hs +:= 1; IF array ISNT REF[]LINT(NIL) THEN array[index +:= 1] := n FI; n := IF ODD n THEN 3*n+1 ELSE n OVER 2 FI OD; IF array ISNT REF[]LINT(NIL) THEN array[index +:= 1] := n FI; hs );   main: ( INT j, hmax := 0; INT jatmax, n; INT border = 4;   FOR j TO 100000-1 DO n := hailstone(j, NIL); IF hmax < n THEN hmax := n; jatmax := j FI OD;   [2]INT test := (27, jatmax); FOR key TO UPB test DO INT val = test[key]; n := hailstone(val, NIL); [n]LINT array; n := hailstone(val, array);   printf(($"[ "n(border)(g(0)", ")" ..."n(border)(", "g(0))"] len="g(0)l$, array[:border], array[n-border+1:], n)) #;free(array) # OD; printf(($"Max "g(0)" at j="g(0)l$, hmax, jatmax)) # ELLA Algol68RS: print(("Max",hmax," at j=",jatmax, new line)) # )
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color use the formula recommended by CIE: L = 0.2126 × R + 0.7152 × G + 0.0722 × B When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
#Go
Go
package raster   import ( "math" "math/rand" )   // Grmap parallels Bitmap, but with an element type of uint16 // in place of Pixel. type Grmap struct { Comments []string rows, cols int px []uint16 pxRow [][]uint16 }   // NewGrmap constructor. func NewGrmap(x, y int) (b *Grmap) { g := &Grmap{ Comments: []string{creator}, // creator a const in bitmap source file rows: y, cols: x, px: make([]uint16, x*y), pxRow: make([][]uint16, y), } x0, x1 := 0, x for i := range g.pxRow { g.pxRow[i] = g.px[x0:x1] x0, x1 = x1, x1+x } return g }   func (b *Grmap) Extent() (cols, rows int) { return b.cols, b.rows }   func (g *Grmap) Fill(c uint16) { for i := range g.px { g.px[i] = c } }   func (g *Grmap) SetPx(x, y int, c uint16) bool { defer func() { recover() }() g.pxRow[y][x] = c return true }   func (g *Grmap) GetPx(x, y int) (uint16, bool) { defer func() { recover() }() return g.pxRow[y][x], true }   // Grmap method of Bitmap, converts (color) Bitmap to (grayscale) Grmap func (b *Bitmap) Grmap() *Grmap { g := NewGrmap(b.cols, b.rows) g.Comments = append([]string{}, b.Comments...) for i, p := range b.px { g.px[i] = uint16((int64(p.R)*2126 + int64(p.G)*7152 + int64(p.B)*722) * math.MaxUint16 / (math.MaxUint8 * 10000)) } return g }   // Bitmap method Grmap, converts Grmap to Bitmap. All pixels in the resulting // color Bitmap will be (very nearly) shades of gray. func (g *Grmap) Bitmap() *Bitmap { b := NewBitmap(g.cols, g.rows) b.Comments = append([]string{}, g.Comments...) for i, p := range g.px { roundedSum := int(p) * 3 * math.MaxUint8 / math.MaxUint16 rounded := uint8(roundedSum / 3) remainder := roundedSum % 3 b.px[i].R = rounded b.px[i].G = rounded b.px[i].B = rounded if remainder > 0 { odd := rand.Intn(3) switch odd + (remainder * 3) { case 3: b.px[i].R++ case 4: b.px[i].G++ case 5: b.px[i].B++ case 6: b.px[i].G++ b.px[i].B++ case 7: b.px[i].R++ b.px[i].B++ case 8: b.px[i].R++ b.px[i].G++ } } } return b }
http://rosettacode.org/wiki/Go_Fish
Go Fish
Write a program to let the user play Go Fish against a computer opponent. Use the following rules: Each player is dealt nine cards to start with. On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more. If the opponent has any cards of the named rank, they must hand over all such cards, and the requester can ask again. If the opponent has no cards of the named rank, the requester draws a card and ends their turn. A book is a collection of every card of a given rank. Whenever a player completes a book, they may remove it from their hand. If at any time a player's hand is empty, they may immediately draw a new card, so long as any new cards remain in the deck. The game ends when every book is complete. The player with the most books wins. The game's AI need not be terribly smart, but it should use at least some strategy. That is, it shouldn't choose legal moves entirely at random. You may want to use code from Playing Cards. Related tasks: Playing cards Card shuffles Deal cards_for_FreeCell War Card_Game Poker hand_analyser
#Java
Java
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Go_Fish use warnings; use List::Util qw( first shuffle );   my $pat = qr/[atjqk2-9]/; # ranks my $deck = join '', shuffle map { my $rank = $_; map "$rank$_", qw( S H C D ) } qw( a t j q k ), 2 .. 9;   my $mebooks = my $youbooks = 0;   my $me = substr $deck, 0, 2 * 9, ''; my $mepicks = join '', $me =~ /$pat/g; arrange($me); $mebooks++ while $me =~ s/($pat).\1.\1.\1.//; my $you = substr $deck, 0, 2 * 9, ''; my $youpicks = join '', $you =~ /$pat/g; arrange($you); $youbooks++ while $you =~ s/($pat).\1.\1.\1.//;   while( $mebooks + $youbooks < 13 ) { play( \$you, \$youbooks, \$youpicks, \$me, \$mebooks, 1 ); $mebooks + $youbooks == 13 and last; play( \$me, \$mebooks, \$mepicks, \$you, \$youbooks, 0 ); } print "me $mebooks you $youbooks\n";   sub arrange { $_[0] = join '', sort $_[0] =~ /../g }   sub human { my $have = shift =~ s/($pat).\K(?!\1)/ /gr; local $| = 1; my $pick; do { print "You have $have, enter request: "; ($pick) = lc(<STDIN>) =~ /$pat/g; } until $pick and $have =~ /$pick/; return $pick; }   sub play { my ($me, $mb, $lastpicks, $you, $yb, $human) = @_; my $more = 1; while( arrange( $$me ), $more and $$mb + $$yb < 13 ) { # use Data::Dump 'dd'; dd \@_, "deck $deck"; if( $$me =~ s/($pat).\1.\1.\1.// ) { print "book of $&\n"; $$mb++; } elsif( $$me ) { my $pick = $human ? do { human($$me) } : do { my %picks; $picks{$_}++ for my @picks = $$me =~ /$pat/g; my $pick = first { $picks{$_} } split(//, $$lastpicks), shuffle @picks; print "pick $pick\n"; $$lastpicks =~ s/$pick//g; $$lastpicks .= $pick; $pick; }; if( $$you =~ s/(?:$pick.)+// ) { $$me .= $&; } else { print "GO FISH !!\n"; $$me .= substr $deck, 0, 2, ''; $more = 0; } } elsif( $deck ) { $$me .= substr $deck, 0, 2, ''; } else { $more = 0; } } arrange( $$me ); }
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#Crystal
Crystal
require "big"   def hamming(limit) h = Array.new(limit, 1.to_big_i) # h = Array.new(limit+1, 1.to_big_i) x2, x3, x5 = 2.to_big_i, 3.to_big_i, 5.to_big_i i, j, k = 0, 0, 0 (1...limit).each do |n| # (1..limit).each do |n| h[n] = Math.min(x2, Math.min(x3, x5)) x2 = 2 * h[i += 1] if x2 == h[n] x3 = 3 * h[j += 1] if x3 == h[n] x5 = 5 * h[k += 1] if x5 == h[n] end h[limit - 1] end   start = Time.monotonic print "Hamming Number (1..20): "; (1..20).each { |i| print "#{hamming(i)} " } puts puts "Hamming Number 1691: #{hamming 1691}" puts "Hamming Number 1,000,000: #{hamming 1_000_000}" puts "Elasped Time: #{(Time.monotonic - start).total_seconds} secs"  
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#Factor
Factor
  USING: io random math math.parser kernel formatting ; IN: guess-the-number   <PRIVATE   : gen-number ( -- n ) 10 random 1 + ;   : make-guess ( n -- n ? ) dup readln string>number = ;   : play-game ( n -- n ) [ make-guess ] [ "Guess a number between 1 and 10:" print flush ] do until ;   PRIVATE>   : guess-the-number ( -- ) gen-number play-game "Yes, the number was %d!\n" printf ;  
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#Fantom
Fantom
  class Main { public static Void main () { Str target := (1..10).random.toStr Str guess := "" while (guess != target) { echo ("Enter a guess: ") guess = Env.cur.in.readLine if (guess.trim == target) // 'trim' to remove any spaces/newline { echo ("Well guessed!") break } else echo ("Failed - try again") } } }  
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#Elixir
Elixir
defmodule Greatest do def subseq_sum(list) do list_i = Enum.with_index(list) acc = {0, 0, length(list), 0, 0} {_,max,first,last,_} = Enum.reduce(list_i, acc, fn {elm,i},{curr,max,first,last,curr_first} -> if curr < 0 do if elm > max, do: {elm, elm, i, i, curr_first}, else: {elm, max, first, last, curr_first} else cur2 = curr + elm if cur2 > max, do: {cur2, cur2, curr_first, i, curr_first}, else: {cur2, max, first, last, curr_first} end end) {max, Enum.slice(list, first..last)} end end
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#ERRE
ERRE
  PROGRAM MAX_SUM   DIM A%[11],B%[10],C%[4]   !$DYNAMIC DIM P%[0]   PROCEDURE MAX_SUBSEQUENCE(P%[],N%->A$) LOCAL A%,B%,I%,J%,M%,S% A%=1 FOR I%=0 TO N% DO S%=0 FOR J%=I% TO N% DO S%+=P%[J%] IF S%>M% THEN M%=S% A%=I% B%=J% END IF END FOR END FOR IF A%>B% THEN A$="[]" EXIT PROCEDURE END IF A$="[" FOR I%=A% TO B% DO A$+=STR$(P%[I%])+"," END FOR A$=LEFT$(A$,LEN(A$)-1)+"]" END PROCEDURE   PROCEDURE SHOW_ARRAY(P%[],N%->A$) LOCAL I% A$="[" FOR I%=0 TO N% DO A$+=STR$(P%[I%])+"," END FOR A$=LEFT$(A$,LEN(A$)-1)+"]" END PROCEDURE   BEGIN   A%[]=(0,1,2,-3,3,-1,0,-4,0,-1,-4,2) N%=UBOUND(A%,1)  !$DIM P%[N%] SHOW_ARRAY(A%[],N%->A$) PRINT(A$;" -> ";) MAX_SUBSEQUENCE(A%[],N%->A$) PRINT(A$)  !$ERASE P%   B%[]=(-1,-2,3,5,6,-2,-1,4,-4,2,-1) N%=UBOUND(B%,1)  !$DIM P%[N%] SHOW_ARRAY(B%[],N%->A$) PRINT(A$;" -> ";) MAX_SUBSEQUENCE(B%[],N%->A$) PRINT(A$)  !$ERASE P%   C%[]=(-1,-2,-3,-4,-5) N%=UBOUND(C%,1)  !$DIM P%[N%] SHOW_ARRAY(C%[],N%->A$) PRINT(A$;" -> ";) MAX_SUBSEQUENCE(C%[],N%->A$) PRINT(A$)  !$ERASE P% END PROGRAM  
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#D
D
import std.stdio, std.random, std.typecons, std.conv, std.string, std.range;   void main() { immutable interval = tuple(1, 100); writefln("Guess my target number that is between " ~ "%d and %d (inclusive).\n", interval[]); immutable target = uniform!"[]"(interval[]);   foreach (immutable i; sequence!q{n}) { writef("Your guess #%d: ", i + 1); immutable txt = stdin.readln.strip;   Nullable!int answer; try { answer = txt.to!int; } catch (ConvException e) { writefln(" I don't understand your input '%s'", txt); continue; } if (answer < interval[0] || answer > interval[1]) { writeln(" Out of range!"); continue; } if (answer == target) { writeln(" Well guessed."); break; } writeln(answer < target ? " Too low." : " Too high."); } }
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#Scala
Scala
import scala.swing._   class GreyscaleBars extends Component { override def paintComponent(g:Graphics2D)={ val barHeight=size.height>>2 for(run <- 0 to 3; colCount=8<<run){ val deltaX=size.width.toDouble/colCount val colBase=if (run%2==0) -255 else 0 for(x <- 0 until colCount){ val col=(colBase+(255.0/(colCount-1)*x).toInt).abs g.setColor(new Color(col,col,col))   val startX=(deltaX*x).toInt val endX=(deltaX*(x+1)).toInt g.fillRect(startX, barHeight*run, endX-startX, barHeight) } } } }
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "draw.s7i"; include "keybd.s7i";   const proc: main is func local var integer: barHeight is 0; var integer: barNumber is 0; var integer: colCount is 0; var integer: deltaX is 0; var integer: x is 0; var integer: col is 0; begin screen(640, 480); KEYBOARD := GRAPH_KEYBOARD; barHeight := height(curr_win) div 4; for barNumber range 0 to 3 do colCount := 8 << barNumber; deltaX := width(curr_win) div colCount; for x range 0 to pred(colCount) do if barNumber rem 2 = 0 then col := 65535 - 65535 div pred(colCount) * x; else col := 65535 div pred(colCount) * x; end if; rect(deltaX * x, barHeight * barNumber, deltaX, barHeight, color(col, col, col)); end for; end for; ignore(getc(KEYBOARD)); end func;
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the scorer scores, in turn, until the computer correctly guesses the target number. The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm. Related tasks   Guess the number/With Feedback   Bulls and cows/Player
#Perl
Perl
#!/usr/bin/perl   my $min = 1; my $max = 99; my $guess = int(rand $max) + $min; my $tries = 0;   print "=>> Think of a number between $min and $max and I'll guess it!\n Press <ENTER> when are you ready... ";   <STDIN>;   { do {   $tries++; print "\n=>> My guess is: $guess Is your number higher, lower, or equal? (h/l/e)\n> ";   my $score = <STDIN>;   if ($max <= $min) { print "\nI give up...\n" and last; } elsif ($score =~ /^h/i) { $min = $guess + 1; } elsif ($score =~ /^l/i) { $max = $guess; } elsif ($score =~ /^e/i) { print "\nI knew it! It took me only $tries tries.\n" and last; } else { print "error: invalid score\n"; }   $guess = int(($max + $min) / 2);   } while(1); }
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#Elena
Elena
import extensions; import system'collections; import system'routines;   isHappy(int n) { auto cache := new List<int>(5); int sum := 0; int num := n; while (num != 1) { if (cache.indexOfElement:num != -1) { ^ false }; cache.append(num); while (num != 0) { int digit := num.mod:10; sum += (digit*digit); num /= 10 }; num := sum; sum := 0 };   ^ true }   public program() { auto happynums  := new List<int>(8); int num := 1; while (happynums.Length < 8) { if (isHappy(num)) { happynums.append(num) };   num += 1 }; console.printLine("First 8 happy numbers: ", happynums.asEnumerable()) }
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, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles". Task Implement a great-circle distance function, or use a library function, to show the great-circle distance between: Nashville International Airport (BNA)   in Nashville, TN, USA,   which is: N 36°7.2', W 86°40.2' (36.12, -86.67) -and- Los Angeles International Airport (LAX)  in Los Angeles, CA, USA,   which is: N 33°56.4', W 118°24.0' (33.94, -118.40) User Kaimbridge clarified on the Talk page: -- 6371.0 km is the authalic radius based on/extracted from surface area; -- 6372.8 km is an approximation of the radius of the average circumference (i.e., the average great-elliptic or great-circle radius), where the boundaries are the meridian (6367.45 km) and the equator (6378.14 km). Using either of these values results, of course, in differing distances: 6371.0 km -> 2886.44444283798329974715782394574671655 km; 6372.8 km -> 2887.25995060711033944886005029688505340 km; (results extended for accuracy check: Given that the radii are only approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km, practical precision required is certainly no greater than about .0000001——i.e., .1 mm!) As distances are segments of great circles/circumferences, it is recommended that the latter value (r = 6372.8 km) be used (which most of the given solutions have already adopted, anyways). Most of the examples below adopted Kaimbridge's recommended value of 6372.8 km for the earth radius. However, the derivation of this ellipsoidal quadratic mean radius is wrong (the averaging over azimuth is biased). When applying these examples in real applications, it is better to use the mean earth radius, 6371 km. This value is recommended by the International Union of Geodesy and Geophysics and it minimizes the RMS relative error between the great circle and geodesic distance.
#PARI.2FGP
PARI/GP
dist(th1, th2, ph)={ my(v=[cos(ph)*cos(th1)-cos(th2),sin(ph)*cos(th1),sin(th1)-sin(th2)]); asin(sqrt(norml2(v))/2) }; distEarth(th1, ph1, th2, ph2)={ my(d=12742, deg=Pi/180); \\ Authalic diameter of the Earth d*dist(th1*deg, th2*deg, (ph1-ph2)*deg) }; distEarth(36.12, -86.67, 33.94, -118.4)
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
#Glee
Glee
"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/procedure to generate successive members of the Harshad sequence. Use it to:   list the first 20 members of the sequence,   and   list the first Harshad number greater than 1000. Show your output here. Related task   Increasing gaps between consecutive Niven numbers See also   OEIS: A005349
#PILOT
PILOT
C :n=0  :i=0 *first20 U :*harshad C :i=i+1 T :#i: #n J (i<20):*first20 C :n=1000 U :*harshad T :First Harshad number greater than 1000: #n E : *harshad C :n=n+1  :r=n  :s=0 *digit C :a=r/10  :s=s+(r-a*10)  :r=a J (r):*digit J (n<>s*(n/s)):*harshad E :
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
#Kotlin
Kotlin
import java.awt.* import javax.swing.*   fun main(args: Array<String>) { JOptionPane.showMessageDialog(null, "Goodbye, World!") // in alert box with(JFrame("Goodbye, World!")) { // on title bar layout = FlowLayout() add(JButton("Goodbye, World!")) // on button add(JTextArea("Goodbye, World!")) // in editable area pack() defaultCloseOperation = JFrame.EXIT_ON_CLOSE isVisible = true } }
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dialogs to query the user for further information Task For a minimal "application", write a program that presents a form with three components to the user: a numeric input field ("Value") a button ("increment") a button ("random") The field is initialized to zero. The user may manually enter a new value into the field, or increment its value with the "increment" button. Entering a non-numeric value should be either impossible, or issue an error message. Pressing the "random" button presents a confirmation dialog, and resets the field's value to a random value if the answer is "Yes". (This task may be regarded as an extension of the task Simple windowed application).
#Run_BASIC
Run BASIC
dim dd$(5) ' drop down box for i = 1 to 5 dd$(i) = "Drop ";i next i value$ = "1234" notes$ = "Rosetta Code is good"   bf$ = "<SPAN STYLE='font-family:arial; font-weight:700; font-size:12pt'>"   [screen] cls html bf$;"<center><TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 bgcolor=wheat>" html "<TR align=center BGCOLOR=tan><TD colspan=2>Rosetta Code</TD></TR><TR>" html "<TD align=right bgcolor=tan>Value:</TD><TD>" textbox #val,value$,5 html "</TD></TR><TR><TD bgcolor=tan align=right>Radio</TD><TD>" radiogroup #rdo,"1,2,3,4,5",rdo$ #rdo horizontal(1) html "</TD></TR><TR><TD bgcolor=tan align=right>Drop Down</TD><TD>" listbox #dd,dd$(),1   html "</TD></TR><TR><TD bgcolor=tan align=right>Notes</TD><TD>" textarea #notes,notes$,25,3 html "</TD></TR><TR bgcolor=tan><TD colspan=2 ALIGN=CENTER>" button #inc, "Increment", [incr] button #rnd, "Random", [rand] button #ex, "Exit", [exit] html "</TD></TR></TABLE>" wait   [incr] value = val(#val contents$()) value$ = str$(value + 1) goto [screen]   [rand] value$ = str$(int(rnd(1) * 10000)) goto [screen]   [exit] print "Bye" end
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dialogs to query the user for further information Task For a minimal "application", write a program that presents a form with three components to the user: a numeric input field ("Value") a button ("increment") a button ("random") The field is initialized to zero. The user may manually enter a new value into the field, or increment its value with the "increment" button. Entering a non-numeric value should be either impossible, or issue an error message. Pressing the "random" button presents a confirmation dialog, and resets the field's value to a random value if the answer is "Yes". (This task may be regarded as an extension of the task Simple windowed application).
#Scala
Scala
import scala.swing._ import scala.swing.Swing._ import scala.swing.event._   object Interact extends SimpleSwingApplication { def top = new MainFrame { title = "Rosetta Code >>> Task: component interaction | Language: Scala"   val numberField = new TextField { text = "0" // start at 0 horizontalAlignment = Alignment.Right }   val incButton = new Button { text = "Increment" } val randButton = new Button { text = "Random" }   // arrange buttons in a grid with 1 row, 2 columns val buttonPanel = new GridPanel(1, 2) { contents ++= List(incButton, randButton) }   // arrange text field and button panel in a grid with 2 row, 1 column contents = new GridPanel(2, 1) { contents ++= List(numberField, buttonPanel) }   // listen for keys pressed in numberField and button clicks listenTo(numberField.keys, incButton, randButton) reactions += { case kt: KeyTyped if (!kt.char.isDigit) => // if the entered char isn't a digit … kt.consume // … eat the event (i.e. stop it from being processed) case ButtonClicked(`incButton`) => if (numberField.text.isEmpty) numberField.text = "0" // we use BigInt to avoid long overflow/number format exception numberField.text = (BigInt(numberField.text) + 1).toString case ButtonClicked(`randButton`) => import Dialog._ numberField.text = showOptions(buttonPanel, message = "Are you sure?", title = "Choose an option!", entries = List("Yes", "No", "Cancel"), initial = 2) match { case Result.Yes => (Long.MaxValue * math.random).toLong.toString case _ => numberField.text } } centerOnScreen() } }
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] Reference Converting Between Gray and Binary Codes. It includes step-by-step animations.
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"STRINGLIB"   PRINT " Decimal Binary Gray Decoded" FOR number% = 0 TO 31 gray% = FNgrayencode(number%) PRINT number% " " FN_tobase(number%, 2, 5) ; PRINT " " FN_tobase(gray%, 2, 5) FNgraydecode(gray%) NEXT END   DEF FNgrayencode(B%) = B% EOR (B% >>> 1)   DEF FNgraydecode(G%) : LOCAL B% REPEAT B% EOR= G% : G% = G% >>> 1 : UNTIL G% = 0 = B%
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] Reference Converting Between Gray and Binary Codes. It includes step-by-step animations.
#bc
bc
scale = 0 /* to use integer division */   /* encode Gray code */ define e(i) { auto h, r   if (i <= 0) return 0 h = i / 2 r = e(h) * 2 /* recurse */ if (h % 2 != i % 2) r += 1 /* xor low bits of h, i */ return r }   /* decode Gray code */ define d(i) { auto h, r   if (i <= 0) return 0 h = d(i / 2) /* recurse */ r = h * 2 if (h % 2 != i % 2) r += 1 /* xor low bits of h, i */ return r }     /* print i as 5 binary digits */ define p(i) { auto d, d[]   for (d = 0; d <= 4; d++) { d[d] = i % 2 i /= 2 } for (d = 4; d >= 0; d--) { if(d[d] == 0) "0" if(d[d] == 1) "1" } }   for (i = 0; i < 32; i++) { /* original */ t = p(i); " => " /* encoded */ e = e(i); t = p(e); " => " /* decoded */ d = d(e); t = p(d); " " } quit
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#Batch_File
Batch File
  @echo off setlocal enabledelayedexpansion :: Without storing the output of the command, it can be viewed by inputting the command dir   :: Storing the output of 'dir' as "line[]" containing the respective lines of output (starting at line[1]) :: Note: This method removes any empty lines from the output set tempcount=0 for /f "tokens=*" %%i in ('dir') do ( set /a tempcount+=1 set "line!tempcount!=%%i" ) :: The array would be viewed like this for /l %%i in (1,1,%tempcount%) do echo !line%%i!   :: Storing the output of 'dir' in a file, then outputting the contents of the file to the screen :: NOTE: rewrites any file named "out.temp" in the current directory dir>out.temp type out.temp del out.temp   pause>nul  
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#Bracmat
Bracmat
(system= .sys$(str$(!arg " > temp"))&get$(temp,STR) );
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#C
C
  #include <stdio.h> #include <stdlib.h> #include <string.h>   int main(int argc, char **argv) { if (argc < 2) return 1;   FILE *fd; fd = popen(argv[1], "r"); if (!fd) return 1;   char buffer[256]; size_t chread; /* String to store entire command contents in */ size_t comalloc = 256; size_t comlen = 0; char *comout = malloc(comalloc);   /* Use fread so binary data is dealt with correctly */ while ((chread = fread(buffer, 1, sizeof(buffer), fd)) != 0) { if (comlen + chread >= comalloc) { comalloc *= 2; comout = realloc(comout, comalloc); } memmove(comout + comlen, buffer, chread); comlen += chread; }   /* We can now work with the output as we please. Just print * out to confirm output is as expected */ fwrite(comout, 1, comlen, stdout); free(comout); pclose(fd); return 0; }  
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#360_Assembly
360 Assembly
  SWAP CSECT , control section start BAKR 14,0 stack caller's registers LR 12,15 entry point address to reg.12 USING SWAP,12 use as base MVC A,=C'5678____' init field A MVC B,=C'____1234' init field B LA 2,L address of length field in reg.2 WTO TEXT=(2) Write To Operator, results in: * +5678________1234 XC A,B XOR A,B XC B,A XOR B,A XC A,B XOR A,B. A holds B, B holds A WTO TEXT=(2) Write To Operator, results in: * +____12345678____ PR , return to caller LTORG , literals displacement L DC H'16' halfword containg decimal 16 A DS CL8 field A, 8 bytes B DS CL8 field B, 8 bytes END SWAP program end  
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#APL
APL
LIST←2 4 6 3 8 ⌈/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 task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#Action.21
Action!
CARD FUNC Gcd(CARD a,b) CARD tmp   IF a<b THEN tmp=a a=b b=tmp FI   WHILE b#0 DO tmp=a MOD b a=b b=tmp OD RETURN(a)   PROC Test(CARD a,b) CARD res   res=Gcd(a,b) PrintF("GCD of %I and %I is %I%E",a,b,res) RETURN   PROC Main() Test(48,18) Test(9360,12240) Test(17,19) Test(123,1) Test(0,0) RETURN
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.
#C.23
C#
  using System.Collections.Generic; using System.IO;   class Program { static void Main() { var files = new List<string> { "test1.txt", "test2.txt" }; foreach (string file in files) { File.WriteAllText(file, File.ReadAllText(file).Replace("Goodbye London!", "Hello New York!")); } } }  
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.
#C.2B.2B
C++
#include <fstream> #include <iterator> #include <boost/regex.hpp> #include <string> #include <iostream>   int main( int argc , char *argv[ ] ) { boost::regex to_be_replaced( "Goodbye London\\s*!" ) ; std::string replacement( "Hello New York!" ) ; for ( int i = 1 ; i < argc ; i++ ) { std::ifstream infile ( argv[ i ] ) ; if ( infile ) { std::string filetext( (std::istreambuf_iterator<char>( infile )) , std::istreambuf_iterator<char>( ) ) ; std::string changed ( boost::regex_replace( filetext , to_be_replaced , replacement )) ; infile.close( ) ; std::ofstream outfile( argv[ i ] , std::ios_base::out | std::ios_base::trunc ) ; if ( outfile.is_open( ) ) { outfile << changed ; outfile.close( ) ; } } else std::cout << "Can't find file " << argv[ i ] << " !\n" ; } return 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 conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):   hailstone sequence,   hailstone numbers   3x + 2 mapping,   3n + 1 problem   Collatz sequence   Hasse's algorithm   Kakutani's problem   Syracuse algorithm,   Syracuse problem   Thwaites conjecture   Ulam's problem The hailstone sequence is also known as   hailstone numbers   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). Task Create a routine to generate the hailstone sequence for a number. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.   (But don't show the actual sequence!) See also   xkcd (humourous).   The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).   The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
#ALGOL-M
ALGOL-M
  BEGIN   INTEGER N, LEN, YES, NO, LIMIT, LONGEST, NLONG;   % RETURN P MOD Q % INTEGER FUNCTION MOD(P, Q); INTEGER P, Q; BEGIN MOD := P - Q * (P / Q); END;   % COMPUTE AND OPTIONALLY DISPLAY HAILSTONE SEQUENCE FOR N. % % RETURN LENGTH OF SEQUENCE OR ZERO ON OVERFLOW. % INTEGER FUNCTION HAILSTONE(N, DISPLAY); INTEGER N, DISPLAY; BEGIN INTEGER LEN; LEN := 1; IF DISPLAY = 1 THEN WRITE(""); WHILE (N <> 1) AND (N > 0) DO BEGIN IF DISPLAY = 1 THEN WRITEON(N," "); IF MOD(N,2) = 0 THEN N := N / 2 ELSE N := (N * 3) + 1; LEN := LEN + 1; END; IF DISPLAY = 1 THEN WRITEON(N); HAILSTONE := (IF N < 0 THEN 0 ELSE LEN); END;   % EXERCISE THE FUNCTION % YES := 1; NO := 0; WRITE("DISPLAY HAILSTONE SEQUENCE FOR WHAT NUMBER?"); READ(N); LEN := HAILSTONE(N, YES); WRITE("SEQUENCE LENGTH =", LEN);   % FIND LONGEST SEQUENCE BEFORE OVERFLOW % N := 2; LONGEST := 1; LEN := 2; NLONG := 2; LIMIT := 1000; WRITE("SEARCHING FOR LONGEST SEQUENCE UP TO N =",LIMIT," ..."); WHILE (N < LIMIT) AND (LEN <> 0) DO BEGIN LEN := HAILSTONE(N, NO); IF LEN > LONGEST THEN BEGIN LONGEST := LEN; NLONG := N; END; N := N + 1; END; IF LEN = 0 THEN WRITE("SEARCH TERMINATED WITH OVERFLOW AT N =",N-1); WRITE("MAXIMUM SEQUENCE LENGTH =", LONGEST, " FOR N =", NLONG);   END
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color use the formula recommended by CIE: L = 0.2126 × R + 0.7152 × G + 0.0722 × B When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
#Haskell
Haskell
module Bitmap.Gray(module Bitmap.Gray) where   import Bitmap import Control.Monad.ST   newtype Gray = Gray Int deriving (Eq, Ord)   instance Color Gray where luminance (Gray x) = x black = Gray 0 white = Gray 255 toNetpbm = map $ toEnum . luminance fromNetpbm = map $ Gray . fromEnum netpbmMagicNumber _ = "P5" netpbmMaxval _ = "255"   toGrayImage :: Color c => Image s c -> ST s (Image s Gray) toGrayImage = mapImage $ Gray . luminance
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color use the formula recommended by CIE: L = 0.2126 × R + 0.7152 × G + 0.0722 × B When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
#J
J
NB. converts the image to grayscale according to formula NB. L = 0.2126*R + 0.7152*G + 0.0722*B toGray=: [: <. +/ .*"1&0.2126 0.7152 0.0722   NB. converts grayscale image to the color image, with all channels equal toColor=: 3 & $"0
http://rosettacode.org/wiki/Go_Fish
Go Fish
Write a program to let the user play Go Fish against a computer opponent. Use the following rules: Each player is dealt nine cards to start with. On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more. If the opponent has any cards of the named rank, they must hand over all such cards, and the requester can ask again. If the opponent has no cards of the named rank, the requester draws a card and ends their turn. A book is a collection of every card of a given rank. Whenever a player completes a book, they may remove it from their hand. If at any time a player's hand is empty, they may immediately draw a new card, so long as any new cards remain in the deck. The game ends when every book is complete. The player with the most books wins. The game's AI need not be terribly smart, but it should use at least some strategy. That is, it shouldn't choose legal moves entirely at random. You may want to use code from Playing Cards. Related tasks: Playing cards Card shuffles Deal cards_for_FreeCell War Card_Game Poker hand_analyser
#Julia
Julia
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Go_Fish use warnings; use List::Util qw( first shuffle );   my $pat = qr/[atjqk2-9]/; # ranks my $deck = join '', shuffle map { my $rank = $_; map "$rank$_", qw( S H C D ) } qw( a t j q k ), 2 .. 9;   my $mebooks = my $youbooks = 0;   my $me = substr $deck, 0, 2 * 9, ''; my $mepicks = join '', $me =~ /$pat/g; arrange($me); $mebooks++ while $me =~ s/($pat).\1.\1.\1.//; my $you = substr $deck, 0, 2 * 9, ''; my $youpicks = join '', $you =~ /$pat/g; arrange($you); $youbooks++ while $you =~ s/($pat).\1.\1.\1.//;   while( $mebooks + $youbooks < 13 ) { play( \$you, \$youbooks, \$youpicks, \$me, \$mebooks, 1 ); $mebooks + $youbooks == 13 and last; play( \$me, \$mebooks, \$mepicks, \$you, \$youbooks, 0 ); } print "me $mebooks you $youbooks\n";   sub arrange { $_[0] = join '', sort $_[0] =~ /../g }   sub human { my $have = shift =~ s/($pat).\K(?!\1)/ /gr; local $| = 1; my $pick; do { print "You have $have, enter request: "; ($pick) = lc(<STDIN>) =~ /$pat/g; } until $pick and $have =~ /$pick/; return $pick; }   sub play { my ($me, $mb, $lastpicks, $you, $yb, $human) = @_; my $more = 1; while( arrange( $$me ), $more and $$mb + $$yb < 13 ) { # use Data::Dump 'dd'; dd \@_, "deck $deck"; if( $$me =~ s/($pat).\1.\1.\1.// ) { print "book of $&\n"; $$mb++; } elsif( $$me ) { my $pick = $human ? do { human($$me) } : do { my %picks; $picks{$_}++ for my @picks = $$me =~ /$pat/g; my $pick = first { $picks{$_} } split(//, $$lastpicks), shuffle @picks; print "pick $pick\n"; $$lastpicks =~ s/$pick//g; $$lastpicks .= $pick; $pick; }; if( $$you =~ s/(?:$pick.)+// ) { $$me .= $&; } else { print "GO FISH !!\n"; $$me .= substr $deck, 0, 2, ''; $more = 0; } } elsif( $deck ) { $$me .= substr $deck, 0, 2, ''; } else { $more = 0; } } arrange( $$me ); }
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#D
D
import std.stdio, std.bigint, std.algorithm, std.range, core.memory;   auto hamming(in uint n) pure nothrow /*@safe*/ { immutable BigInt two = 2, three = 3, five = 5; auto h = new BigInt[n]; h[0] = 1; BigInt x2 = 2, x3 = 3, x5 = 5; size_t i, j, k;   foreach (ref el; h.dropOne) { el = min(x2, x3, x5); if (el == x2) x2 = two * h[++i]; if (el == x3) x3 = three * h[++j]; if (el == x5) x5 = five * h[++k]; } return h.back; }   void main() { GC.disable; iota(1, 21).map!hamming.writeln; 1_691.hamming.writeln; 1_000_000.hamming.writeln; }
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#Forth
Forth
  \ tested with GForth 0.7.0 : RND ( -- n) TIME&DATE 2DROP 2DROP DROP 10 MOD ; \ crude random number : ASK ( -- ) CR ." Guess a number between 1 and 10? " ; : GUESS ( -- n) PAD DUP 4 ACCEPT EVALUATE ; : REPLY ( n n' -- n) 2DUP <> IF CR ." No, it's not " DUP . THEN ;   : GAME ( -- ) RND BEGIN ASK GUESS REPLY OVER = UNTIL CR ." Yes it was " . CR ." Good guess!"  ;  
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#Fortran
Fortran
program guess_the_number implicit none   integer :: guess real :: r integer :: i, clock, count, n integer,dimension(:),allocatable :: seed   real,parameter :: rmax = 10   !initialize random number generator: call random_seed(size=n) allocate(seed(n)) call system_clock(count) seed = count call random_seed(put=seed) deallocate(seed)   !pick a random number between 1 and rmax: call random_number(r) !r between 0.0 and 1.0 i = int((rmax-1.0)*r + 1.0) !i between 1 and rmax   !get user guess: write(*,'(A)') 'I''m thinking of a number between 1 and 10.' do !loop until guess is correct write(*,'(A)',advance='NO') 'Enter Guess: ' read(*,'(I5)') guess if (guess==i) exit write(*,*) 'Sorry, try again.' end do   write(*,*) 'You''ve guessed my number!'   end program guess_the_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 the empty sequence.
#Euler_Math_Toolbox
Euler Math Toolbox
  >function %maxsubs (v,n) ... $if n==1 then $ if (v[1]<0) then return {zeros(1,0),zeros(1,0)} $ else return {v,v}; $ endif; $endif; ${v1,v2}=%maxsubs(v[1:n-1],n-1); $m1=sum(v1); m2=sum(v2); m3=m2+v[n]; $if m3>0 then v3=v2|v[n]; else v3=zeros(1,0); endif; $if m3>m1 then return {v2|v[n],v3}; $else return {v1,v3}; $endif; $endfunction >function maxsubs (v) ... ${v1,v2}=%maxsubs(v,cols(v)); $return v1 $endfunction >maxsubs([0, 1, 2, -3, 3, -1, 0, -4, 0, -1, -4]) [ 0 1 2 ] >maxsubs([-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]) [ 3 5 6 -2 -1 4 ] >maxsubs([-1, -2, -3, -4, -5]) Empty matrix of size 1x0  
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#Euphoria
Euphoria
function maxSubseq(sequence s) integer sum, maxsum, first, last maxsum = 0 first = 1 last = 0 for i = 1 to length(s) do sum = 0 for j = i to length(s) do sum += s[j] if sum > maxsum then maxsum = sum first = i last = j end if end for end for return s[first..last] end function   ? maxSubseq({-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1}) ? maxSubseq({}) ? maxSubseq({-1, -5, -3})
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#DCL
DCL
$ rnd = f$extract( 21, 2, f$time() ) $ count = 0 $ loop: $ inquire guess "guess what number between 0 and 99 inclusive I am thinking of" $ guess = f$integer( guess ) $ if guess .lt. 0 .or. guess .gt. 99 $ then $ write sys$output "out of range" $ goto loop $ endif $ count = count + 1 $ if guess .lt. rnd then $ write sys$output "too small" $ if guess .gt. rnd then $ write sys$output "too large" $ if guess .ne. rnd then $ goto loop $ write sys$output "it only took you ", count, " guesses"
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#Tcl
Tcl
package require Tcl 8.5 package require Tk 8.5   wm attributes . -fullscreen 1 pack [canvas .c -highlightthick 0] -fill both -expand 1   # Add more values into this to do more greyscale bar variations set splits {8 16 32 64} set dy [expr {[winfo screenheight .c] / [llength $splits]}] set y 0 foreach s $splits { set dx [expr {double([winfo screenwidth .c]) / $s}] set dc [expr {double(0xFF) / ($s-1)}] for {set i 0} {$i < $s} {incr i} { set c [expr {int($i * $dc)}] set x [expr {int($i * $dx)}] .c create rectangle $x $y [expr {$x+$dx+1}] [expr {$y+$dy+1}] \ -fill [format "#%02x%02x%02x" $c $c $c] -outline {} } incr y $dy }
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the scorer scores, in turn, until the computer correctly guesses the target number. The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm. Related tasks   Guess the number/With Feedback   Bulls and cows/Player
#Phix
Phix
-- -- demo\rosetta\Guess_the_number2.exw -- with javascript_semantics -- (spacing not (yet) great...) include pGUI.e Ihandle lbl, guess, toohigh, too_low, correct, newgame, dlg integer Min=0, Max=100, Guess constant LTHINK = sprintf("Think of a number between %d and %d.",{Min,Max}) procedure set_active(bool bActive) IupSetInt({toohigh, too_low, correct},"ACTIVE",bActive) IupSetInt(newgame,"ACTIVE",not bActive) end procedure procedure set_guess() Guess = floor((Max+Min)/2) string title = sprintf("My guess is %d, is this too high, too low, or correct?", Guess) if Max<Min then set_active(false) title = "I think something is strange here..." end if IupSetStrAttribute(guess,"TITLE",title) IupRefresh(guess) end procedure function click_cb(Ihandle ih) switch substitute(IupGetAttribute(ih,"TITLE"),"Too ","")[1] do case 'H': Max = Guess-1 set_guess() case 'L': Min = Guess+1 set_guess() case 'C': IupSetStrAttribute(guess,"TITLE","I did it!") set_active(false) case 'N': Min = 0 Max = 100 set_guess() set_active(true) end switch return IUP_DEFAULT end function procedure main() IupOpen() lbl = IupLabel(LTHINK) guess = IupLabel("") toohigh = IupButton("Too High", Icallback("click_cb")) too_low = IupButton("Too Low", Icallback("click_cb")) correct = IupButton("Correct", Icallback("click_cb")) newgame = IupButton("New Game", Icallback("click_cb"), "ACTIVE=NO") dlg = IupDialog(IupVbox({lbl, guess, IupHbox({toohigh,too_low,correct,newgame}, "GAP=10")}, `NMARGIN=15x15,GAP=10`), `MINSIZE=300x100,TITLE="Guess the number2"`) set_guess() IupShow(dlg) if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#Elixir
Elixir
defmodule Happy do def task(num) do Process.put({:happy, 1}, true) Stream.iterate(1, &(&1+1)) |> Stream.filter(fn n -> happy?(n) end) |> Enum.take(num) end   defp happy?(n) do sum = square_sum(n, 0) val = Process.get({:happy, sum}) if val == nil do Process.put({:happy, sum}, false) val = happy?(sum) Process.put({:happy, sum}, val) end val end   defp square_sum(0, sum), do: sum defp square_sum(n, sum) do r = rem(n, 10) square_sum(div(n, 10), sum + r*r) end end   IO.inspect Happy.task(8)
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, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles". Task Implement a great-circle distance function, or use a library function, to show the great-circle distance between: Nashville International Airport (BNA)   in Nashville, TN, USA,   which is: N 36°7.2', W 86°40.2' (36.12, -86.67) -and- Los Angeles International Airport (LAX)  in Los Angeles, CA, USA,   which is: N 33°56.4', W 118°24.0' (33.94, -118.40) User Kaimbridge clarified on the Talk page: -- 6371.0 km is the authalic radius based on/extracted from surface area; -- 6372.8 km is an approximation of the radius of the average circumference (i.e., the average great-elliptic or great-circle radius), where the boundaries are the meridian (6367.45 km) and the equator (6378.14 km). Using either of these values results, of course, in differing distances: 6371.0 km -> 2886.44444283798329974715782394574671655 km; 6372.8 km -> 2887.25995060711033944886005029688505340 km; (results extended for accuracy check: Given that the radii are only approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km, practical precision required is certainly no greater than about .0000001——i.e., .1 mm!) As distances are segments of great circles/circumferences, it is recommended that the latter value (r = 6372.8 km) be used (which most of the given solutions have already adopted, anyways). Most of the examples below adopted Kaimbridge's recommended value of 6372.8 km for the earth radius. However, the derivation of this ellipsoidal quadratic mean radius is wrong (the averaging over azimuth is biased). When applying these examples in real applications, it is better to use the mean earth radius, 6371 km. This value is recommended by the International Union of Geodesy and Geophysics and it minimizes the RMS relative error between the great circle and geodesic distance.
#Pascal
Pascal
Program HaversineDemo(output);   uses Math;   function haversineDist(th1, ph1, th2, ph2: double): double; const diameter = 2 * 6372.8; var dx, dy, dz: double; begin ph1 := degtorad(ph1 - ph2); th1 := degtorad(th1); th2 := degtorad(th2);   dz := sin(th1) - sin(th2); dx := cos(ph1) * cos(th1) - cos(th2); dy := sin(ph1) * cos(th1); haversineDist := arcsin(sqrt(dx**2 + dy**2 + dz**2) / 2) * diameter; end;   begin writeln ('Haversine distance: ', haversineDist(36.12, -86.67, 33.94, -118.4):7:2, ' km.'); end.
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Global_Script
Global Script
λ _. print qq{Hello world!\n}
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/procedure to generate successive members of the Harshad sequence. Use it to:   list the first 20 members of the sequence,   and   list the first Harshad number greater than 1000. Show your output here. Related task   Increasing gaps between consecutive Niven numbers See also   OEIS: A005349
#PL.2FI
PL/I
*process source or(!) xref attributes; niven: Proc Options(main); /********************************************************************* * 08-06.2013 Walter Pachl translated from Rexx * with a slight improvement: Do j=y+1 By 1; *********************************************************************/ Dcl (ADDR,HBOUND,MOD,SUBSTR,VERIFY) Builtin; Dcl SYSPRINT Print;   Dcl (x,y) dec fixed(8); x=20; y=1000; Begin; Dcl (n(x),j) Dec Fixed(8); Dcl ni Bin Fixed(31) Init(0); Dcl result Char(100) Var Init(''); loop: Do j=1 By 1; If mod(j,sumdigs(j))=0 Then Do; ni+=1; n(ni)=j; result=result!!' '!!d2c(j); If ni=x Then Leave loop; End; End; Put Edit('first 20 Niven numbers: ',result)(Skip,a,a); Do j=y+1 By 1; If mod(j,sumdigs(j))=0 Then Leave; End; Put Edit('first Niven number > ',d2c(y),' is: ',d2c(j))(Skip,4(a)); End;   sumDigs: proc(z) Returns(Dec Fixed(3)); Dcl z Pic'(8)9'; Dcl d(8) Pic'9' Based(addr(z)); Dcl i Bin Fixed(31); Dcl sd Dec Fixed(3) Init(0); Do i=1 To hbound(d); sd+=d(i); End; Return(sd); End;   d2c: Proc(z) Returns(char(8) Var); Dcl z Pic'(8)z'; Dcl p Bin Fixed(31); p=verify(z,' '); Return(substr(z,p)); End;   End;
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#LabVIEW
LabVIEW
sys_process('/usr/bin/osascript', (: '-e', 'display dialog "Goodbye, World!"'))->wait
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
#Lasso
Lasso
sys_process('/usr/bin/osascript', (: '-e', 'display dialog "Goodbye, World!"'))->wait
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dialogs to query the user for further information Task For a minimal "application", write a program that presents a form with three components to the user: a numeric input field ("Value") a button ("increment") a button ("random") The field is initialized to zero. The user may manually enter a new value into the field, or increment its value with the "increment" button. Entering a non-numeric value should be either impossible, or issue an error message. Pressing the "random" button presents a confirmation dialog, and resets the field's value to a random value if the answer is "Yes". (This task may be regarded as an extension of the task Simple windowed application).
#Smalltalk
Smalltalk
|top input vh incButton rndButton|   vh := ValueHolder with:0.   top := StandardSystemView label:'Rosetta GUI interaction'. top extent:300@100. top add:((Label label:'Value:') origin: 0 @ 10 corner: 100 @ 40). top add:(input := EditField origin: 102 @ 10 corner: 1.0 @ 40). input model:(TypeConverter onNumberValue:vh). input acceptOnLostFocus:true; acceptOnReturn:true.   top add:((incButton := Button label:'Inc') origin: 10 @ 50 corner: 100 @ 80). top add:((rndButton := Button label:'Rnd') origin: 110 @ 50 corner: 210 @ 80).   incButton action:[ vh value: (vh value + 1) ]. rndButton action:[ vh value: Random nextInteger ].   top open
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dialogs to query the user for further information Task For a minimal "application", write a program that presents a form with three components to the user: a numeric input field ("Value") a button ("increment") a button ("random") The field is initialized to zero. The user may manually enter a new value into the field, or increment its value with the "increment" button. Entering a non-numeric value should be either impossible, or issue an error message. Pressing the "random" button presents a confirmation dialog, and resets the field's value to a random value if the answer is "Yes". (This task may be regarded as an extension of the task Simple windowed application).
#Tcl
Tcl
package require Tk   ###--- Our data Model! ---### # A single variable will do just fine set field 0   ###--- Lay out the GUI components in our View ---### # We use the Ttk widget set here; it looks much better on Windows and OSX   # First, a quick hack to make things look even nicer place [ttk::frame .bg] -relwidth 1 -relheight 1   # A labelled frame containing an entry field constrained to use numbers pack [ttk::labelframe .val -text "Value"] pack [ttk::entry .val.ue -textvariable field \ -validate key -invalidcommand bell \ -validatecommand {string is integer %P}] # Now, a pair of buttons pack [ttk::button .inc -text "increment" -command step] pack [ttk::button .rnd -text "random" -command random]   ###--- Now we define the behaviors, the Controller ---### # How to respond to a click on the "increment" button proc step {} { global field incr field } # How to respond to a click on the "random" button proc random {} { global field if {[tk_messageBox -type yesno -parent . \ -message "Reset to random?"] eq "yes"} { set field [expr {int(rand() * 5000)}] } }
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] Reference Converting Between Gray and Binary Codes. It includes step-by-step animations.
#C
C
int gray_encode(int n) { return n ^ (n >> 1); }   int gray_decode(int n) { int p = n; while (n >>= 1) p ^= n; return p; }
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] Reference Converting Between Gray and Binary Codes. It includes step-by-step animations.
#C.23
C#
using System;   public class Gray { public static ulong grayEncode(ulong n) { return n^(n>>1); }   public static ulong grayDecode(ulong n) { ulong i=1<<8*64-2; //long is 64-bit ulong p, b=p=n&i;   while((i>>=1)>0) b|=p=n&i^p>>1; return b; }   public static void Main(string[] args) { Console.WriteLine("Number\tBinary\tGray\tDecoded"); for(ulong i=0;i<32;i++) { Console.WriteLine(string.Format("{0}\t{1}\t{2}\t{3}", i, Convert.ToString((long)i, 2), Convert.ToString((long)grayEncode(i), 2), grayDecode(grayEncode(i)))); } } }
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#C.23
C#
using System;   namespace GetSystemCommandOutput { class Program { static void Main(string[] args) { System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = "cmd.exe"; startInfo.Arguments = "/c echo Hello World"; startInfo.RedirectStandardOutput = true; startInfo.UseShellExecute = false; process.StartInfo = startInfo; process.Start();   string output = process.StandardOutput.ReadToEnd(); Console.WriteLine("Output is {0}", output); } } }
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#C.2B.2B
C++
#include <fstream> #include <iostream>   std::string execute(const std::string& command) { system((command + " > temp.txt").c_str());   std::ifstream ifs("temp.txt"); std::string ret{ std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>() }; ifs.close(); // must close the inout stream so the file can be cleaned up if (std::remove("temp.txt") != 0) { perror("Error deleting temporary file"); } return ret; }   int main() { std::cout << execute("whoami") << '\n'; }
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#6502_Assembly
6502 Assembly
;swap X with Y pha  ;push accumulator txa pha  ;push x tya pha ;push y pla tax ;pop y into x pla tay  ;pop x into y pla  ;pop accumulator
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.
#AppleScript
AppleScript
  max({1, 2, 3, 4, 20, 6, 11, 3, 9, 7})   on max(aList) set _curMax to first item of aList repeat with i in (rest of aList) if i > _curMax then set _curMax to contents of i end repeat return _curMax end max  
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#ActionScript
ActionScript
//Euclidean algorithm function gcd(a:int,b:int):int { var tmp:int; //Swap the numbers so a >= b if(a < b) { tmp = a; a = b; b = tmp; } //Find the gcd while(b != 0) { tmp = a % b; a = b; b = tmp; } return 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.
#Clojure
Clojure
(defn hello-goodbye [& more] (doseq [file more] (spit file (.replace (slurp file) "Goodbye London!" "Hello New York!"))))
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.
#Common_Lisp
Common Lisp
  (defun hello-goodbye (files) (labels ((replace-from-file (file) (with-open-file (in file) (loop for line = (read-line in nil) while line do (loop for index = (search "Goodbye London!" line) while index do (setf (subseq line index) "Hello New York!")) collecting line))) (write-lines-to-file (lines file) (with-open-file (out file :direction :output :if-exists :overwrite) (dolist (line lines) (write-line line out)))) (replace-in-file (file) (write-lines-to-file (replace-from-file file) file))) (map nil #'replace-in-file files)))  
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):   hailstone sequence,   hailstone numbers   3x + 2 mapping,   3n + 1 problem   Collatz sequence   Hasse's algorithm   Kakutani's problem   Syracuse algorithm,   Syracuse problem   Thwaites conjecture   Ulam's problem The hailstone sequence is also known as   hailstone numbers   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). Task Create a routine to generate the hailstone sequence for a number. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.   (But don't show the actual sequence!) See also   xkcd (humourous).   The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).   The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
#ALGOL_W
ALGOL W
begin  % show some Hailstone Sequence related information  %  % calculates the length of the sequence generated by n,  %  % if showFirstAndLast is true, the first and last 4 elements of the  %  % sequence are stored in first and last  %  % hs holds a cache of the upbHs previously calculated sequence lengths  %  % if showFirstAndLast is false, the cache will be used  % procedure hailstone ( integer value n  ; integer array first, last ( * )  ; integer result length  ; integer array hs ( * )  ; integer value upbHs  ; logical value showFirstAndLast ) ; if not showFirstAndLast and n <= upbHs and hs( n ) not = 0 then begin  % no need to store the start and end of the sequence and we already  %  % know the length of the sequence for n  % length := hs( n ) end else begin  % must calculate the sequence length  % integer sv; for i := 1 until 4 do first( i ) := last( i ) := 0; length := 0; sv  := n; if sv > 0 then begin while begin length := length + 1; if showFirstAndLast then begin if length <= 4 then first( length ) := sv; for lPos := 1 until 3 do last( lPos ) := last( lPos + 1 ); last( 4 ) := sv end else if sv <= upbHs and hs( sv ) not = 0 then begin  % have a known value  % length := ( length + hs( sv ) ) - 1; sv  := 1 end ; sv not = 1 end do begin sv := if odd( sv ) then ( 3 * sv ) + 1 else sv div 2 end while_sv_ne_1 ; if n < upbHs then hs( n ) := length end if_sv_gt_0 end hailstone ; begin  % test the hailstone procedure  % integer HS_CACHE_SIZE; HS_CACHE_SIZE := 100000; begin integer array first, last ( 1 :: 4 ); integer length, maxLength, maxNumber; integer array hs ( 1 :: HS_CACHE_SIZE ); for i := 1 until HS_CACHE_SIZE do hs( i ) := 0; hailstone( 27, first, last, length, hs, HS_CACHE_SIZE, true ); write( i_w := 1, s_w := 0 , "27: length ", length, ", first: [" , first( 1 ), " ", first( 2 ), " ", first( 3 ), " ", first( 4 ) , "] last: [" , last( 1 ), " ", last( 2 ), " ", last( 3 ), " ", last( 4 ) , "]" ); maxNumber := 0; maxLength := 0; for n := 1 until 100000 do begin hailstone( n, first, last, length, hs, HS_CACHE_SIZE, false ); if length > maxLength then begin maxNumber := n; maxLength := length end if_length_gt_maxLength end for_n ; write( i_w := 1, s_w := 1, "Maximum sequence length: ", maxLength, " for: ", maxNumber ) end end end.
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color use the formula recommended by CIE: L = 0.2126 × R + 0.7152 × G + 0.0722 × B When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
#Java
Java
void convertToGrayscale(final BufferedImage image){ for(int i=0; i<image.getWidth(); i++){ for(int j=0; j<image.getHeight(); j++){ int color = image.getRGB(i,j);   int alpha = (color >> 24) & 255; int red = (color >> 16) & 255; int green = (color >> 8) & 255; int blue = (color) & 255;   final int lum = (int)(0.2126 * red + 0.7152 * green + 0.0722 * blue);   alpha = (alpha << 24); red = (lum << 16); green = (lum << 8); blue = lum;   color = alpha + red + green + blue;   image.setRGB(i,j,color); } } }  
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color use the formula recommended by CIE: L = 0.2126 × R + 0.7152 × G + 0.0722 × B When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
#JavaScript
JavaScript
  function toGray(img) { let cnv = document.getElementById("canvas"); let ctx = cnv.getContext('2d'); let imgW = img.width; let imgH = img.height; cnv.width = imgW; cnv.height = imgH;   ctx.drawImage(img, 0, 0); let pixels = ctx.getImageData(0, 0, imgW, imgH); for (let y = 0; y < pixels.height; y ++) { for (let x = 0; x < pixels.width; x ++) { let i = (y * 4) * pixels.width + x * 4; let avg = (pixels.data[i] + pixels.data[i + 1] + pixels.data[i + 2]) / 3;   pixels.data[i] = avg; pixels.data[i + 1] = avg; pixels.data[i + 2] = avg; } } ctx.putImageData(pixels, 0, 0, 0, 0, pixels.width, pixels.height); return cnv.toDataURL(); }  
http://rosettacode.org/wiki/Go_Fish
Go Fish
Write a program to let the user play Go Fish against a computer opponent. Use the following rules: Each player is dealt nine cards to start with. On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more. If the opponent has any cards of the named rank, they must hand over all such cards, and the requester can ask again. If the opponent has no cards of the named rank, the requester draws a card and ends their turn. A book is a collection of every card of a given rank. Whenever a player completes a book, they may remove it from their hand. If at any time a player's hand is empty, they may immediately draw a new card, so long as any new cards remain in the deck. The game ends when every book is complete. The player with the most books wins. The game's AI need not be terribly smart, but it should use at least some strategy. That is, it shouldn't choose legal moves entirely at random. You may want to use code from Playing Cards. Related tasks: Playing cards Card shuffles Deal cards_for_FreeCell War Card_Game Poker hand_analyser
#Kotlin
Kotlin
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Go_Fish use warnings; use List::Util qw( first shuffle );   my $pat = qr/[atjqk2-9]/; # ranks my $deck = join '', shuffle map { my $rank = $_; map "$rank$_", qw( S H C D ) } qw( a t j q k ), 2 .. 9;   my $mebooks = my $youbooks = 0;   my $me = substr $deck, 0, 2 * 9, ''; my $mepicks = join '', $me =~ /$pat/g; arrange($me); $mebooks++ while $me =~ s/($pat).\1.\1.\1.//; my $you = substr $deck, 0, 2 * 9, ''; my $youpicks = join '', $you =~ /$pat/g; arrange($you); $youbooks++ while $you =~ s/($pat).\1.\1.\1.//;   while( $mebooks + $youbooks < 13 ) { play( \$you, \$youbooks, \$youpicks, \$me, \$mebooks, 1 ); $mebooks + $youbooks == 13 and last; play( \$me, \$mebooks, \$mepicks, \$you, \$youbooks, 0 ); } print "me $mebooks you $youbooks\n";   sub arrange { $_[0] = join '', sort $_[0] =~ /../g }   sub human { my $have = shift =~ s/($pat).\K(?!\1)/ /gr; local $| = 1; my $pick; do { print "You have $have, enter request: "; ($pick) = lc(<STDIN>) =~ /$pat/g; } until $pick and $have =~ /$pick/; return $pick; }   sub play { my ($me, $mb, $lastpicks, $you, $yb, $human) = @_; my $more = 1; while( arrange( $$me ), $more and $$mb + $$yb < 13 ) { # use Data::Dump 'dd'; dd \@_, "deck $deck"; if( $$me =~ s/($pat).\1.\1.\1.// ) { print "book of $&\n"; $$mb++; } elsif( $$me ) { my $pick = $human ? do { human($$me) } : do { my %picks; $picks{$_}++ for my @picks = $$me =~ /$pat/g; my $pick = first { $picks{$_} } split(//, $$lastpicks), shuffle @picks; print "pick $pick\n"; $$lastpicks =~ s/$pick//g; $$lastpicks .= $pick; $pick; }; if( $$you =~ s/(?:$pick.)+// ) { $$me .= $&; } else { print "GO FISH !!\n"; $$me .= substr $deck, 0, 2, ''; $more = 0; } } elsif( $deck ) { $$me .= substr $deck, 0, 2, ''; } else { $more = 0; } } arrange( $$me ); }
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#Dart
Dart
import 'dart:math';   final lb2of2 = 1.0; final lb2of3 = log(3.0) / log(2.0); final lb2of5 = log(5.0) / log(2.0);   class Trival { final double log2; final int twos; final int threes; final int fives; Trival mul2() { return Trival(this.log2 + lb2of2, this.twos + 1, this.threes, this.fives); } Trival mul3() { return Trival(this.log2 + lb2of3, this.twos, this.threes + 1, this.fives); } Trival mul5() { return Trival(this.log2 + lb2of5, this.twos, this.threes, this.fives + 1); } @override String toString() { return this.log2.toString() + " " + this.twos.toString() + " " + this.threes.toString() + " " + this.fives.toString(); } const Trival(this.log2, this.twos, this.threes, this.fives); }   Iterable<Trival> makeHammings() sync* { var one = Trival(0.0, 0, 0, 0); yield(one); var s532 = one.mul2(); var mrg = one.mul3(); var s53 = one.mul3().mul3(); // equivalent to 9 for advance step var s5 = one.mul5(); var i = -1; var j = -1; List<Trival> h = []; List<Trival> m = []; Trival rslt; while (true) { if (s532.log2 < mrg.log2) { rslt = s532; h.add(s532); ++i; s532 = h[i].mul2(); } else { rslt = mrg; h.add(mrg); if (s53.log2 < s5.log2) { mrg = s53; m.add(s53); ++j; s53 = m[j].mul3(); } else { mrg = s5; m.add(s5); s5 = s5.mul5(); } if (j > (m.length >> 1)) {m.removeRange(0, j); j = 0; } } if (i > (h.length >> 1)) {h.removeRange(0, i); i = 0; } yield(rslt); } }   BigInt trival2Int(Trival tv) { return BigInt.from(2).pow(tv.twos) * BigInt.from(3).pow(tv.threes) * BigInt.from(5).pow(tv.fives); }   void main() { final numhams = 1000000000000; var hamseqstr = "The first 20 Hamming numbers are: ( "; makeHammings().take(20) .forEach((h) => hamseqstr += trival2BigInt(h).toString() + " "); print(hamseqstr + ")"); var nthhamseqstr = "The first 20 Hamming numbers are: ( "; for (var i = 1; i <= 20; ++i) { nthhamseqstr += trival2BigInt(nthHamming(i)).toString() + " "; } print(nthhamseqstr + ")"); final strt = DateTime.now().millisecondsSinceEpoch; final answr = makeHammings().skip(999999).first; final elpsd = DateTime.now().millisecondsSinceEpoch - strt; print("The ${numhams}th Hamming number is: $answr"); print("in full as: ${trival2BigInt(answr)}"); print("This test took $elpsd milliseconds."); }
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Randomize Dim n As Integer = Int(Rnd * 10) + 1 Dim guess As Integer Print "Guess which number I've chosen in the range 1 to 10" Print Do Input " Your guess : "; guess If n = guess Then Print "Well guessed!" End End If Loop
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#Frink
Frink
// Guess a Number target = random[1,10] // Min and max are both inclusive for the random function guess = 0 println["Welcome to guess a number! I've picked a number between 1 and 10. Try to guess it!"] while guess != target { guessStr = input["What is your guess?"] guess = parseInt[guessStr] if guess == undef println["$guessStr is not a valid guess. Please enter a number from 1 to 10."] else guess == target ? println["$guess is correct. Well guessed!"] : println["$guess is not correct. Guess again!"] }  
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#F.23
F#
let maxsubseq s = let (_, _, maxsum, maxseq) = List.fold (fun (sum, seq, maxsum, maxseq) x -> let (sum, seq) = (sum + x, x :: seq) if sum < 0 then (0, [], maxsum, maxseq) else if sum > maxsum then (sum, seq, sum, seq) else (sum, seq, maxsum, maxseq)) (0, [], 0, []) s List.rev maxseq   printfn "%A" (maxsubseq [-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 the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#Delphi
Delphi
program GuessTheNumber;   {$APPTYPE CONSOLE}   uses SysUtils, Math;     const // Set min/max limits min: Integer = 1; max: Integer = 10;   var last, val, inp: Integer; s: string;   // Initialise new game procedure NewGame; begin // Make sure this number isn't the same as the last one repeat val := RandomRange(min,max); until val <> last;   // Save this number last := val; Writeln('Guess a number between ', min, ' and ', max, ' [Answer = ', val, ']'); end;   begin // Initialise the random number generator with a random value Randomize;   // Initialise last number last := 0;   // Initialise user input s := '';   // Start game NewGame;   // Loop repeat // User input Readln(s);   // Validate - checxk if input is a number if TryStrToInt(s,inp) then begin // Is it the right number? if (inp = val) then begin // Yes - request a new game Writeln('Correct! Another go? Y/N'); Readln(s); if SameText(s,'Y') then // Start new game NewGame else Exit; end else // Input too low/high if (inp < val) then Writeln('Too low! Try again...') else if (inp > val) then Writeln('Too high! Try again...'); end else // Input invalid if not SameText(s,'bored') then Writeln('Invalid input! Try again...');   until SameText(s,'bored');     end.  
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#Wren
Wren
import "graphics" for Canvas, Color import "dome" for Window import "math" for Math   class GreyBars { construct new(width, height) { Window.title = "Grey bars example" Window.resize(width, height) Canvas.resize(width, height) _w = width _h = height }   init() { drawBars() }   drawBars() { var run = 0 var colorComp = 0 // component of the color var columnCount = 8 while (columnCount < 128) { var colorGap = 255 / (columnCount - 1) // by this gap we change the background color var columnWidth = (_w / columnCount).floor var columnHeight = (_h / 4).floor if (run % 2 == 0) { // switches color directions with each iteration of while loop colorComp = 0 } else { colorComp = 255 colorGap = -colorGap } var ystart = columnHeight * run var xstart = 0 for (i in 0...columnCount) { var iColor = Math.round(colorComp) var nextColor = Color.rgb(iColor, iColor, iColor) Canvas.rectfill(xstart, ystart, xstart + columnWidth, ystart + columnHeight, nextColor) xstart = xstart + columnWidth colorComp = colorComp + colorGap } run = run + 1 columnCount = columnCount * 2 } }   update() {}   draw(alpha) {} }   var Game = GreyBars.new(640, 320)
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the scorer scores, in turn, until the computer correctly guesses the target number. The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm. Related tasks   Guess the number/With Feedback   Bulls and cows/Player
#PicoLisp
PicoLisp
(de guessTheNumber (Min Max) (prinl "Think of a number between " Min " and " Max ".") (prinl "On every guess of mine you should state whether my guess was") (prinl "too high, too low, or equal to your number by typing 'h', 'l', Or '='") (use Guess (loop (NIL (> Max Min) (prinl "I think somthing is strange here...") ) (prin "My guess is " (setq Guess (+ Min (/ (- Max Min) 2))) ",is this correct? " ) (flush) (NIL (case (uppc (car (line))) ("H" (setq Max Guess)) ("L" (setq Min Guess)) ("=" (nil (prinl "I did it!"))) (T (prinl "I do not understand that...")) ) ) ) ) )
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the scorer scores, in turn, until the computer correctly guesses the target number. The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm. Related tasks   Guess the number/With Feedback   Bulls and cows/Player
#Prolog
Prolog
min(1). max(10).   pick_number(Min, Max) :- min(Min), max(Max), format('Pick a number between ~d and ~d, and I will guess it...~nReady? (Enter anything when ready):', [Min, Max]), read(_).   guess_number(Min, Max) :- Guess is (Min + Max) // 2, format('I guess ~d...~nAm I correct (c), too low (l), or too high (h)? ', [Guess]), repeat, read(Score), ( Score = l -> NewMin is Guess + 1, guess_number(NewMin, Max) ; Score = h -> NewMax is Guess - 1, guess_number(Min, NewMax) ; Score = c -> writeln('I am correct!') ; writeln('Invalid input'), false ).   play :- pick_number(Min, Max), guess_number(Min, Max).
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#Erlang
Erlang
-module(tasks). -export([main/0]). -import(lists, [map/2, member/2, sort/1, sum/1]).   is_happy(X, XS) -> if X == 1 -> true; X < 1 -> false; true -> case member(X, XS) of true -> false; false -> is_happy(sum(map(fun(Z) -> Z*Z end, [Y - 48 || Y <- integer_to_list(X)])), [X|XS]) end end.   main(X, XS) -> if length(XS) == 8 -> io:format("8 Happy Numbers: ~w~n", [sort(XS)]); true -> case is_happy(X, []) of true -> main(X + 1, [X|XS]); false -> main(X + 1, XS) end end. main() -> main(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, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles". Task Implement a great-circle distance function, or use a library function, to show the great-circle distance between: Nashville International Airport (BNA)   in Nashville, TN, USA,   which is: N 36°7.2', W 86°40.2' (36.12, -86.67) -and- Los Angeles International Airport (LAX)  in Los Angeles, CA, USA,   which is: N 33°56.4', W 118°24.0' (33.94, -118.40) User Kaimbridge clarified on the Talk page: -- 6371.0 km is the authalic radius based on/extracted from surface area; -- 6372.8 km is an approximation of the radius of the average circumference (i.e., the average great-elliptic or great-circle radius), where the boundaries are the meridian (6367.45 km) and the equator (6378.14 km). Using either of these values results, of course, in differing distances: 6371.0 km -> 2886.44444283798329974715782394574671655 km; 6372.8 km -> 2887.25995060711033944886005029688505340 km; (results extended for accuracy check: Given that the radii are only approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km, practical precision required is certainly no greater than about .0000001——i.e., .1 mm!) As distances are segments of great circles/circumferences, it is recommended that the latter value (r = 6372.8 km) be used (which most of the given solutions have already adopted, anyways). Most of the examples below adopted Kaimbridge's recommended value of 6372.8 km for the earth radius. However, the derivation of this ellipsoidal quadratic mean radius is wrong (the averaging over azimuth is biased). When applying these examples in real applications, it is better to use the mean earth radius, 6371 km. This value is recommended by the International Union of Geodesy and Geophysics and it minimizes the RMS relative error between the great circle and geodesic distance.
#Perl
Perl
use ntheory qw/Pi/;   sub asin { my $x = shift; atan2($x, sqrt(1-$x*$x)); }   sub surfacedist { my($lat1, $lon1, $lat2, $lon2) = @_; my $radius = 6372.8; my $radians = Pi() / 180;; my $dlat = ($lat2 - $lat1) * $radians; my $dlon = ($lon2 - $lon1) * $radians; $lat1 *= $radians; $lat2 *= $radians; my $a = sin($dlat/2)**2 + cos($lat1) * cos($lat2) * sin($dlon/2)**2; my $c = 2 * asin(sqrt($a)); return $radius * $c; } my @BNA = (36.12, -86.67); my @LAX = (33.94, -118.4); printf "Distance: %.3f km\n", surfacedist(@BNA, @LAX);
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
#GlovePIE
GlovePIE
debug="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/procedure to generate successive members of the Harshad sequence. Use it to:   list the first 20 members of the sequence,   and   list the first Harshad number greater than 1000. Show your output here. Related task   Increasing gaps between consecutive Niven numbers See also   OEIS: A005349
#PL.2FM
PL/M
100H:   /* FIND THE SUM OF THE DIGITS OF A 16-BIT NUMBER */ DIGIT$SUM: PROCEDURE(N) BYTE; DECLARE N ADDRESS, SUM BYTE; SUM = 0; DO WHILE N > 0; SUM = SUM + (N MOD 10); N = N / 10; END; RETURN SUM; END DIGIT$SUM;   /* FIND THE NEXT HARSHAD NUMBER ABOVE N */ NEXT$HARSHAD: PROCEDURE(N) ADDRESS; DECLARE N ADDRESS; NEXT: N = N + 1; IF N MOD DIGIT$SUM(N) = 0 THEN RETURN N; ELSE GO TO NEXT; END NEXT$HARSHAD;   /* CP/M SYSCALL */ BDOS: PROCEDURE(FUNC, ARG); DECLARE FUNC BYTE, ARG ADDRESS; GO TO 5; END BDOS;   /* PRINT A STRING */ PRINT$STRING: PROCEDURE(STRING); DECLARE STRING ADDRESS; CALL BDOS(9, STRING); END PRINT$STRING;   /* PRINT A NUMBER */ PRINT$NUMBER: PROCEDURE(N); DECLARE S (7) BYTE INITIAL ('..... $'); DECLARE (N, P) ADDRESS, (C BASED P) BYTE; P = .S(5); DIGIT: P = P - 1; C = (N MOD 10) + '0'; N = N / 10; IF N > 0 THEN GO TO DIGIT; CALL PRINT$STRING(P); END PRINT$NUMBER;   DECLARE CRLF DATA (13,10,'$'); DECLARE N ADDRESS INITIAL (0), S BYTE;   /* PRINT FIRST 20 HARSHADS */ CALL PRINT$STRING(.'FIRST 20: $'); DO S = 1 TO 20; CALL PRINT$NUMBER(N := NEXT$HARSHAD(N)); END; CALL PRINT$STRING(.CRLF);   /* PRINT HARSHAD NUMBER ABOVE 1000 */ CALL PRINT$STRING(.'FIRST ABOVE 1000: $'); CALL PRINT$NUMBER(NEXT$HARSHAD(1000)); CALL PRINT$STRING(.CRLF);   CALL BDOS(0,0); EOF
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
#Liberty_BASIC
Liberty BASIC
NOTICE "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
#Lingo
Lingo
_player.alert("Goodbye, World!")
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dialogs to query the user for further information Task For a minimal "application", write a program that presents a form with three components to the user: a numeric input field ("Value") a button ("increment") a button ("random") The field is initialized to zero. The user may manually enter a new value into the field, or increment its value with the "increment" button. Entering a non-numeric value should be either impossible, or issue an error message. Pressing the "random" button presents a confirmation dialog, and resets the field's value to a random value if the answer is "Yes". (This task may be regarded as an extension of the task Simple windowed application).
#Vala
Vala
bool validate_input(Gtk.Window window, string str){ int64 val; bool ret = int64.try_parse(str,out val);;   if(!ret){ var dialog = new Gtk.MessageDialog(window, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, "Invalid value"); dialog.run(); dialog.destroy(); } return ret; }     int main (string[] args) { Gtk.init (ref args);   var window = new Gtk.Window(); window.title = "Rosetta Code"; window.window_position = Gtk.WindowPosition.CENTER; window.destroy.connect(Gtk.main_quit); window.set_default_size(0,0);     var box = new Gtk.Box(Gtk.Orientation.HORIZONTAL, 1); box.set_border_width(1);     var label = new Gtk.Label ("Value:");     var entry = new Gtk.Entry(); entry.set_text("0"); //initialize to zero entry.activate.connect (() => { // read and validate the entered value validate_input(window, entry.get_text()); });     // button to increment var ib = new Gtk.Button.with_label("increment"); ib.clicked.connect(() => { // read and validate the entered value var str = entry.get_text(); if(validate_input(window, str)){ entry.set_text((int.parse(str)+1).to_string()); } });     // button to put in a random value if confirmed var rb = new Gtk.Button.with_label("random"); rb.clicked.connect (() => { var dialog = new Gtk.MessageDialog(window, Gtk.DialogFlags.MODAL, Gtk.MessageType.QUESTION, Gtk.ButtonsType.YES_NO, "set random value"); var answer = dialog.run(); dialog.destroy(); if(answer == Gtk.ResponseType.YES){ entry.set_text(Random.int_range(0,10000).to_string()); } });     box.pack_start(label, false, false, 2); box.pack_start(entry, false, false, 2); box.pack_start(ib, false, false, 2); box.pack_start(rb, false, false, 2);   window.add(box);   window.show_all();   Gtk.main (); return 0; }  
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] Reference Converting Between Gray and Binary Codes. It includes step-by-step animations.
#C.2B.2B
C++
  #include <bitset> #include <iostream> #include <string> #include <assert.h>   uint32_t gray_encode(uint32_t b) { return b ^ (b >> 1); }   uint32_t gray_decode(uint32_t g) { for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1) { if (g & bit) g ^= bit >> 1; } return g; }   std::string to_binary(int value) // utility function { const std::bitset<32> bs(value); const std::string str(bs.to_string()); const size_t pos(str.find('1')); return pos == std::string::npos ? "0" : str.substr(pos); }   int main() { std::cout << "Number\tBinary\tGray\tDecoded\n"; for (uint32_t n = 0; n < 32; ++n) { uint32_t g = gray_encode(n); assert(gray_decode(g) == n);   std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n"; } }
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#Clojure
Clojure
(use '[clojure.java.shell :only [sh]]) (sh "echo" "Hello")
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#Common_Lisp
Common Lisp
(trivial-shell:shell-command "uname -imp")
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#D
D
import std.process; import std.stdio;   void main() { auto cmd = executeShell("echo hello");   if (cmd.status == 0) { writeln("Output: ", cmd.output); } else { writeln("Failed to execute command, status=", cmd.status); } }
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#68000_Assembly
68000 Assembly
EXG D0,D1 ;swap the contents of D0 and D1 EXG A0,A1 ;swap the contents of A0 and A1
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.
#Applesoft_BASIC
Applesoft BASIC
100 REMMAX 110 R$ = "":E$ = "" 120 L = LEN (L$) 130 IF L = 0 THEN RETURN 140 FOR I = 1 TO L 150 C$ = MID$ (L$,I,1) 160 SP = C$ = " " 170 IF SP THEN GOSUB 200 180 E$ = E$ + C$ 190 NEXT I 200 C$ = "" 210 IF E$ = "" THEN RETURN 220 V = VAL (E$):V$ = R$ 230 E$ = "":E = V$ = "" 240 IF E AND V = 0 THEN RETURN 250 R$ = STR$ (V) 260 IF E THEN RETURN 270 R = VAL (V$) 280 IF R < V THEN RETURN 290 R$ = V$: RETURN