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/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.
#Ada
Ada
with Ada.Text_Io; use Ada.Text_Io;   procedure Gcd_Test is function Gcd (A, B : Integer) return Integer is M : Integer := A; N : Integer := B; T : Integer; begin while N /= 0 loop T := M; M := N; N := T mod N; end loop; return M; end Gcd;   begin Put_Line("GCD of 100, 5 is" & Integer'Image(Gcd(100, 5))); Put_Line("GCD of 5, 100 is" & Integer'Image(Gcd(5, 100))); Put_Line("GCD of 7, 23 is" & Integer'Image(Gcd(7, 23))); end Gcd_Test;
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.
#D
D
import std.file, std.array;   void main() { auto from = "Goodbye London!", to = "Hello, New York!"; foreach (fn; "a.txt b.txt c.txt".split()) { write(fn, replace(cast(string)read(fn), from, to)); } }
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.
#Delphi
Delphi
  program Globally_replace_text_in_several_files;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.IoUtils;   procedure StringReplaceByFile(_old, _new: string; FileName: TFilename; ReplaceFlags: TReplaceFlags = []); overload var Text: string; begin if not FileExists(FileName) then exit; Text := TFile.ReadAllText(FileName); TFile.Delete(FileName); TFile.WriteAllText(StringReplace(Text, _old, _new, ReplaceFlags), FileName); end;   procedure StringReplaceByFile(_old, _new: string; FileNames: TArray<TFileName>; ReplaceFlags: TReplaceFlags = []); overload; begin for var fn in FileNames do StringReplaceByFile(_old, _new, fn); end;   begin StringReplaceByFile('Goodbye London!', 'Hello New York!', ['a.txt', 'b.txt', 'c.txt']); end.
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).
#APL
APL
  ⍝ recursive dfn: dfnHailstone←{ c←⊃⌽⍵ ⍝ last element 1=c:1 ⍝ if it is 1, stop. ⍵,∇(1+2|c)⊃(c÷2)(1+3×c) ⍝ otherwise pick the next step, and append the result of the recursive call }   ⍝ tradfn version: ∇seq←hailstone n;next ⍝ Returns the hailstone sequence for a given number   seq←n ⍝ Init the sequence :While n≠1 next←(n÷2) (1+3×n) ⍝ Compute both possibilities n←next[1+2|n] ⍝ Pick the appropriate next step seq,←n ⍝ Append that to the sequence :EndWhile ∇    
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.
#Julia
Julia
  using Color, Images, FixedPointNumbers   const M_RGB_Y = reshape(Color.M_RGB_XYZ[2,:], 3)   function rgb2gray(img::Image) g = red(img)*M_RGB_Y[1] + green(img)*M_RGB_Y[2] + blue(img)*M_RGB_Y[3] g = clamp(g, 0.0, 1.0) return grayim(g) end   function gray2rgb(img::Image) colorspace(img) == "Gray" || return img g = map((x)->RGB{Ufixed8}(x, x, x), img.data) return Image(g, spatialorder=spatialorder(img)) end   ima = imread("grayscale_image_color.png") imb = rgb2gray(ima) imc = gray2rgb(imb) imwrite(imc, "grayscale_image_rc.png")  
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.
#Kotlin
Kotlin
// version 1.2.10   import java.io.File import java.awt.image.BufferedImage import javax.imageio.ImageIO   fun BufferedImage.toGrayScale() { for (x in 0 until width) { for (y in 0 until height) { var argb = getRGB(x, y) val alpha = (argb shr 24) and 0xFF val red = (argb shr 16) and 0xFF val green = (argb shr 8) and 0xFF val blue = argb and 0xFF val lumin = (0.2126 * red + 0.7152 * green + 0.0722 * blue).toInt() argb = (alpha shl 24) or (lumin shl 16) or (lumin shl 8) or lumin setRGB(x, y, argb) } } }   fun main(args: Array<String>) { val image = ImageIO.read(File("bbc.jpg")) // using BBC BASIC image image.toGrayScale() val grayFile = File("bbc_gray.jpg") ImageIO.write(image, "jpg", grayFile) }
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
#Lua
Lua
#!/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).
#DCL
DCL
$ limit = p1 $ $ n = 0 $ h_'n = 1 $ x2 = 2 $ x3 = 3 $ x5 = 5 $ i = 0 $ j = 0 $ k = 0 $ $ n = 1 $ loop: $ x = x2 $ if x3 .lt. x then $ x = x3 $ if x5 .lt. x then $ x = x5 $ h_'n = x $ if x2 .eq. h_'n $ then $ i = i + 1 $ x2 = 2 * h_'i $ endif $ if x3 .eq. h_'n $ then $ j = j + 1 $ x3 = 3 * h_'j $ endif $ if x5 .eq. h_'n $ then $ k = k + 1 $ x5 = 5 * h_'k $ endif $ n = n + 1 $ if n .le. limit then $ goto loop $ $ i = 0 $ loop2: $ write sys$output h_'i $ i = i + 1 $ if i .lt. 20 then $ goto loop2 $ $ n = limit - 1 $ write sys$output h_'n
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#Gambas
Gambas
Public Sub Form_Open() Dim byGuess, byGos As Byte Dim byNo As Byte = Rand(1, 10) Dim sHead As String = "Guess the number"   Repeat Inc byGos byGuess = InputBox("Guess the number between 1 and 10", sHead) sHead = "Sorry, have another go" Until byGuess = byNo   Message.Info("Well guessed! You took " & Str(byGos) & " gos to guess the number was " & Str(byNo), "OK") Me.Close   End
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#GML
GML
var n, g; n = irandom_range(1,10); show_message("I'm thinking of a number from 1 to 10"); g = get_integer("Please enter guess", 1); while(g != n) { g = get_integer("I'm sorry "+g+" is not my number, try again. Please enter guess", 1); } show_message("Well guessed!");
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#Factor
Factor
USING: kernel locals math math.order sequences ;   :: max-with-index ( elt0 ind0 elt1 ind1 -- elt ind ) elt0 elt1 < [ elt1 ind1 ] [ elt0 ind0 ] if ; : last-of-max ( accseq -- ind ) -1 swap -1 [ max-with-index ] reduce-index nip ;   : max-subseq ( seq -- subseq ) dup 0 [ + 0 max ] accumulate swap suffix last-of-max head dup 0 [ + ] accumulate swap suffix [ neg ] map last-of-max tail ;
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.
#Forth
Forth
2variable best variable best-sum   : sum ( array len -- sum ) 0 -rot cells over + swap do i @ + cell +loop ;   : max-sub ( array len -- sub len ) over 0 best 2! 0 best-sum ! dup 1 do \ foreach length 2dup i - 1+ cells over + swap do \ foreach start i j sum dup best-sum @ > if best-sum ! i j best 2! else drop then cell +loop loop 2drop best 2@ ;   : .array ." [" dup 0 ?do over i cells + @ . loop ." ] = " sum . ;   create test -1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1 , create test2 -1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , 99 ,
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)
#EasyLang
EasyLang
print "Guess a number between 1 and 100!" n = random 100 + 1 repeat g = number input write g if error = 1 print "You must enter a number!" elif g > n print " is too high" elif g < n print " is too low" . until g = n . print " is correct"
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.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations int Q, N, W, B, C, Y; [SetVid($112); \640x480x24 graphics for Q:= 0 to 4-1 do \quarter of screen [N:= 8<<Q; \number of bars W:= 640/N; \width of bar (pixels) for B:= 0 to N-1 do \for each bar... [C:= fix(255.0/float(N-1) * float(if Q&1 then N-1-B else B)); C:= C<<16 + C<<8 + C; \RGB color = gray for Y:= Q*120 to (Q+1)*120-1 do [Move(W*B, Y); Line(W*(B+1)-1, Y, C)]; ]; ]; Q:= ChIn(1); \wait for keystroke SetVid(3); \restore normal text mode ]
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.
#Yabasic
Yabasic
open window 1024, 600 w = peek("winwidth") h = peek("winheight") rows = 4 hd = int(h / rows) mitad = 0     for row = 1 to rows if not mitad then wd = int(w / (8 * row)) mitad = wd else mitad = mitad / 2 end if c = 255 / (w / mitad) for n = 0 to (w / mitad) color 255 - c * n, 255 - c * n, 255 - c * n if mod(row, 2) = 0 color c * n, c * n, c * n fill rectangle mitad * n, hd * (row - 1), mitad * (n+1), hd * row pause .1 next n next row
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.
#zkl
zkl
img:=PPM(640,480); foreach q in ([0..3]){ //quarter of screen n:=(8).shiftLeft(q); //number of bars w:=640/n; //width of bar (pixels) foreach b in ([0..n-1]){ //for each bar... c:=(255.0/(n-1).toFloat() * (if(q.isOdd) n-1-b else b)).toInt(); c:=c.shiftLeft(16) + c.shiftLeft(8) + c; //RGB color = gray foreach y in ([(3-q)*120 .. (3-q+1)*120-1]){ // flip image vertically img.line(w*b,y, w*(b+1)-1,y, c); } } } img.write(File("foo.ppm","wb"));
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
#PureBasic
PureBasic
min=0 max=100   If OpenConsole() PrintN("Think of a number between "+Str(min)+" and "+Str(max)+".") PrintN("On every guess of mine you should state whether my guess was") PrintN("too high, too low, or equal to your number by typing 'h', 'l', Or '='") Repeat If max<=min PrintN("I think somthing is strange here...") Break EndIf Guess=(max-min)/2+min Print("My guess is "+Str(Guess)+",is this correct? "): Respons.s=UCase(Input()) If Respons="H": max=Guess-1 ElseIf Respons="L": min=Guess+1 ElseIf Respons="=" PrintN("I did it!") Break Else PrintN("I do not understand that...") EndIf ForEver EndIf
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
#Euphoria
Euphoria
function is_happy(integer n) sequence seen integer k seen = {} while n > 1 do seen &= n k = 0 while n > 0 do k += power(remainder(n,10),2) n = floor(n/10) end while n = k if find(n,seen) then return 0 end if end while return 1 end function   integer n,count n = 1 count = 0 while count < 8 do if is_happy(n) then ? n count += 1 end if n += 1 end while
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.
#Phix
Phix
function haversine(atom lat1, long1, lat2, long2) constant MER = 6371, -- mean earth radius(km) DEG_TO_RAD = PI/180 lat1 *= DEG_TO_RAD lat2 *= DEG_TO_RAD long1 *= DEG_TO_RAD long2 *= DEG_TO_RAD return MER*arccos(sin(lat1)*sin(lat2)+cos(lat1)*cos(lat2)*cos(long2-long1)) end function atom d = haversine(36.12,-86.67,33.94,-118.4) printf(1,"Distance is %f km (%f miles)\n",{d,d/1.609344})
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
#GML
GML
show_message("Hello world!"); // displays a pop-up message show_debug_message("Hello world!"); // sends text to the debug log or IDE
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
#PowerShell
PowerShell
  1..1000 | Where { $_ % ( [int[]][string[]][char[]][string]$_ | Measure -Sum ).Sum -eq 0 } | Select -First 20 1001..2000 | Where { $_ % ( [int[]][string[]][char[]][string]$_ | Measure -Sum ).Sum -eq 0 } | Select -First 1  
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
#xTalk
xTalk
answer "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
#Lobster
Lobster
gl_window("graphical hello world", 800, 600) gl_setfontname("data/fonts/Droid_Sans/DroidSans.ttf") gl_setfontsize(30)   while gl_frame(): gl_clear([ 0.0, 0.0, 0.0, 1.0 ]) gl_text("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).
#Visual_Basic
Visual Basic
VERSION 5.00 Begin VB.Form Form1 Caption = "Form1" ClientHeight = 2265 ClientLeft = 60 ClientTop = 600 ClientWidth = 2175 LinkTopic = "Form1" ScaleHeight = 2265 ScaleWidth = 2175 StartUpPosition = 3 'Windows Default Begin VB.CommandButton cmdRnd Caption = "Random" Height = 495 Left = 120 TabIndex = 2 Top = 1680 Width = 1215 End Begin VB.CommandButton cmdInc Caption = "Increment" Height = 495 Left = 120 TabIndex = 1 Top = 1080 Width = 1215 End Begin VB.TextBox txtValue Height = 495 Left = 120 TabIndex = 0 Text = "0" Top = 240 Width = 1215 End End Attribute VB_Name = "Form1" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False '-----user-written code begins here; everything above this line is hidden in the IDE----- Private Sub Form_Load() Randomize Timer End Sub   Private Sub cmdRnd_Click() If MsgBox("Random?", vbYesNo) Then txtValue.Text = Int(Rnd * 11) End Sub   Private Sub cmdInc_Click() If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1 End Sub   Private Sub txtValue_KeyPress(KeyAscii As Integer) Select Case KeyAscii Case 8, 43, 45, 48 To 57 'backspace, +, -, or number Case Else KeyAscii = 0 End Select End Sub
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).
#Web_68
Web 68
@1Rosetta code program. @aPROGRAM guicomponent CONTEXT VOID USE standard BEGIN @<Included declarations@> @<Modes in the outer reach@> @<Names in the outer reach@> @<Callback procedures@> @<Other routines@> @<Main logic@> END FINISH   @ This file contains all the macros for the Xforms library procedures. Only macros which are called will actually generate code.   @iforms.w@>   @ Initialise the Xforms library, create the form, set the value in the input field, show the form and hand control to the Xforms library.   @<Main...@>= open(argf,"",arg channel); fl initialize(argc,argv,"GUI interact",NIL,0); main form:=create form main; fl set input(main input OF main form,float(value,10,5,2)); fl show form(main OF main form,fl place center,fl fullborder,"GUI interact"); fl do forms   @ The input value will be stored in !value!.   @<Names...@>= REF FDMAIN main form; REAL value:=0; FILE argf;   @1The form. The following section contains declarations for the form. It was output by the program 'fdtow68' using the file output by the 'fdesign' program.   @2Modes. This is the mode declaration for form !main!.   @<Modes...@>= MODE FDMAIN = STRUCT( REF FLFORM main, REF FLOBJECT main increment, REF FLOBJECT main input, REF FLOBJECT main random);   @ This procedure creates form !main!.   @<Other...@>= PROC create form main = REF FDMAIN: BEGIN REF FLOBJECT obj; REF FDMAIN fdui:=HEAP FDMAIN; OP(REF FDMAIN)CBPTR TOCBPTR = BIOP 99; main OF fdui:=fl bgn form(fl no box,259,126); obj:=fl add box(fl up box,0,0,259,126,""); fl set object color(obj,fl col1,fl col1); main input OF fdui:=obj:=fl add input(fl float input,78,18,160,35,"Value"); fl set object lsize(obj,fl normal size); fl set object callback(obj,main cb,1); fl set object return(obj,fl return end changed); main increment OF fdui:=obj:=fl add button(fl normal button,20,70,100,40,"Increment"); fl set object lsize(obj,fl normal size); fl set object callback(obj,main cb,2); fl set button mouse buttons(obj,BIN 7); main random OF fdui:=obj:=fl add button(fl normal button,140,70,100,40,"Random"); fl set object lsize(obj,fl normal size); fl set object callback(obj,main cb,3); fl set button mouse buttons(obj,BIN 7); fl end form; fl adjust form size(main OF fdui); fdui OF main OF fdui:=TOCBPTR fdui; fdui END; #create form main#   @2Callback procedures. There is only one callback procedure.   @<Callback...@>= PROC main cb = (REF FLOBJECT obj,INT data)VOID: CASE data IN #input# BEGIN FILE mf; open(mf,fl get input(main input OF main form)+blank,mem channel); get(mf,value); #convert the input to binary# close(mf) END , #increment# ( value +:= 1; fl set input(main input OF main form,float(value,10,5,2)) ) , #random# ( value:=random; fl set input(main input OF main form,float(value,10,5,2)) ) ESAC; #main cb#   @2Macro calls. Here are all the Xforms macro calls in alphabetical order.   @<Include...@>= macro fl add box; macro fl add button; macro fl add input; macro fl adjust form size; macro fl bgn form; macro fl do forms; macro fl end form; macro fl get border width; macro fl get input; macro fl initialize; macro fl set border width; macro fl set button mouse buttons; macro fl set input; macro fl set object callback; macro fl set object color; macro fl set object lsize; macro fl set object return; macro fl show form;   @ The 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.
#CoffeeScript
CoffeeScript
  gray_encode = (n) -> n ^ (n >> 1)   gray_decode = (g) -> n = g n ^= g while g >>= 1 n   for i in [0..32] console.log gray_decode gray_encode(i)  
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.
#Common_Lisp
Common Lisp
(defun gray-encode (n) (logxor n (ash n -1)))   (defun gray-decode (n) (do ((p n (logxor p n))) ((zerop n) p) (setf n (ash n -1))))   (loop for i to 31 do (let* ((g (gray-encode i)) (b (gray-decode g))) (format t "~2d:~6b =>~6b =>~6b :~2d~%" i i g b b)))
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
#F.23
F#
  // System Command Output. Nigel Galloway: October 6th., 2020 let n=new System.Diagnostics.Process(StartInfo=System.Diagnostics.ProcessStartInfo(RedirectStandardOutput=true,RedirectStandardError=true,UseShellExecute=false, FileName= @"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\Common7\IDE\CommonExtensions\Microsoft\FSharp\fsc.exe",Arguments="--help")) n.Start() printfn "%s" ((n.StandardOutput).ReadToEnd()) n.Close()  
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
#Factor
Factor
USING: io.encodings.utf8 io.launcher ; "echo hello" utf8 [ contents ] with-process-reader .
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
#Forth
Forth
s" ps " system \ Output only \ read via pipe into buffer create buffer 266 allot s" ps " r/o open-pipe throw dup buffer swap 256 swap read-file throw swap close-pipe throw drop   buffer swap type \ output is the same like above  
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!
#8086_Assembly
8086 Assembly
xchg ax,bx ;exchanges ax with bx   xchg ah,al ;swap the high and low bytes of ax     ;XCHG a register with memory mov dx,0FFFFh mov word ptr [ds:userRam],dx mov si,offset userRam mov ax,1234h xchg ax,[si] ;exchange ax with the value stored at userRam. Now, ax = 0FFFFh and the value stored at userRam = 1234h     ;XCHG a register with a value on the stack. mov ax,1234h mov bx,4567h push bx push bp mov bp,sp ;using [sp] as an operand for XCHG will not work. You need to use bp instead.   xchg ax,[2+bp] ;exchanges AX with the value that was pushed from BX onto the stack. Now, AX = 4567h, ;and the entry on the stack just underneath the top of the stack is 1234h.
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.
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program rechMax.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall   /*********************************/ /* Initialized data */ /*********************************/ .data szMessResult: .ascii "Max number is = " @ message result sMessValeur: .fill 12, 1, ' ' .ascii " rank = " sMessRank: .fill 12, 1, ' ' .ascii " address (hexa) = " sMessAddress: .fill 12, 1, ' ' .asciz "\n"   tTableNumbers: .int 50 .int 12 .int -1000 .int 40 .int 255 .int 60 .int 254 .equ NBRANKTABLE, (. - tTableNumbers) / 4 @ number table posts   /*********************************/ /* UnInitialized data */ /*********************************/ .bss /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program push {fp,lr} @ saves 2 registers   ldr r1,iAdrtTableNumbers mov r2,#0 ldr r4,[r1,r2,lsl #2] mov r3,r2 add r2,#1 1: cmp r2,#NBRANKTABLE bge 2f ldr r0,[r1,r2,lsl #2] cmp r0,r4 movgt r4,r0 movgt r3,r2 add r2,#1 b 1b   2: mov r0,r4 ldr r1,iAdrsMessValeur bl conversion10S @ call conversion mov r0,r3 ldr r1,iAdrsMessRank bl conversion10 @ call conversion ldr r0,iAdrtTableNumbers add r0,r3,lsl #2 ldr r1,iAdrsMessAddress bl conversion16 @ call conversion ldr r0,iAdrszMessResult bl affichageMess @ display message         100: @ standard end of the program mov r0, #0 @ return code pop {fp,lr} @restaur 2 registers mov r7, #EXIT @ request to exit program swi 0 @ perform the system call iAdrtTableNumbers: .int tTableNumbers iAdrsMessValeur: .int sMessValeur iAdrsMessRank: .int sMessRank iAdrsMessAddress: .int sMessAddress iAdrszMessResult: .int szMessResult   /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {fp,lr} /* save registres */ push {r0,r1,r2,r7} /* save others registers */ mov r2,#0 /* counter length */ 1: /* loop length calculation */ ldrb r1,[r0,r2] /* read octet start position + index */ cmp r1,#0 /* if 0 its over */ addne r2,r2,#1 /* else add 1 in the length */ bne 1b /* and loop */ /* so here r2 contains the length of the message */ mov r1,r0 /* address message in r1 */ mov r0,#STDOUT /* code to write to the standard output Linux */ mov r7, #WRITE /* code call system "write" */ swi #0 /* call systeme */ pop {r0,r1,r2,r7} /* restaur others registers */ pop {fp,lr} /* restaur des 2 registres */ bx lr /* return */ /******************************************************************/ /* Converting a register to hexadecimal */ /******************************************************************/ /* r0 contains value and r1 address area */ conversion16: push {r1-r4,lr} /* save registers */ mov r2,#28 @ start bit position mov r4,#0xF0000000 @ mask mov r3,r0 @ save entry value 1: @ start loop and r0,r3,r4 @value register and mask lsr r0,r2 @ move right cmp r0,#10 @ compare value addlt r0,#48 @ <10 ->digit addge r0,#55 @ >10 ->letter A-F strb r0,[r1],#1 @ store digit on area and + 1 in area address lsr r4,#4 @ shift mask 4 positions subs r2,#4 @ counter bits - 4 <= zero  ? bge 1b @ no -> loop @end pop {r1-r4,lr} @ restaur registres bx lr @return /******************************************************************/ /* Converting a register to a decimal */ /******************************************************************/ /* r0 contains value and r1 address area */ conversion10: push {r1-r4,lr} /* save registers */ mov r3,r1 mov r2,#10   1: @ start loop bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1 add r1,#48 @ digit strb r1,[r3,r2] @ store digit on area sub r2,#1 @ previous position cmp r0,#0 @ stop if quotient = 0 */ bne 1b @ else loop @ and move spaves in first on area mov r1,#' ' @ space 2: strb r1,[r3,r2] @ store space in area subs r2,#1 @ @ previous position bge 2b @ loop if r2 >= zéro   100: pop {r1-r4,lr} @ restaur registres bx lr @return /***************************************************/ /* Converting a register to a signed decimal */ /***************************************************/ /* r0 contains value and r1 area address */ conversion10S: push {r0-r4,lr} @ save registers mov r2,r1 /* debut zone stockage */ mov r3,#'+' /* par defaut le signe est + */ cmp r0,#0 @ negative number ? movlt r3,#'-' @ yes mvnlt r0,r0 @ number inversion addlt r0,#1 mov r4,#10 @ length area 1: @ start loop bl divisionpar10 add r1,#48 @ digit strb r1,[r2,r4] @ store digit on area sub r4,r4,#1 @ previous position cmp r0,#0 @ stop if quotient = 0 bne 1b   strb r3,[r2,r4] @ store signe subs r4,r4,#1 @ previous position blt 100f @ if r4 < 0 -> end   mov r1,#' ' @ space 2: strb r1,[r2,r4] @store byte space subs r4,r4,#1 @ previous position bge 2b @ loop if r4 > 0 100: pop {r0-r4,lr} @ restaur registers bx lr /***************************************************/ /* division par 10 signé */ /* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/* /* and http://www.hackersdelight.org/ */ /***************************************************/ /* r0 dividende */ /* r0 quotient */ /* r1 remainder */ divisionpar10: /* r0 contains the argument to be divided by 10 */ push {r2-r4} /* save registers */ mov r4,r0 ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */ smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */ mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */ mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */ add r0, r2, r1 /* r0 <- r2 + r1 */ add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */ sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */ pop {r2-r4} bx lr /* leave function */ .align 4 .Ls_magic_number_10: .word 0x66666667      
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.
#Aime
Aime
o_integer(gcd(33, 77)); o_byte('\n'); o_integer(gcd(49865, 69811)); o_byte('\n');
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.
#Erlang
Erlang
  -module( globally_replace_text ).   -export( [in_files/3, main/1] ).   in_files( Old, New, Files ) when is_list(Old) -> in_files( binary:list_to_bin(Old), binary:list_to_bin(New), Files ); in_files( Old, New, Files ) -> [replace_in_file(Old, New, X, file:read_file(X)) || X <- Files].   main( [Old, New | Files] ) -> in_files( Old, New, Files ).       replace_in_file( Old, New, File, {ok, Binary} ) -> replace_in_file_return( File, file:write_file(File, binary:replace(Binary, Old, New, [global])) ); replace_in_file( _Old, _New, File, {error, Error} ) -> io:fwrite( "Error: Could not read ~p: ~p~n", [File, Error] ), error.   replace_in_file_return( _File, ok ) -> ok; replace_in_file_return( File, {error, Error} ) -> io:fwrite( "Error: Could not write ~p: ~p~n", [File, Error] ), error.  
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).
#AppleScript
AppleScript
on hailstoneSequence(n) script o property sequence : {n} end script   repeat until (n = 1) if (n mod 2 is 0) then set n to n div 2 else set n to 3 * n + 1 end if set end of o's sequence to n end repeat   return o's sequence end hailstoneSequence   set n to 27 tell hailstoneSequence(n) return {n:n, |length of sequence|:(its length), |first 4 numbers|:items 1 thru 4, |last 4 numbers|:items -4 thru -1} end tell
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.
#Liberty_BASIC
Liberty BASIC
  nomainwin WindowWidth = 400 WindowHeight = 400 open "Bitmap" for graphics_nf_nsb as #1 h=hwnd(#1) calldll #user32, "GetDC", h as ulong, DC as ulong #1 "trapclose [q]" loadbmp "clr","MLcolor.bmp" #1 "drawbmp clr 1 1;flush" for x = 1 to 150 for y = 1 to 200 calldll #gdi32, "GetPixel", DC as ulong, x as long, y as long, PX as ulong B = int(PX/(256*256)) G = int((PX-B*256*256) / 256) R = int(PX-B*256*256-G*256) L = 0.2126*R+0.7152*G+0.0722*B #1 "down;color ";L;" ";L;" ";L;";set ";x;" ";y next y next x wait [q] unloadbmp "clr":close #1: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.
#Lingo
Lingo
on rgbToGrayscaleImageFast (img) res = image(img.width, img.height, 8) res.paletteRef = #grayScale res.copyPixels(img, img.rect, img.rect) return res end   on rgbToGrayscaleImageCustom (img) res = image(img.width, img.height, 8) res.paletteRef = #grayScale repeat with x = 0 to img.width-1 repeat with y = 0 to img.height-1 c = img.getPixel(x,y) n = c.red*0.2126 + c.green*0.7152 + c.blue*0.0722 res.setPixel(x,y, color(256-n)) end repeat end repeat return res end
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
#Locomotive_Basic
Locomotive Basic
#!/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).
#Delphi
Delphi
  note description : "Initial part, in order, of the sequence of Hamming numbers" math : "[ Hamming numbers, also known as regular numbers and 5-smooth numbers, are natural integers that have 2, 3 and 5 as their only prime factors. ]" computer_arithmetic : "[ This version avoids integer overflow and stops at the last representable number in the sequence. ]" output : "[ Per requirements of the RosettaCode example, execution will produce items of indexes 1 to 20 and 1691. The algorithm (procedure `hamming') is more general and will produce the first `n' Hamming numbers for any `n'. ]" source : "This problem was posed in Edsger W. Dijkstra, A Discipline of Programming, Prentice Hall, 1978" date : "8 August 2012" authors : "Bertrand Meyer", "Emmanuel Stapf" revision : "1.0" libraries : "Relies on SORTED_TWO_WAY_LIST from EiffelBase" implementation : "[ Using SORTED_TWO_WAY_LIST provides an elegant illustration of how to implement a lazy scheme in Eiffel through the use of object-oriented data structures. ]" warning : "[ The formatting (<lang>) specifications for Eiffel in RosettaCode are slightly obsolete: `note' and other newer keywords not supported, red color for manifest strings. This should be fixed soon. ]"   class APPLICATION   create make   feature {NONE} -- Initialization   make -- Print first 20 Hamming numbers, in order, and the 1691-st one. local Hammings: like hamming -- List of Hamming numbers, up to 1691-st one. do Hammings := hamming (1691) across 1 |..| 20 as i loop io.put_natural (Hammings.i_th (i.item)); io.put_string (" ") end io.put_new_line; io.put_natural (Hammings.i_th (1691)); io.put_new_line end   feature -- Basic operations   hamming (n: INTEGER): ARRAYED_LIST [NATURAL] -- First `n' elements (in order) of the Hamming sequence, -- or as many of them as will not produce overflow. local sl: SORTED_TWO_WAY_LIST [NATURAL] overflow: BOOLEAN first, next: NATURAL do create Result.make (n); create sl.make sl.extend (1); sl.start across 1 |..| n as i invariant -- "The numbers output so far are the first `i' - 1 Hamming numbers, in order". -- "Result.first is the `i'-th Hamming number." until sl.is_empty loop first := sl.first; sl.start Result.extend (first); sl.remove across << 2, 3, 5 >> as multiplier loop next := multiplier.item * first overflow := overflow or next <= first if not overflow and then not sl.has (next) then sl.extend (next) end end end end end  
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   func main() { fmt.Print("Guess number from 1 to 10: ") rand.Seed(time.Now().Unix()) n := rand.Intn(10) + 1 for guess := n; ; fmt.Print("No. Try again: ") { switch _, err := fmt.Scan(&guess); { case err != nil: fmt.Println("\n", err, "\nSo, bye.") return case guess == n: fmt.Println("Well guessed!") return } } }
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
#Groovy
Groovy
  def random = new Random() def keyboard = new Scanner(System.in) def number = random.nextInt(10) + 1 println "Guess the number which is between 1 and 10: " def guess = keyboard.nextInt() while (number != guess) { println "Guess again: " guess = keyboard.nextInt() } println "Hurray! You guessed correctly!"  
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.
#Fortran
Fortran
program MaxSubSeq implicit none   integer, parameter :: an = 11 integer, dimension(an) :: a = (/ -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 /)   integer, dimension(an,an) :: mix integer :: i, j integer, dimension(2) :: m   forall(i=1:an,j=1:an) mix(i,j) = sum(a(i:j)) m = maxloc(mix) ! a(m(1):m(2)) is the wanted subsequence print *, a(m(1):m(2))   end program MaxSubSeq
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)
#EchoLisp
EchoLisp
  ;;(read <default-value> <prompt>) prompts the user with a default value using the browser dialog box. ;; we play sounds to make this look like an arcade game (lib 'web) ; (play-sound) is defined in web.lib   (define (guess-feed (msg " 🔮 Enter a number in [0...100], -1 to stop.") (n (random 100)) (user 0)) (set! user (read user msg)) (play-sound 'ko) (unless (eq? n user ) ; user is the last user answer (guess-feed (cond ;; adapt prompt according to condition ((not (integer? user)) "❌ Please, enter an integer") (( < user 0) (error "🌵 - It was:" n)) ; exit to top level ((> n user) "Too low ...") ((< n user) "Too high ...")) n user)) (play-sound 'ok ) " 🔮 Well played!! 🍒 🍇 🍓")  
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.
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 REM wind the colour down or use a black and white television to see greyscale bars 20 REM The ZX Spectrum display is 32 columns wide, so we have 8 columns of 4 spaces 25 BORDER 0: CLS 30 FOR r=0 TO 21: REM There are 22 rows 40 FOR c=0 TO 7: REM We use the native colour sequence here 50 PRINT PAPER c;" ";: REM four spaces, the semicolon prevents newline 60 NEXT c 70 REM at this point the cursor has wrapped, so we don't need a newline 80 NEXT r
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
#Python
Python
inclusive_range = mn, mx = (1, 10)   print('''\ Think of a number between %i and %i and wait for me to guess it. On every guess of mine you should state whether the guess was too high, too low, or equal to your number by typing h, l, or = ''' % inclusive_range)   i = 0 while True: i += 1 guess = (mn+mx)//2 txt = input("Guess %2i is: %2i. The score for which is (h,l,=): "  % (i, guess)).strip().lower()[0] if txt not in 'hl=': print(" I don't understand your input of '%s' ?" % txt) continue if txt == 'h': mx = guess-1 if txt == 'l': mn = guess+1 if txt == '=': print(" Ye-Haw!!") break if (mn > mx) or (mn < inclusive_range[0]) or (mx > inclusive_range[1]): print("Please check your scoring as I cannot find the value") break   print("\nThanks for keeping score.")
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
#F.23
F#
open System.Collections.Generic open Microsoft.FSharp.Collections   let answer = let sqr x = x*x // Classic square definition let rec AddDigitSquare n = match n with | 0 -> 0 // Sum of squares for 0 is 0 | _ -> sqr(n % 10) + (AddDigitSquare (n / 10)) // otherwise add square of bottom digit to recursive call let dict = new Dictionary<int, bool>() // Dictionary to memoize values let IsHappy n = if dict.ContainsKey(n) then // If we've already discovered it dict.[n] // Return previously discovered value else let cycle = new HashSet<_>(HashIdentity.Structural) // Set to keep cycle values in let rec isHappyLoop n = if cycle.Contains n then n = 1 // If there's a loop, return true if it's 1 else cycle.Add n |> ignore // else add this value to the cycle isHappyLoop (AddDigitSquare n) // and check the next number in the cycle let f = isHappyLoop n // Keep track of whether we're happy or not cycle |> Seq.iter (fun i -> dict.[i] <- f) // and apply it to all the values in the cycle f // Return the boolean   1 // Starting with 1, |> Seq.unfold (fun i -> Some (i, i + 1)) // make an infinite sequence of consecutive integers |> Seq.filter IsHappy // Keep only the happy ones |> Seq.truncate 8 // Stop when we've found 8 |> Seq.iter (Printf.printf "%d\n") // Print results  
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.
#PHP
PHP
class POI { private $latitude; private $longitude;   public function __construct($latitude, $longitude) { $this->latitude = deg2rad($latitude); $this->longitude = deg2rad($longitude); }   public function getLatitude() { return $this->latitude; }   public function getLongitude() { return $this->longitude; }   public function getDistanceInMetersTo(POI $other) { $radiusOfEarth = 6371; // Earth's radius in kilometers.   $diffLatitude = $other->getLatitude() - $this->latitude; $diffLongitude = $other->getLongitude() - $this->longitude;   $a = sin($diffLatitude / 2) ** 2 + cos($this->latitude) * cos($other->getLatitude()) * sin($diffLongitude / 2) ** 2;   $c = 2 * asin(sqrt($a)); $distance = $radiusOfEarth * $c;   return $distance; } }
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
#Go
Go
package main   import "fmt"   func main() { fmt.Println("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
#Prolog
Prolog
:- use_module(library(lambda)).   niven :- nb_setval(go, 1),   L = [1 | _], print_niven(L, 1), gen_niven(1, L).     print_niven([X|T], N) :- when(ground(X), ( ( nb_getval(go, 1) -> ( N < 20 -> writeln(X), N1 is N+1, print_niven(T, N1) ; ( X > 1000 -> writeln(X), nb_setval(go, 0) ; N1 is N+1, print_niven(T, N1))) ; true))).       gen_niven(X, [N | T]) :- ( nb_getval(go, 1) -> X1 is X+1, sum_of_digit(X, S), ( X mod S =:= 0 -> N = X, gen_niven(X1, T) ; gen_niven(X1, [N | T])) ; true).     sum_of_digit(N, S) :- number_chars(N, LC), maplist(\X^Y^number_chars(Y, [X]), LC, LN), sum_list(LN, S).    
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Logo
Logo
LABEL [Hello, World!] SETLABELHEIGHT 2 * last LABELSIZE LABEL [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
#Lua
Lua
require "iuplua"   dlg = iup.dialog{iup.label{title="Goodbye, World!"}; title="test"} dlg:show()   if (not iup.MainLoopLevel or iup.MainLoopLevel()==0) then iup.MainLoop() 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).
#Wren
Wren
import "graphics" for Canvas, Color import "input" for Mouse, Keyboard import "dome" for Window import "random" for Random import "./polygon" for Polygon   var Rand = Random.new()   class Button { construct new(x, y, w, h, legend, c, oc, lc) { var vertices = [[x, y], [x+w, y], [x+w, y+h], [x, y+h]] _rect = Polygon.quick(vertices) _x = x _y = y _w = w _h = h _legend = legend _c = c _oc = oc _lc = lc }   draw() { _rect.drawfill(_c) _rect.draw(_oc) var l = Canvas.getPrintArea(_legend) var lx = ((_w - l.x)/2).truncate lx = (lx > 0) ? _x + lx : _x + 1 var ly = ((_h - l.y)/2).truncate ly = (ly > 0) ? _y + ly : _y + 1 Canvas.print(_legend, lx, ly, _lc) }   justClicked { Mouse["left"].justPressed && _rect.contains(Mouse.position.x, Mouse.position.y) } }   class TextBox { construct new(x, y, w, h, label, c, oc, lc) { var vertices = [[x, y], [x+w, y], [x+w, y+h], [x, y+h]] _rect = Polygon.quick(vertices) _x = x _y = y _w = w _h = h _label = label _c = c _oc = oc _lc = lc _text = "" }   text { _text } text=(t) { _text = t }   draw() { _rect.drawfill(_c) _rect.draw(_oc) var l = Canvas.getPrintArea(_label).x var lx = _x - l - 7 if (lx < 1) { lx = 1 _label = _label[0..._x] } Canvas.print(_label, lx, _y, _lc) Canvas.getPrintArea(_label).x Canvas.print(_text, _x + 3, _y + 1, Color.black) } }   class GUIComponentInteraction { construct new() { Window.title = "GUI component interaction" _btnIncrement = Button.new(60, 40, 80, 80, "Increment", Color.red, Color.blue, Color.white) _btnRandom = Button.new(180, 40, 80, 80, "Random", Color.green, Color.blue, Color.white) _txtValue = TextBox.new(140, 160, 80, 8, "Value", Color.white, Color.blue, Color.white) _txtValue.text = "0" Keyboard.handleText = true _waiting = false }   init() { drawControls() }   update() { if (_waiting) { if (Keyboard["Y"].justPressed) { var rn = Rand.int(1000) // max 999 say _txtValue.text = rn.toString _waiting = false } else if (Keyboard["N"].justPressed) { _waiting = false } } else if (_btnIncrement.justClicked) { var number = Num.fromString(_txtValue.text) + 1 _txtValue.text = number.toString } else if (_btnRandom.justClicked) { Canvas.print("Reset to a random number y/n?", 60, 200, Color.white) _waiting = true } else if ("0123456789".any { |d| Keyboard[d].justPressed }) { if (_txtValue.text != "0") { _txtValue.text = _txtValue.text + Keyboard.text } else { _txtValue.text = Keyboard.text } } }   draw(alpha) { if (!_waiting) drawControls() }   drawControls() { Canvas.cls() _btnIncrement.draw() _btnRandom.draw() _txtValue.draw() } }   var Game = GUIComponentInteraction.new()
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.
#Component_Pascal
Component Pascal
  MODULE GrayCodes; IMPORT StdLog,SYSTEM;   PROCEDURE Encode*(i: INTEGER; OUT x: INTEGER); VAR j: INTEGER; s,r: SET; BEGIN s := BITS(i);j := MAX(SET); WHILE (j >= 0) & ~(j IN s) DO DEC(j) END; r := {};IF j >= 0 THEN INCL(r,j) END; WHILE j > 0 DO IF ((j IN s) & ~(j - 1 IN s)) OR (~(j IN s) & (j - 1 IN s)) THEN INCL(r,j-1) END; DEC(j) END; x := SYSTEM.VAL(INTEGER,r) END Encode;   PROCEDURE Decode*(x: INTEGER; OUT i: INTEGER); VAR j: INTEGER; s,r: SET; BEGIN s := BITS(x);r:={};j := MAX(SET); WHILE (j >= 0) & ~(j IN s) DO DEC(j) END; IF j >= 0 THEN INCL(r,j) END; WHILE j > 0 DO IF ((j IN r) & ~(j - 1 IN s)) OR (~(j IN r) & (j - 1 IN s)) THEN INCL(r,j-1) END; DEC(j) END; i := SYSTEM.VAL(INTEGER,r); END Decode;     PROCEDURE Do*; VAR grayCode,binCode: INTEGER; i: INTEGER; BEGIN StdLog.String(" i ");StdLog.String(" bin code ");StdLog.String(" gray code ");StdLog.Ln; StdLog.String("---");StdLog.String(" ----------------");StdLog.String(" ---------------");StdLog.Ln; FOR i := 0 TO 32 DO; Encode(i,grayCode);Decode(grayCode,binCode); StdLog.IntForm(i,10,3,' ',FALSE); StdLog.IntForm(binCode,2,16,' ',TRUE); StdLog.IntForm(grayCode,2,16,' ',TRUE); StdLog.Ln; END END Do;   END GrayCodes.  
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
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   'capture the output of the 'dir' command and print it to a text file   Open "dir_output.txt" For Output As #1 Open Pipe "dir" For Input As #2 Dim li As String   While Not Eof(2) Line Input #2, li Print #1, li Wend   Close #2 Close #1 End
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
#FutureBasic
FutureBasic
  include "NSLog.incl"   local fn ObserverOne( ref as NotificationRef ) FileHandleRef fh = fn NotificationObject( ref ) CFDataRef dta = fn FileHandleAvailableData( fh )   if ( fn DataLength( dta ) > 0 ) CFStringRef string = fn StringWithData( dta, NSUTF8StringEncoding ) NSLog( @"%@", string ) FileHandleWaitForDataInBackgroundAndNotify( fh ) else NotificationCenterRemoveObserver( @fn ObserverOne, NSFileHandleDataAvailableNotification ) end if end fn   local fn RunCommand( cmdStr as CFStringRef ) '~'1 TaskRef task = fn TaskInit TaskSetExecutableURL( task, fn URLFileURLWithPath( @"/bin/sh" ) ) CFArrayRef arguments = fn ArrayWithObjects( @"-c", cmdStr, NULL ) TaskSetArguments( task, arguments ) PipeRef p = fn PipeInit TaskSetStandardOutput( task, p ) FileHandleRef fh = fn PipeFileHandleForReading( p ) NotificationCenterAddObserver( @fn ObserverOne, NSFileHandleDataAvailableNotification, (FileHandleRef)fh ) fn TaskLaunch( task, NULL ) FileHandleWaitForDataInBackgroundAndNotify( fh ) end fn   fn RunCommand( @"man mdls | col -b" )   HandleEvents  
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
#Gambas
Gambas
Public Sub Main() Dim sStore As String   Shell "ls" To sStore Print sStore   End
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#8th
8th
  swap  
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Arturo
Arturo
arr: [5 4 2 9 7 3]   print max arr
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.
#ALGOL_60
ALGOL 60
begin comment Greatest common divisor - algol 60;   integer procedure gcd(m,n); value m,n; integer m,n; begin integer a,b; a:=abs(m); b:=abs(n); if a=0 then gcd:=b else begin integer c,i; for i:=a while b notequal 0 do begin c:=b; b:=a-(a div b)*b; a:=c end; gcd:=a end end gcd;   outinteger(1,gcd(21,35)) end  
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#F.23
F#
open System.IO   [<EntryPoint>] let main args = let textFrom = "Goodbye London!" let textTo = "Hello New York!" for name in args do let content = File.ReadAllText(name) let newContent = content.Replace(textFrom, textTo) if content <> newContent then File.WriteAllText(name, newContent) 0
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.
#Factor
Factor
USING: fry io.encodings.utf8 io.files kernel qw sequences splitting ;   : global-replace ( files old new -- ) '[ [ utf8 file-contents _ _ replace ] [ utf8 set-file-contents ] bi ] each ;     qw{ a.txt b.txt c.txt } "Goodbye London!" "Hello New York!" global-replace
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.
#Fortran
Fortran
SUBROUTINE FILEHACK(FNAME,THIS,THAT) !Attacks a file! CHARACTER*(*) FNAME !The name of the file, presumed to contain text. CHARACTER*(*) THIS !The text sought in each record. CHARACTER*(*) THAT !Its replacement, should it be found. INTEGER F,T !Mnemonics for file unit numbers. PARAMETER (F=66,T=67) !These should do. INTEGER L !A length CHARACTER*6666 ALINE !Surely sufficient? LOGICAL AHIT !Could count them, but no report is called for. INQUIRE(FILE = FNAME, EXIST = AHIT) !This mishap is frequent, so attend to it. IF (.NOT.AHIT) RETURN !Nothing can be done! OPEN (F,FILE=FNAME,STATUS="OLD",ACTION="READWRITE") !Grab the source file. OPEN (T,STATUS="SCRATCH") !Request a temporary file. AHIT = .FALSE. !None found so far. Chew through the input, replacing THIS by THAT while writing to the temporary file.. 10 READ (F,11,END = 20) L,ALINE(1:MIN(L,LEN(ALINE))) !Grab a record. IF (L.GT.LEN(ALINE)) STOP "Monster record!" !Perhaps unmanageable. 11 FORMAT (Q,A) !Obviously, Q = length of characters unread in the record. L1 = 1 !Start at the start. 12 L2 = INDEX(ALINE(L1:L),THIS) !Look from L1 onwards. IF (L2.LE.0) THEN !A hit? WRITE (T,13) ALINE(L1:L) !No. Finish with the remainder of the line. 13 FORMAT (A) !Thus finishing the output line. GO TO 10 !And try for the next record. END IF !So much for not finding THIS. 14 L2 = L1 + L2 - 2 !Otherwise, THIS is found, starting at L1. WRITE (T,15) ALINE(L1:L2) !So roll the text up to the match, possibly none. 15 FORMAT (A,$) !But not ending the record. WRITE (T,15) THAT !Because THIS is replaced by THAT. AHIT = .TRUE. !And we've found at least one match. L1 = L2 + LEN(THIS) + 1 !Finger the first character beyond the matching THIS. IF (L - L1 + 1 .GE. LEN(THIS)) GO TO 12 !Might another search succeed? WRITE (T,13) ALINE(L1:L) !Nope. Finish the line with the tail end. GO TO 10 !And try for another record. Copy the temporary file back over the source file. Hope for no mishap and data loss! 20 IF (AHIT) THEN !If there were no hits, there is nothing to do. CLOSE (F) !Oh well. REWIND T !Go back to the start. OPEN (F,FILE="new"//FNAME,STATUS = "REPLACE",ACTION = "WRITE") !Overwrite... 21 READ (T,11,END = 22) L,ALINE(1:MIN(L,LEN(ALINE))) !Grab a line. IF (L.GT.LEN(ALINE)) STOP "Monster changed record!" !Once you start checking... WRITE (F,13) ALINE(1:L) !In case LEN(THAT) > LEN(THIS) GO TO 21 !Go grab the next line. END IF !So much for the replacement of the file. 22 CLOSE(T) !Finished: it will vanish. CLOSE(F) !Hopefully, the buffers will be written. END !So much for that.   PROGRAM ATTACK INTEGER N PARAMETER (N = 6) !More than one, anyway. CHARACTER*48 VICTIM(N) !Alternatively, the file names could be read from a file DATA VICTIM/ !Along with the target and replacement texts in each case. 1 "StaffStory.txt", 2 "Accounts.dat", 3 "TravelAgent.txt", 4 "RemovalFirm.dat", 5 "Addresses.txt", 6 "SongLyrics.txt"/ !Invention flags.   DO I = 1,N !So, step through the list. CALL FILEHACK(VICTIM(I),"Goodbye London!","Hello New York!") !One by one. END DO !On to the next.   END
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).
#ARM_Assembly
ARM Assembly
.org 0x08000000   b ProgramStart   ;cartridge header goes here     ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Program Start   .equ ramarea, 0x02000000 .equ CursorX,ramarea .equ CursorY,ramarea+1 .equ hailstoneram,0x02000004     ProgramStart: mov sp,#0x03000000 ;Init Stack Pointer   mov r4,#0x04000000 ;DISPCNT - LCD Video Controller mov r2,#0x403 ;4= Layer 2 on / 3= ScreenMode 3 str r2,[r4] ;now the user can see the screen   bl ResetTextCursors ;set text cursors to top left of screen. This routine, as well as the other I/O ; routines, were omitted to keep this entry short. mov r0,#27 adr r1,HailStoneMessage_Init bl PrintString bl NewLine bl ShowHex32 bl NewLine bl NewLine     bl Hailstone   ;function is complete, return the output adr r1,HailStoneMessage_0 bl PrintString bl NewLine ldr r1,HailStoneRam_Mirror ;mov r2,0x02000004     ldr r0,[r1],#4 bl ShowHex32 bl NewLine   ldr r0,[r1],#4 bl ShowHex32 bl NewLine   ldr r0,[r1],#4 bl ShowHex32 bl NewLine   ldr r0,[r1],#4 bl ShowHex32 bl NewLine bl NewLine   adr r1,HailStoneMessage_1 bl PrintString bl NewLine   ldr r0,[r2],#4 bl ShowHex32 bl NewLine   ldr r0,[r2],#4 bl ShowHex32 bl NewLine   ldr r0,[r2],#4 bl ShowHex32 bl NewLine   ldr r0,[r2],#4 bl ShowHex32 bl NewLine bl NewLine   adr r1,HailStoneMessage_2 bl PrintString bl NewLine mov r0,r3 bl ShowHex32   forever: b forever ;we're done, so trap the program counter.   Hailstone: ;input: R0 = n. ;out: r2 = pointer to last 4 entries ; r3 = length of sequence     ;reg usage: ;R1 = scratchpad ;R3 = counter for entries in the sequence. ;R5 = pointer to output ram stmfd sp!,{r4-r12,lr}   mov r5,#0x02000000 add r5,r5,#4 str r0,[r5],#4 ;store in hailstone ram and post-inc by 4 mov r3,#0 loop_hailstone: add r3,r3,#1 ;represents number of entries in the sequence cmp r0,#1 beq hailstone_end tst r0,#1 ;;;; executes only if r0 was even moveq r0,r0,lsr #1 ;divide   ;;;; executes only if r0 was odd movne r1,r0 movne r0,r0,lsl #1 addne r0,r1,r0 addne r0,r0,#1   str r0,[r5],#4 ;store in hailstone ram, post inc by 4   b loop_hailstone     hailstone_end: sub r5,r5,#16 ;subtract 16 to get pointer to last 4 entries. mov r2,r5 ;output ptr to last 4 entries to r2. ;pointer to first 4 entries is 0x02000004 ldmfd sp!,{r4-r12,pc}   HailStoneRam_Mirror: .long 0x02000004 HailstoneMessage_Init: .byte "Your input was:",255 .align 4 HailstoneMessage_0: .byte "First 4 numbers are:",255 .align 4 HailstoneMessage_1: .byte "Last 4 numbers are:",255 .align 4 HailstoneMessage_2: .byte "Sequence length is:",255 .align 4   ;;;;;;;;;;; EVERYTHING PAST THIS POINT IS JUST I/O ROUTINES FOR PRINTING NUMBERS AND WORDS TO THE GAME BOY ADVANCE'S SCREEN ;;;;;;;;;;; I ASSURE YOU THAT ALL OF IT WORKS BUT CHANCES ARE YOU DIDN'T COME HERE TO SEE THAT. ;;;;;;;;;;; THANKS TO KEITH OF CHIBIAKUMAS.COM FOR WRITING THEM!
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.
#Lua
Lua
function ConvertToGrayscaleImage( bitmap ) local size_x, size_y = #bitmap, #bitmap[1] local gray_im = {}   for i = 1, size_x do gray_im[i] = {} for j = 1, size_y do gray_im[i][j] = math.floor( 0.2126*bitmap[i][j][1] + 0.7152*bitmap[i][j][2] + 0.0722*bitmap[i][j][3] ) end end   return gray_im end   function ConvertToColorImage( gray_im ) local size_x, size_y = #gray_im, #gray_im[1] local bitmap = Allocate_Bitmap( size_x, size_y ) -- this function is defined at http://rosettacode.org/wiki/Basic_bitmap_storage#Lua   for i = 1, size_x do for j = 1, size_y do bitmap[i][j] = { gray_im[i][j], gray_im[i][j], gray_im[i][j] } end end   return bitmap 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.
#Maple
Maple
with(ImageTools): #conversion forward dimensions:=[upperbound(img)]; gray := Matrix(dimensions[1], dimensions[2]); for i from 1 to dimensions[1] do for j from 1 to dimensions[2] do gray[i,j] := 0.2126 * img[i,j,1] + 0.7152*img[i,j,2] + 0.0722*img[i,j,3]: end do: end do: #display the result Embed(Create(gray)): #conversion backward x:=Create(gray); ToRGB(x); #display the result Embed(x);
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
#!/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).
#Eiffel
Eiffel
  note description : "Initial part, in order, of the sequence of Hamming numbers" math : "[ Hamming numbers, also known as regular numbers and 5-smooth numbers, are natural integers that have 2, 3 and 5 as their only prime factors. ]" computer_arithmetic : "[ This version avoids integer overflow and stops at the last representable number in the sequence. ]" output : "[ Per requirements of the RosettaCode example, execution will produce items of indexes 1 to 20 and 1691. The algorithm (procedure `hamming') is more general and will produce the first `n' Hamming numbers for any `n'. ]" source : "This problem was posed in Edsger W. Dijkstra, A Discipline of Programming, Prentice Hall, 1978" date : "8 August 2012" authors : "Bertrand Meyer", "Emmanuel Stapf" revision : "1.0" libraries : "Relies on SORTED_TWO_WAY_LIST from EiffelBase" implementation : "[ Using SORTED_TWO_WAY_LIST provides an elegant illustration of how to implement a lazy scheme in Eiffel through the use of object-oriented data structures. ]" warning : "[ The formatting (<lang>) specifications for Eiffel in RosettaCode are slightly obsolete: `note' and other newer keywords not supported, red color for manifest strings. This should be fixed soon. ]"   class APPLICATION   create make   feature {NONE} -- Initialization   make -- Print first 20 Hamming numbers, in order, and the 1691-st one. local Hammings: like hamming -- List of Hamming numbers, up to 1691-st one. do Hammings := hamming (1691) across 1 |..| 20 as i loop io.put_natural (Hammings.i_th (i.item)); io.put_string (" ") end io.put_new_line; io.put_natural (Hammings.i_th (1691)); io.put_new_line end   feature -- Basic operations   hamming (n: INTEGER): ARRAYED_LIST [NATURAL] -- First `n' elements (in order) of the Hamming sequence, -- or as many of them as will not produce overflow. local sl: SORTED_TWO_WAY_LIST [NATURAL] overflow: BOOLEAN first, next: NATURAL do create Result.make (n); create sl.make sl.extend (1); sl.start across 1 |..| n as i invariant -- "The numbers output so far are the first `i' - 1 Hamming numbers, in order". -- "Result.first is the `i'-th Hamming number." until sl.is_empty loop first := sl.first; sl.start Result.extend (first); sl.remove across << 2, 3, 5 >> as multiplier loop next := multiplier.item * first overflow := overflow or next <= first if not overflow and then not sl.has (next) then sl.extend (next) end end end end end  
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#GW-BASIC
GW-BASIC
10 RANDOMIZE TIMER:N=INT(RND*10+1):G=0 20 PRINT "Guess the number between 1 and 10." 30 WHILE N<>G 40 INPUT "Your guess? ",G 50 WEND 60 PRINT "That's correct!"
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
#Haskell
Haskell
  import Control.Monad import System.Random   -- Repeat the action until the predicate is true. until_ act pred = act >>= pred >>= flip unless (until_ act pred)   answerIs ans guess | ans == guess = putStrLn "You got it!" >> return True | otherwise = putStrLn "Nope. Guess again." >> return False   ask = liftM read getLine   main = do ans <- randomRIO (1,10) :: IO Int putStrLn "Try to guess my secret number between 1 and 10." ask `until_` answerIs ans  
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.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Dim As Integer seq(10) = {-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1} Dim As Integer i, j, sum, maxSum, first, last   maxSum = 0   For i = LBound(seq) To UBound(seq) sum = 0 For j = i To UBound(seq) ' only proper sub-sequences are considered If i = LBound(seq) AndAlso j = UBound(seq) Then Exit For sum += seq(j) If sum > maxSum Then maxSum = sum first = i last = j End If Next j Next i   If maxSum > 0 Then Print "Maximum subsequence is from indices"; first; " to"; last Print "Elements are : "; For i = first To last Print seq(i); " "; Next Print Print "Sum is"; maxSum Else Print "Maximum subsequence is the empty sequence which has a sum of 0" End If   Print Print "Press any key to quit" Sleep
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)
#Ela
Ela
open string datetime random core monad io   guess () = do putStrLn "What's the upper bound?" ub <- readAny main ub where main ub | ub < 0 = "Bound should be greater than 0." | else = do putStrLn $ format "Guess a number from 1 to {0}" ub dt <- datetime.now guesser (rnd (milliseconds $ dt) 1 ub) guesser v = do x <- readAny if x == v then cont () else if x < v then do putStrLn "Too small!" guesser v else do putStrLn "Too big!" guesser v cont () = do putStrLn "Correct! Do you wish to continue (Y/N)?" ask () ask () = do a <- readStr if a == "y" || a == "Y" then guess () else if a == "n" || a == "N" then do putStrLn "Bye!" else do putStrLn "Say what?" ask ()   guess () ::: IO
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
#Quackery
Quackery
  [ [ $ "lower higher equal" nest$ ] constant ] is responses ( --> $ )   [ trim reverse trim reverse $ "" swap witheach [ lower join ] ] is cleanup ( $ --> $ )   [ $ "Think of a number from 1 to" $ " 100 and press enter." join input drop 0 temp put [] 100 times [ i 1+ join ] [ dup size 0 = iff [ say "Impossible!" cr 0 ] done dup size 2 / split behead dup temp replace say "I guess " echo say "." cr $ "lower, higher or equal? " input cleanup responses find [ table [ nip false ] [ drop false ] [ say "I guessed it!" cr true ] [ say "I do not understand." temp share swap join join cr false ] ] do until ] 2drop temp release ] is play ( --> )
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
#R
R
guessANumberPlayer <- function(low, high) { boundryErrorCheck(low, high) repeat { guess <- floor(mean(c(low, high))) #Invalid inputs to this switch will simply cause the repeat loop to run again, breaking nothing. switch(guessResult(guess), l = low <- guess + 1, h = high <- guess - 1, c = return(paste0("Your number is ", guess, ".", " I win!"))) } }   #Copied from my solution at https://rosettacode.org/wiki/Guess_the_number/With_feedback#R boundryErrorCheck <- function(low, high) { if(!is.numeric(low) || as.integer(low) != low) stop("Lower bound must be an integer. Try again.") if(!is.numeric(high) || as.integer(high) != high) stop("Upper bound must be an integer. Try again.") if(high < low) stop("Upper bound must be strictly greater than lower bound. Try again.") if(low == high) stop("This game is impossible to lose. Try again.") invisible() }   guessResult <- function(guess) readline(paste0("My guess is ", guess, ". If it is too low, submit l. If it is too high, h. Otherwise, c. "))
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
#Factor
Factor
USING: combinators kernel make math sequences ;   : squares ( n -- s ) 0 [ over 0 > ] [ [ 10 /mod sq ] dip + ] while nip ;   : (happy?) ( n1 n2 -- ? ) [ squares ] [ squares squares ] bi* { { [ dup 1 = ] [ 2drop t ] } { [ 2dup = ] [ 2drop f ] } [ (happy?) ] } cond ;   : happy? ( n -- ? ) dup (happy?) ;   : happy-numbers ( n -- seq ) [ 0 [ over 0 > ] [ dup happy? [ dup , [ 1 - ] dip ] when 1 + ] while 2drop ] { } make ;
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.
#PicoLisp
PicoLisp
(scl 12) (load "@lib/math.l")   (de haversine (Th1 Ph1 Th2 Ph2) (setq Ph1 (*/ (- Ph1 Ph2) pi 180.0) Th1 (*/ Th1 pi 180.0) Th2 (*/ Th2 pi 180.0) ) (let (DX (- (*/ (cos Ph1) (cos Th1) 1.0) (cos Th2)) DY (*/ (sin Ph1) (cos Th1) 1.0) DZ (- (sin Th1) (sin Th2)) ) (* `(* 2 6371) (asin (/ (sqrt (+ (* DX DX) (* DY DY) (* DZ DZ))) 2 ) ) ) ) )
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.
#PL.2FI
PL/I
test: procedure options (main); /* 12 January 2014. Derived from Fortran version */ declare d float;   d = haversine(36.12, -86.67, 33.94, -118.40); /* BNA to LAX */ put edit ( 'distance: ', d, ' km') (A, F(10,3)); /* distance: 2887.2600 km */     degrees_to_radians: procedure (degree) returns (float); declare degree float nonassignable; declare pi float (15) initial ( (4*atan(1.0d0)) );   return ( degree*pi/180 ); end degrees_to_radians;   haversine: procedure (deglat1, deglon1, deglat2, deglon2) returns (float); declare (deglat1, deglon1, deglat2, deglon2) float nonassignable; declare (a, c, dlat, dlon, lat1, lat2) float; declare radius float value (6372.8);   dlat = degrees_to_radians(deglat2-deglat1); dlon = degrees_to_radians(deglon2-deglon1); lat1 = degrees_to_radians(deglat1); lat2 = degrees_to_radians(deglat2); a = (sin(dlat/2))**2 + cos(lat1)*cos(lat2)*(sin(dlon/2))**2; c = 2*asin(sqrt(a)); return ( radius*c ); end haversine;   end test;
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
#Golfscript
Golfscript
"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
#PureBasic
PureBasic
If OpenConsole()=0 : End 1 : EndIf   Procedure.i Niven(v.i) w=v While v : s+v%10 : v/10 : Wend If w%s=0 : ProcedureReturn w : EndIf EndProcedure   Repeat i+1 If Niven(i) : c+1 : Print(Str(i)+" ") : EndIf If c=20 And i<1000 : Print("... ") : i=1000 : EndIf If c=21 : Break : EndIf ForEver   Input()
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
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Declare Simple Form \\ we can define form before open Layer Simple { \\ center Window with 12pt font, 12000 twips width and 6000 twips height \\ ; at the end command to center the form in current screen Window 12, 12000, 6000; \\ make layer gray and split screen 0 Cls #333333, 0 \\ set split screen to 3rd line, like Cls ,2 without clear screen Scroll Split 2 Cursor 0, 2 } With Simple, "Title", "Hello Form" Function Simple.Click { Layer Simple { \\ open msgbox Print Ask("Hello World") Refresh } } \\ now open as modal Method Simple, "Show", 1 \\ now form deleted Declare Simple Nothing } CheckIt  
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
#Maple
Maple
  Maplets:-Display( Maplets:-Elements:-Maplet( [ "Goodbye, World!" ] ) );  
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] Reference Converting Between Gray and Binary Codes. It includes step-by-step animations.
#Crystal
Crystal
  def gray_encode(bin) bin ^ (bin >> 1) end   def gray_decode(gray) bin = gray while gray > 0 gray >>= 1 bin ^= gray end bin 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.
#D
D
uint grayEncode(in uint n) pure nothrow @nogc { return n ^ (n >> 1); }   uint grayDecode(uint n) pure nothrow @nogc { auto p = n; while (n >>= 1) p ^= n; return p; }   void main() { import std.stdio;   " N N2 enc dec2 dec".writeln; foreach (immutable n; 0 .. 32) { immutable g = n.grayEncode; immutable d = g.grayDecode; writefln("%2d: %5b => %5b => %5b: %2d", n, n, g, d, d); assert(d == 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
#Genie
Genie
[indent=4] /* Get system command output, in Genie   valac getSystemCommandOutput.gs ./getSystemCommandOutput */   init try // Blocking with output capture standard_output : string standard_error : string exit_status : int Process.spawn_command_line_sync("sh -c 'ls getSys*'", out standard_output, out standard_error, out exit_status) print standard_output except e : SpawnError stderr.printf("%s\n", e.message)
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
#Go
Go
package main   import ( "fmt" "log" "os/exec" )   func main() { output, err := exec.Command("ls", "-l").CombinedOutput() if err != nil { log.Fatal(err) } fmt.Print(string(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
#Haskell
Haskell
#!/usr/bin/env stack -- stack --resolver lts-8.15 --install-ghc runghc --package process   import System.Process (readProcess)   main :: IO () main = do -- get the output of the process as a list of lines results <- lines <$> readProcess "hexdump" ["-C", "/etc/passwd"] ""   -- print each line in reverse mapM_ (putStrLn . reverse) results
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!
#ACL2
ACL2
(defun swap (pair) (cons (cdr pair) (car pair)))   (let ((p (cons 1 2))) (cw "Before: ~x0~%After: ~x1~%" p (swap p)))
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.
#AutoHotkey
AutoHotkey
list = 1,5,17,-2 Loop Parse, list, `, x := x < A_LoopField ? A_LoopField : x MsgBox Max = %x%
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#ALGOL_68
ALGOL 68
PROC gcd = (INT a, b) INT: ( IF a = 0 THEN b ELIF b = 0 THEN a ELIF a > b THEN gcd(b, a MOD b) ELSE gcd(a, b MOD a) FI ); test:( INT a = 33, b = 77; printf(($x"The gcd of"g" and "g" is "gl$,a,b,gcd(a,b))); INT c = 49865, d = 69811; printf(($x"The gcd of"g" and "g" is "gl$,c,d,gcd(c,d))) )
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.
#FreeBASIC
FreeBASIC
Const matchtext = "Goodbye London!" Const repltext = "Hello New York!" Const matchlen = Len(matchtext)   Dim As Integer x, L0 = 1 dim as string filespec, linein   L0 = 1 While Len(Command(L0)) filespec = Dir(Command(L0)) While Len(filespec) Open filespec For Binary As 1 linein = Space(Lof(1)) Get #1, 1, linein Do x = Instr(linein, matchtext) If x Then linein = Left(linein, x - 1) & repltext & Mid(linein, x + matchlen) Else Exit Do End If Loop Close Open filespec For Output As 1 Print #1, linein; Close filespec = Dir Wend L0 += 1 Wend
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.
#Go
Go
package main   import ( "bytes" "io/ioutil" "log" "os" )   func main() { gRepNFiles("Goodbye London!", "Hello New York!", []string{ "a.txt", "b.txt", "c.txt", }) }   func gRepNFiles(olds, news string, files []string) { oldb := []byte(olds) newb := []byte(news) for _, fn := range files { if err := gRepFile(oldb, newb, fn); err != nil { log.Println(err) } } }   func gRepFile(oldb, newb []byte, fn string) (err error) { var f *os.File if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil { return } defer func() { if cErr := f.Close(); err == nil { err = cErr } }() var b []byte if b, err = ioutil.ReadAll(f); err != nil { return } if bytes.Index(b, oldb) < 0 { return } r := bytes.Replace(b, oldb, newb, -1) if err = f.Truncate(0); err != nil { return } _, err = f.WriteAt(r, 0) return }
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).
#Arturo
Arturo
hailstone: function [n][ ret: @[n] while [n>1][ if? 1 = and n 1 -> n: 1+3*n else -> n: n/2   'ret ++ n ] ret ]   print "Hailstone sequence for 27:" print hailstone 27   maxHailstoneLength: 0 maxHailstone: 0   loop 2..1000 'x [ l: size hailstone x if l>maxHailstoneLength [ maxHailstoneLength: l maxHailstone: x ] ]   print ["max hailstone sequence found (<100000): of length" maxHailstoneLength "for" maxHailstone]  
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
toGrayscale[rgb_Image] := ImageApply[#.{0.2126, 0.7152, 0.0722}&, rgb] toFakeRGB[L_Image] := ImageApply[{#, #, #}&, L]
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.
#MATLAB
MATLAB
function [grayImage] = colortograyscale(inputImage) grayImage = rgb2gray(inputImage);
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.
#Nim
Nim
  import bitmap import lenientops   type   GrayImage* = object w*, h*: Index pixels*: seq[Luminance]   proc newGrayImage*(width, height: int): GrayImage = ## Create a gray image with given width and height. new(result) result.w = width result.h = height result.pixels.setLen(width * height)   iterator indices*(img: GrayImage): Point = ## Yield the pixels coordinates as tuples. for y in 0 ..< img.h: for x in 0 ..< img.w: yield (x, y)   proc `[]`*(img: GrayImage; x, y: int): Luminance = ## Get a pixel luminance value. img.pixels[y * img.w + x]   proc `[]=`*(img: GrayImage; x, y: int; lum: Luminance) = ## Set a pixel luminance to given value. img.pixels[y * img.w + x] = lum   proc fill*(img: GrayImage; lum: Luminance) = ## Set the pixels to a given luminance. for x, y in img.indices: img[x, y] = lum   func toGrayLuminance(color: Color): Luminance = ## Compute the luminance from RGB value. Luminance(0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b + 0.5)   func toGrayImage*(img: Image): GrayImage = ## result = newGrayImage(img.w, img.h) for pt in img.indices: result[pt.x, pt.y] = img[pt.x, pt.y].toGrayLuminance()   func toImage*(img: GrayImage): Image = result = newImage(img.w, img.h) for pt in img.indices: let lum = img[pt.x, pt.y] result[pt.x, pt.y] = (lum, lum, lum)   #———————————————————————————————————————————————————————————————————————————————————————————————————   when isMainModule:   import ppm_write   # Create a RGB image. var image = newImage(100, 50) image.fill(color(128, 128, 128)) for row in 10..20: for col in 0..<image.w: image[col, row] = color(0, 255, 0) for row in 30..40: for col in 0..<image.w: image[col, row] = color(0, 0, 255)   # Convert it to grayscale. var grayImage = image.toGrayImage()   # Convert it back to RGB in order to save it in PPM format using the available procedure. var convertedImage = grayImage.toImage() convertedImage.writePPM("output_gray.ppm")
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
#Nim
Nim
#!/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).
#Elixir
Elixir
defmodule Hamming do def generater do queues = [{2, queue}, {3, queue}, {5, queue}] Stream.unfold({1, queues}, fn {n, q} -> next(n, q) end) end   defp next(n, queues) do queues = Enum.map(queues, fn {m, queue} -> {m, push(queue, m*n)} end) min = Enum.map(queues, fn {_, queue} -> top(queue) end) |> Enum.min queues = Enum.map(queues, fn {m, queue} -> {m, (if min==top(queue), do: erase_top(queue), else: queue)} end) {n, {min, queues}} end   defp queue, do: {[], []}   defp push({input, output}, term), do: {[term | input], output}   defp top({input, []}), do: List.last(input) defp top({_, [h|_]}), do: h   defp erase_top({input, []}), do: erase_top({[], Enum.reverse(input)}) defp erase_top({input, [_|t]}), do: {input, t} end   IO.puts "first twenty Hamming numbers:" IO.inspect Hamming.generater |> Enum.take(20) IO.puts "1691st Hamming number:" IO.puts Hamming.generater |> Enum.take(1691) |> List.last IO.puts "one millionth Hamming number:" IO.puts Hamming.generater |> Enum.take(1_000_000) |> List.last
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
#HolyC
HolyC
U8 n, *g;   n = 1 + RandU16 % 10;   Print("I'm thinking of a number between 1 and 10.\n"); Print("Try to guess it:\n");   while(1) { g = GetStr;   if (Str2I64(g) == n) { Print("Correct!\n"); break; }   Print("That's not my number. Try another guess:\n"); }
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#Icon_and_Unicon
Icon and Unicon
procedure main() n := ?10 repeat { writes("Pick a number from 1 through 10: ") if n = numeric(read()) then break } write("Well guessed!") 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.
#Go
Go
package main   import "fmt"   func gss(s []int) ([]int, int) { var best, start, end, sum, sumStart int for i, x := range s { sum += x switch { case sum > best: best = sum start = sumStart end = i + 1 case sum < 0: sum = 0 sumStart = i + 1 } } return s[start:end], best }   var testCases = [][]int{ {-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1}, {-1, 1, 2, -5, -6}, {}, {-1, -2, -1}, }   func main() { for _, c := range testCases { fmt.Println("Input: ", c) subSeq, sum := gss(c) fmt.Println("Sub seq:", subSeq) fmt.Println("Sum: ", sum, "\n") } }
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#Elena
Elena
import extensions;   public program() { int randomNumber := randomGenerator.eval(1,10); console.printLine("I'm thinking of a number between 1 and 10. Can you guess it?"); bool numberCorrect := false; until(numberCorrect) { console.print("Guess: "); int userGuess := console.readLine().toInt(); if (randomNumber == userGuess) { numberCorrect := true; console.printLine("Congrats!! You guessed right!") } else if (randomNumber < userGuess) { console.printLine("Your guess was too high") } else { console.printLine("Your guess was too low") } } }