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/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
#MAXScript
MAXScript
  rand = random 1 10 clearListener() while true do ( userval = getKBValue prompt:"Enter an integer between 1 and 10: " if userval == rand do (format "\nWell guessed!\n"; exit) format "\nChoose another value\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
#Mercury
Mercury
:- module guess. :- interface. :- import_module io. :- pred main(io::di, io::uo) is det. :- implementation. :- import_module random, string.   main(!IO) :- time(Time, !IO), random.init(Time, Rand), random.random(1, 10, N, Rand, _), main(from_int(N) ++ "\n", !IO).   :- pred main(string::in, io::di, io::uo) is det. main(N, !IO) :- io.write_string("Guess the number: ", !IO), io.read_line_as_string(Res, !IO), ( Res = ok(S), ( if S = N then io.write_string("Well guessed!\n", !IO) else main(N, !IO) )  ; Res = error(E)  ; Res = eof ).   :- pred time(int::out, io::di, io::uo) is det.   :- pragma foreign_decl("C", "#include <time.h>"). :- pragma foreign_proc("C", time(Int::out, _IO0::di, _IO1::uo), [will_not_call_mercury, promise_pure], "Int = time(NULL);").
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.
#Mathprog
Mathprog
  /*Special ordered set of type N   Nigel_Galloway January 26th, 2012 */   param Lmax; param Lmin; set SOS; param Sx{SOS}; var db{Lmin..Lmax,SOS}, binary;   maximize s : sum{q in (Lmin..Lmax),t in (0..q-1), z in SOS: z > (q-1)} Sx[z-t]*db[q,z]; sos1 : sum{t in (Lmin..Lmax),z in SOS: z > (t-1)} db[t,z] = 1; solve;   for{t in (Lmin..Lmax),z in SOS: db[t,z] == 1} { printf "\nA sub-sequence of length %d sums to %f:\n", t,s; printf{q in (z-t+1)..z} "  %f", Sx[q]; } printf "\n\n";   data; param Lmin := 1; param Lmax := 6; param: SOS: Sx := 1 7 2 4 3 -11 4 6 5 3 6 1 ;   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.
#MATLAB_.2F_Octave
MATLAB / Octave
function [S,GS]=gss(a) % Greatest subsequential sum a =[0;a(:);0]'; ix1 = find(a(2:end) >0 & a(1:end-1) <= 0); ix2 = find(a(2:end)<=0 & a(1:end-1) > 0); K = 0; S = 0; for k = 1:length(ix1) s = sum(a(ix1(k)+1:ix2(k))); if (s>S) S=s; K=k; end; end; GS = a(ix1(K)+1:ix2(K));  
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)
#Frink
Frink
// Guess a Number with feedback. target = random[1,100] // Min and max are both inclusive for the random function guess = 0 println["Welcome to guess a number! I've picked a number between 1 and 100. Try to guess it!"] while guess != target { guessStr = input["What is your guess?"] guess = parseInt[guessStr] if guess == undef { println["$guessStr is not a valid guess. Please enter a number from 1 to 100."] next } if guess < target println["My number is higher than $guess."] if guess > target println["My number is lower than $guess."] if guess == target println["$guess is correct! Well guessed!"] }  
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
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET min=1: LET max=100 20 PRINT "Think of a number between ";min;" and ";max 30 PRINT "I will try to guess your number." 40 LET guess=INT ((min+max)/2) 50 PRINT "My guess is ";guess 60 INPUT "Is it higuer than, lower than or equal to your number? ";a$ 65 LET a$=a$(1) 70 IF a$="L" OR a$="l" THEN LET min=guess+1: GO TO 40 80 IF a$="H" OR a$="h" THEN LET max=guess-1: GO TO 40 90 IF a$="E" OR a$="e" THEN PRINT "Goodbye.": STOP 100 PRINT "Sorry, I didn't understand your answer.": GO TO 60
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
#Haskell
Haskell
import Data.Char (digitToInt) import Data.Set (member, insert, empty)   isHappy :: Integer -> Bool isHappy = p empty where p _ 1 = True p s n | n `member` s = False | otherwise = p (insert n s) (f n) f = sum . fmap ((^ 2) . toInteger . digitToInt) . show   main :: IO () main = mapM_ print $ take 8 $ filter isHappy [1 ..]
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.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i"; include "math.s7i";   const func float: greatCircleDistance (in float: latitude1, in float: longitude1, in float: latitude2, in float: longitude2) is func result var float: distance is 0.0; local const float: EarthRadius is 6372.8; # Average great-elliptic or great-circle radius in kilometers begin distance := 2.0 * EarthRadius * asin(sqrt(sin(0.5 * (latitude2 - latitude1)) ** 2 + cos(latitude1) * cos(latitude2) * sin(0.5 * (longitude2 - longitude1)) ** 2)); end func;   const func float: degToRad (in float: degrees) is return degrees * 0.017453292519943295769236907684886127;   const proc: main is func begin writeln("Distance in kilometers between BNA and LAX"); writeln(greatCircleDistance(degToRad(36.12), degToRad(-86.67), # Nashville International Airport (BNA) degToRad(33.94), degToRad(-118.4)) # Los Angeles International Airport (LAX) digits 2); end func;
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.
#Sidef
Sidef
class EarthPoint(lat, lon) {   const earth_radius = 6371 # mean earth radius const radian_ratio = Num.pi/180   # accessors for radians method latR { self.lat * radian_ratio } method lonR { self.lon * radian_ratio }   method haversine_dist(EarthPoint p) { var arc = EarthPoint( self.lat - p.lat, self.lon - p.lon, )   var a = Math.sum( (arc.latR / 2).sin**2, (arc.lonR / 2).sin**2 * self.latR.cos * p.latR.cos )   earth_radius * a.sqrt.asin * 2 } }   var BNA = EarthPoint.new(lat: 36.12, lon: -86.67) var LAX = EarthPoint.new(lat: 33.94, lon: -118.4)   say BNA.haversine_dist(LAX) #=> 2886.444442837983299747157823945746716...
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
#HLA
HLA
program goodbyeWorld; #include("stdlib.hhf") begin goodbyeWorld;   stdout.put( "Hello world!" nl );   end goodbyeWorld;
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
#Seed7
Seed7
$ include "seed7_05.s7i";   const func integer: sumOfDigits (in var integer: num) is func result var integer: sum is 0; begin repeat sum +:= num rem 10; num := num div 10; until num = 0; end func;   const func integer: nextHarshadNum (inout integer: num) is func result var integer: harshadNumber is 0; begin while num mod sumOfDigits(num) <> 0 do incr(num); end while; harshadNumber := num; end func;   const proc: main is func local var integer: current is 1; var integer: count is 0; begin for count range 1 to 20 do write(nextHarshadNum(current) <& " "); incr(current); end for; current := 1001; writeln(" ... " <& nextHarshadNum(current)); end func;
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
#OxygenBasic
OxygenBasic
print "Hello World!"
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Oxygene
Oxygene
  <?xml version="1.0" standalone="no"?> <!--*- mode: xml -*--> <!DOCTYPE glade-interface SYSTEM "http://glade.gnome.org/glade-2.24.dtd">   <glade-interface>   <widget class="GtkWindow" id="hworld"> <property name="visible">True</property> <property name="title">Hello World</property> <property name="modal">False</property> <property name="resizable">True</property> <property name="default_width">200</property> <property name="default_height">100</property> <signal name="delete_event" handler="on_hworld_delete_event"/> <child> <widget class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">Farewell, cruel world.</property> </widget> </child> </widget>   </glade-interface>  
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.
#JavaScript
JavaScript
export function encode (number) { return number ^ (number >> 1) }   export function decode (encodedNumber) { let number = encodedNumber   while (encodedNumber >>= 1) { number ^= encodedNumber }   return number }
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.
#Julia
Julia
grayencode(n::Integer) = n ⊻ (n >> 1) function graydecode(n::Integer) r = n while (n >>= 1) != 0 r ⊻= n end return r 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
#Ursa
Ursa
> decl iodevice iod > decl string<> arg > append "ifconfig" arg > set iod (ursa.util.process.start arg) > decl string<> output > set output (iod.readlines) > for (decl int i) (< i (size output)) (inc i) .. out output<i> endl console ..end for lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384 options=3<RXCSUM,TXCSUM> inet6 ::1 prefixlen 128 inet 127.0.0.1 netmask 0xff000000 inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1 nd6 options=1<PERFORMNUD> gif0: flags=8010<POINTOPOINT,MULTICAST> mtu 1280 stf0: flags=0<> mtu 1280 en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 options=27<RXCSUM,TXCSUM,VLAN_MTU,TSO4> ether d4:9a:20:b8:8d:2c nd6 options=1<PERFORMNUD> media: autoselect status: inactive en1: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 ether 00:26:08:e0:67:cc inet6 fe80::226:8ff:fee0:67cc%en1 prefixlen 64 scopeid 0x5 inet 172.20.30.66 netmask 0xffffff00 broadcast 172.20.30.255 nd6 options=1<PERFORMNUD> media: autoselect status: active fw0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 4078 lladdr d4:9a:20:ff:fe:b8:8d:2c nd6 options=1<PERFORMNUD> media: autoselect <full-duplex> status: inactive p2p0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 2304 ether 02:26:08:e0:67:cc media: autoselect status: inactive >
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
#VBScript
VBScript
For Each line In ExecCmd("ipconfig /all") Wscript.Echo line Next   'Execute the given command and return the output in a text array. Function ExecCmd(cmd)   'Execute the command Dim wso : Set wso = CreateObject("Wscript.Shell") Dim exec : Set exec = wso.Exec(cmd) Dim res : res = ""   'Read all result text from standard output Do res = res & VbLf & exec.StdOut.ReadLine Loop Until exec.StdOut.AtEndOfStream   'Return as a text array ExecCmd = Split(Mid(res,2),vbLf) End Function
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
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Sub Main() Dim proccess As New Process Dim startInfo As New ProcessStartInfo   startInfo.WindowStyle = ProcessWindowStyle.Hidden startInfo.FileName = "cmd.exe" startInfo.Arguments = "/c echo Hello World" startInfo.RedirectStandardOutput = True startInfo.UseShellExecute = False   proccess.StartInfo = startInfo proccess.Start()   Dim output = proccess.StandardOutput.ReadToEnd Console.WriteLine("Output is {0}", output) End Sub   End Module
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!
#Applesoft_BASIC
Applesoft BASIC
A=43:B=47:H=A:A=B:B=H:?" A="A" B="B;
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Burlesque
Burlesque
  blsq ) {88 99 77 66 55}>] 99  
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.
#AutoIt
AutoIt
  _GCD(18, 12) _GCD(1071, 1029) _GCD(3528, 3780)   Func _GCD($ia, $ib) Local $ret = "GCD of " & $ia & " : " & $ib & " = " Local $imod While True $imod = Mod($ia, $ib) If $imod = 0 Then Return ConsoleWrite($ret & $ib & @CRLF) $ia = $ib $ib = $imod WEnd EndFunc ;==>_GCD  
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.
#Red
Red
>> f: request-file >> str: read f >> replace/all str "Goodbye London!" "Hello New York!" >> write f str
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.
#REXX
REXX
/*REXX program reads the files specified and globally replaces a string. */ old= "Goodbye London!" /*the old text to be replaced. */ new= "Hello New York!" /* " new " used for replacement. */ parse arg fileList /*obtain required list of files from CL*/ #= words(fileList) /*the number of files in the file list.*/   do f=1 for #; fn= translate( word(fileList, f), , ','); say; say say '──────── file is being read: ' fn " ("f 'out of' # "files)." call linein fn,1,0 /*position the file for input. */ changes= 0 /*the number of changes in file so far.*/ do rec=0 while lines(fn)\==0 /*read a file (if it exists). */ @.rec= linein(fn) /*read a record (line) from the file. */ if pos(old, @.rec)==0 then iterate /*Anything to change? No, then skip. */ changes= changes + 1 /*flag that file contents have changed.*/ @.rec= changestr(old, @.rec, new) /*change the @.rec record, old ──► new.*/ end /*rec*/   say '──────── file has been read: ' fn", with " rec 'records.' if changes==0 then do; say '──────── file not changed: ' fn; iterate; end call lineout fn,,1 /*position file for output at 1st line.*/ say '──────── file being changed: ' fn   do r=0 for rec; call lineout fn, @.r /*re─write the contents of the file. */ end /*r*/   say '──────── file was changed: ' fn " with" changes 'lines changed.' end /*f*/ /*stick a fork in it, we're all done. */
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).
#Burlesque
Burlesque
  blsq ) 27{^^^^2.%{3.*1.+}\/{2./}\/ie}{1!=}w!bx{\/+]}{\/isn!}w!L[ 112  
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.
#Wren
Wren
import "graphics" for Canvas, Color, ImageData import "dome" for Window   class PercentageDifference { construct new(width, height, image1, image2) { Window.title = "Grayscale Image" Window.resize(width, height) Canvas.resize(width, height) _image1 = image1 _image2 = image2 _img1 = ImageData.loadFromFile(image1) _img2 = ImageData.create(image2, _img1.width, _img1.height) }   init() { toGrayScale() // display images side by side _img1.draw(0, 0) _img2.draw(550, 0) Canvas.print(_image1, 200, 525, Color.white) Canvas.print(_image2, 750, 525, Color.white) }   toGrayScale() { for (x in 0..._img1.width) { for (y in 0..._img1.height) { var c1 = _img1.pget(x, y) var lumin = (0.2126 * c1.r + 0.7152 * c1.g + 0.0722 * c1.b).floor var c2 = Color.rgb(lumin, lumin,lumin, c1.a) _img2.pset(x, y, c2) } } }   update() {}   draw(alpha) {} }   var Game = PercentageDifference.new(1100, 550, "Lenna100.jpg", "Lenna-grayscale.jpg")
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).
#Haskell
Haskell
hamming = 1 : map (2*) hamming `union` map (3*) hamming `union` map (5*) hamming   union a@(x:xs) b@(y:ys) = case compare x y of LT -> x : union xs b EQ -> x : union xs ys GT -> y : union a ys   main = do print $ take 20 hamming print (hamming !! (1691-1), hamming !! (1692-1)) print $ hamming !! (1000000-1)   -- Output: -- [1,2,3,4,5,6,8,9,10,12,15,16,18,20,24,25,27,30,32,36] -- (2125764000,2147483648) -- 519312780448388736089589843750000000000000000000000000000000000000000000000000000000
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
#min
min
randomize   9 random succ   "Guess my number between 1 and 10." puts!   ("Your guess" ask int over ==) 'pop ("Wrong." puts!) () linrec   "Well guessed!" puts!
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#MiniScript
MiniScript
num = ceil(rnd*10) while true x = val(input("Your guess?")) if x == num then print "Well guessed!" break end if end while
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.
#NetRexx
NetRexx
/* REXX *************************************************************** * 10.08.2012 Walter Pachl Pascal algorithm -> Rexx -> NetRexx **********************************************************************/ s=' -1 -2 3 5 6 -2 -1 4 -4 2 -1' maxSum = 0 seqStart = 0 seqEnd = -1 Loop i = 1 To s.words() seqSum = 0 Loop j = i to s.words() seqSum = seqSum + s.word(j) if seqSum > maxSum then Do maxSum = seqSum seqStart = i seqEnd = j end end end Say 'Sequence:' Say s Say 'Subsequence with greatest sum: ' If seqend<seqstart Then Say 'empty' Else Do ol=' '.copies(seqStart-1) Loop i = seqStart to seqEnd w=s.word(i) ol=ol||w.right(3) End Say ol Say 'Sum:' maxSum 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.
#Nim
Nim
proc maxsum(s: openArray[int]): int = var maxendinghere = 0 for x in s: maxendinghere = max(maxendinghere + x, 0) result = max(result, maxendinghere)   echo maxsum(@[-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1])
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#Genie
Genie
[indent=4] /* Number guessing with feedback, in Genie from https://wiki.gnome.org/Projects/Genie/AdvancedSample   valac numberGuessing.gs ./numberGuessing */ class NumberGuessing   prop min:int prop max:int   construct(m:int, n:int) self.min = m self.max = n   def start() try_count:int = 0 number:int = Random.int_range(min, max)   stdout.printf("Welcome to Number Guessing!\n\n") stdout.printf("I have thought up a number between %d and %d\n", min, max) stdout.printf("which you have to guess. I will give hints as we go.\n\n")   while true stdout.printf("Try #%d, ", ++try_count) stdout.printf("please enter a number between %d and %d: ", min, max) line:string? = stdin.read_line() if line is null stdout.printf("bailing...\n") break   input:int64 = 0 unparsed:string = "" converted:bool = int64.try_parse(line, out input, out unparsed) if not converted or line is unparsed stdout.printf("Sorry, input seems invalid\n") continue   guess:int = (int)input if number is guess stdout.printf("Congratulations! You win.\n") break else stdout.printf("Try again. The number in mind is %s than %d.\n", number > guess ? "greater" : "less", guess)   init var game = new NumberGuessing(1, 100) game.start()
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
#Icon_and_Unicon
Icon and Unicon
procedure main(arglist) local n n := arglist[1] | 8 # limiting number of happy numbers to generate, default=8 writes("The first ",n," happy numbers are:") every writes(" ", happy(seq()) \ n ) write() end   procedure happy(i) #: returns i if i is happy local n   if 4 ~= (0 <= i) then { # unhappy if negative, 0, or 4 if i = 1 then return i every (n := 0) +:= !i ^ 2 if happy(n) then return i } end
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, 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.
#smart_BASIC
smart BASIC
  '*** LAT/LONG for Nashville International Airport (BNA) lat1=36.12 Lon1=-86.67   '*** LAT/LONG for Los Angeles International Airport (LAX) Lat2=33.94 Lon2=-118.40   '*** Units: K=kilometers M=miles N=nautical miles Unit$ = "K"   Result=HAVERSINE(Lat1,Lon1,Lat2,Lon2,Unit$) R$=STR$(Result,"#,###.##")   PRINT "The distance between Nashville International Airport and Los Angeles International Airport in kilometers is: "&R$   STOP   DEF HAVERSINE(Lat1,Lon1,Lat2,Lon2,Unit$) '--------------------------------------------------------------- '*** Haversine Formula - Calculate distances by LAT/LONG '   '*** Pass to it the LAT/LONG of the two locations, and then unit of measure '*** Usage: X=HAVERSINE(Lat1,Lon1,Lat2,Lon2,Unit$)   PI=3.14159265358979323846 Radius=6372.8 Lat1=(Lat1*PI/180) Lon1=(Lon1*PI/180) Lat2=(Lat2*PI/180) Lon2=(Lon2*PI/180) DLon=Lon1-Lon2 Answer=ACOS(SIN(Lat1)*SIN(Lat2)+COS(Lat1)*COS(Lat2)*COS(DLon))*Radius   IF UNIT$="M" THEN Answer=Answer*0.621371192 IF UNIT$="N" THEN Answer=Answer*0.539956803   RETURN Answer   ENDDEF  
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.
#Stata
Stata
program spheredist version 15.0 syntax varlist(min=4 max=4 numeric), GENerate(namelist max=1) /// [Radius(real 6371) ALTitude(real 0) LABel(string)] confirm new variable `generate' local lat1 : word 1 of `varlist' local lon1 : word 2 of `varlist' local lat2 : word 3 of `varlist' local lon2 : word 4 of `varlist' local r=2*(`radius'+`altitude'/1000) local k=_pi/180 gen `generate'=`r'*asin(sqrt(sin((`lat2'-`lat1')*`k'/2)^2+ /// cos(`lat1'*`k')*cos(`lat2'*`k')*sin((`lon2'-`lon1')*`k'/2)^2)) if `"`label'"' != "" { label variable `generate' `"`label'"' } end
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#HolyC
HolyC
"Hello world!\n";
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/procedure to generate successive members of the Harshad sequence. Use it to:   list the first 20 members of the sequence,   and   list the first Harshad number greater than 1000. Show your output here. Related task   Increasing gaps between consecutive Niven numbers See also   OEIS: A005349
#Sidef
Sidef
func harshad() { var n = 0; { ++n while !(n %% n.digits.sum); n; } }   var iter = harshad(); say 20.of { iter.run };   var n; do { n = iter.run } while (n <= 1000);   say n;
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
#Oz
Oz
declare [QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']} Window = {QTk.build td(label(text:"Goodbye, World!"))} in {Window show}
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
#Panoramic
Panoramic
print "Goodbye, World!" 'Prints in the upper left corner of the window.  
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.
#K
K
xor: {~x=y} gray:{x[0],xor':x}   / variant: using shift gray1:{(x[0],xor[1_ x;-1_ x])}   / variant: iterative gray2:{x[0],{:[x[y-1]=1;~x[y];x[y]]}[x]'1+!(#x)-1}
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.
#Kotlin
Kotlin
// version 1.0.6   object Gray { fun encode(n: Int) = n xor (n shr 1)   fun decode(n: Int): Int { var p = n var nn = n while (nn != 0) { nn = nn shr 1 p = p xor nn } return p } }   fun main(args: Array<String>) { println("Number\tBinary\tGray\tDecoded") for (i in 0..31) { print("$i\t${Integer.toBinaryString(i)}\t") val g = Gray.encode(i) println("${Integer.toBinaryString(g)}\t${Gray.decode(g)}") } }
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
#Wren
Wren
/* get_system_command_output.wren */ class Command { foreign static output(name, param) // the code for this is provided by Go }   System.print(Command.output("ls", "-ls"))
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#Yabasic
Yabasic
// Rosetta Code problem: https://www.rosettacode.org/wiki/Get_system_command_output // by Jjuanhdez, 06/2022   if peek$("os") = "unix" then c$ = "ls *" else //"windows" c$ = "dir *.*" fi   open("dir_output.txt") for writing as #1 print #1 system$(c$) close #1
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
#zkl
zkl
zkl: System.cmd("date >foo.txt") 0 // date return code zkl: File("foo.txt").read().text Wed Aug 20 00:28:55 PDT 2014
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!
#Axe
Axe
Exch(°A,°B,2)
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.
#C
C
#include <assert.h>   float max(unsigned int count, float values[]) { assert(count > 0); size_t idx; float themax = values[0]; for(idx = 1; idx < count; ++idx) { themax = values[idx] > themax ? values[idx] : themax; } return themax; }
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.
#AWK
AWK
$ awk 'function gcd(p,q){return(q?gcd(q,(p%q)):p)}{print gcd($1,$2)}' 12 16 4 22 33 11 45 67 1
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.
#Ring
Ring
  filenames = ["ReadMe.txt", "ReadMe2.txt"]   for fn in filenames fp = fopen(fn,"r") str = fread(fp,getFileSize(fp)) str = substr(str, "Greetings", "Hello") fclose(fp)   fp = fopen(fn,"w") fwrite(fp, str) fclose(fp) next   func getFileSize fp C_FILESTART = 0 C_FILEEND = 2 fseek(fp,0,C_FILEEND) nFileSize = ftell(fp) fseek(fp,0,C_FILESTART) return nFileSize  
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.
#Ruby
Ruby
ruby -pi -e "gsub('Goodbye London!', 'Hello New York!')" a.txt b.txt c.txt
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.
#Run_BASIC
Run BASIC
file$(1) ="data1.txt" file$(2) ="data2.txt" file$(3) ="data3.txt"   for i = 1 to 3 open file$(i) for input as #in fileBefore$ = input$( #in, lof( #in)) close #in   fileAfter$ = strRep$(fileBefore$, "Goodbye London!", "Hello New York!") open "new_" + file$(i) for output as #out print #out,fileAfter$; close #out next i end   ' -------------------------------- ' string replace - rep str with ' -------------------------------- FUNCTION strRep$(str$,rep$,with$) ln = len(rep$) ln1 = ln - 1 i = 1 while i <= len(str$) if mid$(str$,i,ln) = rep$ then strRep$ = strRep$ + with$ i = i + ln1 else strRep$ = strRep$ + mid$(str$,i,1) end if i = i + 1 WEND END FUNCTION
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.
#Rust
Rust
  //! Author: Rahul Sharma //! Github: <https://github.com/creativcoder>   use std::fs::File; use std::fs::OpenOptions; use std::io::BufRead; use std::io::BufReader; use std::io::BufWriter; use std::io::Write;   fn main() { // opens file for writing replaced lines let out_fd = OpenOptions::new() .write(true) .create(true) .open("resources/output.txt");   // defining a closure write_line let write_line = |line: &str| match out_fd { Ok(ref v) => { let mut writer = BufWriter::new(v); writer.write_all(line.as_bytes()).unwrap(); } Err(ref e) => { println!("Error:{}", e); } }; // read input file match File::open("resources/paragraph.txt") { Ok(handle) => { let mut reader = BufReader::new(handle); let mut line = String::new(); // read the first line reader.read_line(&mut line).unwrap(); // loop until line end while line.trim() != "" { let mut replaced_line = line.trim().replace("Goodbye London!", "Hello New York!"); replaced_line += "\n"; write_line(&replaced_line[..]); line.clear(); reader.read_line(&mut line).unwrap(); } } Err(e) => println!("Error:{}", e), } }  
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).
#C
C
#include <stdio.h> #include <stdlib.h>   int hailstone(int n, int *arry) { int hs = 1;   while (n!=1) { hs++; if (arry) *arry++ = n; n = (n&1) ? (3*n+1) : (n/2); } if (arry) *arry++ = n; return hs; }   int main() { int j, hmax = 0; int jatmax, n; int *arry;   for (j=1; j<100000; j++) { n = hailstone(j, NULL); if (hmax < n) { hmax = n; jatmax = j; } } n = hailstone(27, NULL); arry = malloc(n*sizeof(int)); n = hailstone(27, arry);   printf("[ %d, %d, %d, %d, ...., %d, %d, %d, %d] len=%d\n", arry[0],arry[1],arry[2],arry[3], arry[n-4], arry[n-3], arry[n-2], arry[n-1], n); printf("Max %d at j= %d\n", hmax, jatmax); free(arry);   return 0; }
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.
#Yabasic
Yabasic
import image   open window 600,600   GetImage(1, "House.bmp") DisplayImage(1, 0, 0)   For x = 1 to 300 For y = 1 to 300 z$ = getbit$(x,y,x,y) r = dec(mid$(z$,9,2)) g = dec(mid$(z$,11,2)) b = dec(mid$(z$,13,2)) r3=(r+g+b)/3 g3=(r+g+b)/3 b3=(r+g+b)/3 color r3,g3,b3 dot x+300,y+300 next y next x
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.
#zkl
zkl
fcn toGrayScale(img){ // in-place conversion foreach x,y in (img.w,img.h){ r,g,b:=img[x,y].toBigEndian(3); lum:=(0.2126*r + 0.7152*g + 0.0722*b).toInt(); img[x,y]=((lum*256) + lum)*256 + lum; } }
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).
#Icon_and_Unicon
Icon and Unicon
# Lazily generate the three Hamming numbers that can be derived directly # from a known Hamming number h class Triplet : Class (cv, ce)   method nextVal() suspend cv := @ce end   initially (baseNum) cv := 2*baseNum ce := create (3|5)*baseNum end   # Generate Hamming numbers, in order. Default is first 30 # But an optional argument can be used to generate more (or less) # e.g. hamming 5000 generates the first 5000. procedure main(args) limit := integer(args[1]) | 30 every write("\t", generateHamming() \ limit) end   # Do the work. Start with known Hamming number 1 and maintain # a set of triplet Hamming numbers as they get derived from that # one. Most of the code here is to figure out which Hamming # number is next in sequence (while removing duplicates) procedure generateHamming() triplers := set() insert(triplers, Triplet(1))   suspend 1 repeat { # Pick a Hamming triplet that *may* have the next smallest number t1 := !triplers # any will do to start   every t1 ~=== (t2 := !triplers) do { if t1.cv > t2.cv then { # oops we were wrong, switch assumption t1 := t2 } else if t1.cv = t2.cv then { # t2's value is a duplicate, so # advance triplet t2, if none left in t2, remove it t2.nextVal() | delete(triplers, t2) } }   # Ok, t1 has the next Hamming number, grab it suspend t1.cv insert(triplers, Triplet(t1.cv)) # Advance triplet t1, if none left in t1, remove it t1.nextVal() | delete(triplers, t1) } 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
#MIPS_Assembly
MIPS Assembly
  # WRITTEN: August 26, 2016 (at midnight...)   # This targets MARS implementation and may not work on other implementations # Specifically, using MARS' random syscall .data take_a_guess: .asciiz "Make a guess:" good_job: .asciiz "Well guessed!"   .text #retrieve system time as a seed li $v0,30 syscall   #use the high order time stored in $a1 as the seed arg move $a1,$a0   #set the seed li $v0,40 syscall   #generate number 0-9 (random int syscall generates a number where): # 0 <= $v0 <= $a1 li $a1,10 li $v0,42 syscall   #increment the randomly generated number and store in $v1 add $v1,$a0,1   loop: jal print_take_a_guess jal read_int   #go back to beginning of loop if user hasn't guessed right, # else, just "fall through" to exit_procedure bne $v0,$v1,loop   exit_procedure: #set syscall to print_string, then set good_job string as arg li $v0,4 la $a0,good_job syscall   #exit program li $v0,10 syscall   print_take_a_guess: li $v0,4 la $a0,take_a_guess syscall jr $ra   read_int: li $v0,5 syscall jr $ra  
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
#Nanoquery
Nanoquery
random = new(Nanoquery.Util.Random) target = random.getInt(9) + 1 guess = 0   println "Guess a number between 1 and 10." while not target = guess guess = int(input()) end   println "That's right!"
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#Oberon-2
Oberon-2
  MODULE GreatestSubsequentialSum; IMPORT Out, Err, IntStr, ProgramArgs, TextRider; TYPE IntSeq= POINTER TO ARRAY OF LONGINT;   PROCEDURE ShowUsage(); BEGIN Out.String("Usage: GreatestSubsequentialSum {int}+");Out.Ln END ShowUsage;   PROCEDURE Gss(iseq: IntSeq; VAR start, end, maxsum: LONGINT); VAR i, j, sum: LONGINT; BEGIN i := 0; maxsum := 0; start := 0; end := -1; WHILE (i < LEN(iseq^)) DO sum := 0; j := i; WHILE (j < LEN(iseq^) - 1) DO INC(sum,iseq[j]); IF sum > maxsum THEN maxsum := sum; start := i; end := j END; INC(j) END; INC(i) END END Gss;     PROCEDURE GetParams():IntSeq; VAR reader: TextRider.Reader; iseq: IntSeq; param: ARRAY 32 OF CHAR; argc,i: LONGINT; res: SHORTINT; BEGIN iseq := NIL; reader := TextRider.ConnectReader(ProgramArgs.args); IF reader # NIL THEN argc := ProgramArgs.args.ArgNumber(); IF argc < 1 THEN Err.String("There is no enough arguments.");Err.Ln; ShowUsage; HALT(0) END;   reader.ReadLn; (* Skips program name *)   NEW(iseq,argc); FOR i := 0 TO argc - 1 DO reader.ReadLine(param); IntStr.StrToInt(param,iseq[i],res); END END; RETURN iseq END GetParams;   PROCEDURE Do; VAR iseq: IntSeq; start, end, sum, i: LONGINT; BEGIN iseq := GetParams(); Gss(iseq, start, end, sum); i := start; Out.String("["); WHILE (i <= end) DO Out.LongInt(iseq[i],0); IF (i < end) THEN Out.Char(',') END; INC(i) END; Out.String("]: ");Out.LongInt(sum,0);Out.Ln END Do;   BEGIN Do END GreatestSubsequentialSum.    
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)
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   const lower, upper = 1, 100   func main() { fmt.Printf("Guess integer number from %d to %d: ", lower, upper) rand.Seed(time.Now().Unix()) n := rand.Intn(upper-lower+1) + lower for guess := n; ; { switch _, err := fmt.Scan(&guess); { case err != nil: fmt.Println("\n", err, "So, bye.") return case guess < n: fmt.Print("Too low. Try again: ") case guess > n: fmt.Print("Too high. Try again: ") default: fmt.Println("Well guessed!") return } } }
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
#J
J
8{. (#~1=+/@(*:@(,.&.":))^:(1&~:*.4&~:)^:_ "0) 1+i.100 1 7 10 13 19 23 28 31
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, 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.
#Swift
Swift
import Foundation   func haversine(lat1:Double, lon1:Double, lat2:Double, lon2:Double) -> Double { let lat1rad = lat1 * Double.pi/180 let lon1rad = lon1 * Double.pi/180 let lat2rad = lat2 * Double.pi/180 let lon2rad = lon2 * Double.pi/180   let dLat = lat2rad - lat1rad let dLon = lon2rad - lon1rad let a = sin(dLat/2) * sin(dLat/2) + sin(dLon/2) * sin(dLon/2) * cos(lat1rad) * cos(lat2rad) let c = 2 * asin(sqrt(a)) let R = 6372.8   return R * c }   print(haversine(lat1:36.12, lon1:-86.67, lat2:33.94, lon2:-118.40))
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.
#Symsyn
Symsyn
  lat1 : 36.12 lon1 : -86.67 lat2 : 33.94 lon2 : -118.4   dx : 0. dy : 0. dz : 0. kms : 0.   {degtorad(lon2 - lon1)} lon1 {degtorad lat1} lat1 {degtorad lat2} lat2   {sin lat1 - sin lat2} dz {cos lon1 * cos lat1 - cos lat2} dx {sin lon1 * cos lat1} dy   {arcsin(sqrt(dx^2 + dy^2 + dz^2)/2) * 12745.6} kms   "'Haversine distance: ' kms ' kms'" []  
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
#Hoon
Hoon
~& "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
#Sinclair_ZX81_BASIC
Sinclair ZX81 BASIC
10 FAST 20 LET N=0 30 LET H=0 40 LET N=N+1 50 LET N$=STR$ N 60 LET SD=0 70 FOR I=1 TO LEN N$ 80 LET SD=SD+VAL N$(I) 90 NEXT I 100 IF N/SD<>INT (N/SD) THEN GOTO 40 110 LET H=H+1 120 IF H<=20 OR N>1000 THEN PRINT N 130 IF N>1000 THEN GOTO 150 140 GOTO 40 150 SLOW
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
#PARI.2FGP
PARI/GP
plotinit(1, 1, 1, 1); plotstring(1, "Goodbye, World!"); plotdraw([1, 0, 15]);
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
#Pascal
Pascal
program HelloWorldGraphical;   uses glib2, gdk2, gtk2;   var window: PGtkWidget;   begin gtk_init(@argc, @argv);   window := gtk_window_new (GTK_WINDOW_TOPLEVEL);   gtk_window_set_title (GTK_WINDOW (window), 'Goodbye, World'); g_signal_connect (G_OBJECT (window), 'delete-event', G_CALLBACK (@gtk_main_quit), NULL); gtk_widget_show_all (window);   gtk_main(); 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.
#Liberty_BASIC
Liberty BASIC
  for r =0 to 31 print " Decimal "; using( "###", r); " is "; B$ =dec2Bin$( r) print " binary "; B$; ". Binary "; B$; G$ =Bin2Gray$( dec2Bin$( r)) print " is "; G$; " in Gray code, or "; B$ =Gray2Bin$( G$) print B$; " in pure binary." next r   end   function Bin2Gray$( bin$) ' Given a binary number as a string, returns Gray code as a string. g$ =left$( bin$, 1) for i =2 to len( bin$) bitA =val( mid$( bin$, i -1, 1)) bitB =val( mid$( bin$, i, 1)) AXorB =bitA xor bitB g$ =g$ +str$( AXorB) next i Bin2Gray$ =g$ end function   function Gray2Bin$( g$) ' Given a Gray code as a string, returns equivalent binary num. ' as a string gl =len( g$) b$ =left$( g$, 1) for i =2 to len( g$) bitA =val( mid$( b$, i -1, 1)) bitB =val( mid$( g$, i, 1)) AXorB =bitA xor bitB b$ =b$ +str$( AXorB) next i Gray2Bin$ =right$( b$, gl) end function   function dec2Bin$( num) ' Given an integer decimal, returns binary equivalent as a string n =num dec2Bin$ ="" while ( num >0) dec2Bin$ =str$( num mod 2) +dec2Bin$ num =int( num /2) wend if ( n >255) then nBits =16 else nBits =8 dec2Bin$ =right$( "0000000000000000" +dec2Bin$, nBits) ' Pad to 8 bit or 16 bit end function   function bin2Dec( b$) ' Given a binary number as a string, returns decimal equivalent num. t =0 d =len( b$) for k =d to 1 step -1 t =t +val( mid$( b$, k, 1)) *2^( d -k) next k bin2Dec =t end function  
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!
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion set a=1 set b=woof echo %a% echo %b% call :swap a b echo %a% echo %b% goto :eof   :swap set temp1=!%1! set temp2=!%2! set %1=%temp2% set %2=%temp1% goto :eof
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.
#C.23
C#
int[] values = new int[] {1,2,3,4,5,6,7,8,9,10};   int max = values.Max();
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#Axe
Axe
Lbl GCD r₁→A r₂→B !If B A Return End GCD(B,A^B)
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.
#Scala
Scala
import java.io.{File, PrintWriter}   object GloballyReplaceText extends App {   val (charsetName, fileNames) = ("UTF8", Seq("file1.txt", "file2.txt")) for (fileHandle <- fileNames.map(new File(_))) new PrintWriter(fileHandle, charsetName) { print(scala.io.Source.fromFile(fileHandle, charsetName).mkString .replace("Goodbye London!", "Hello New York!")) close() }   }
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.
#Sed
Sed
sed -i 's/Goodbye London!/Hello New York!/g' a.txt b.txt c.txt
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.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "getf.s7i";   const proc: main is func local var string: fileName is ""; var string: content is ""; begin for fileName range [] ("a.txt", "b.txt", "c.txt") do content := getf(fileName); content := replace(content, "Goodbye London!", "Hello New York!"); putf(fileName, content); end for; end func;
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).
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace Hailstone { class Program { public static List<int> hs(int n,List<int> seq) { List<int> sequence = seq; sequence.Add(n); if (n == 1) { return sequence; }else{ int newn = (n % 2 == 0) ? n / 2 : (3 * n) + 1; return hs(newn, sequence); } }   static void Main(string[] args) { int n = 27; List<int> sequence = hs(n,new List<int>()); Console.WriteLine(sequence.Count + " Elements"); List<int> start = sequence.GetRange(0, 4); List<int> end = sequence.GetRange(sequence.Count - 4, 4); Console.WriteLine("Starting with : " + string.Join(",", start) + " and ending with : " + string.Join(",", end)); int number = 0, longest = 0; for (int i = 1; i < 100000; i++) { int count = (hs(i, new List<int>())).Count; if (count > longest) { longest = count; number = i; } } Console.WriteLine("Number < 100000 with longest Hailstone seq.: " + number + " with length of " + longest); } } }
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).
#J
J
hamming=: {. (/:~@~.@] , 2 3 5 * {)/@(1x ,~ i.@-)
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   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
#Nemerle
Nemerle
using System; using System.Console;   module Guess { Main() : void { def rand = Random(); def x = rand.Next(1, 11); // returns 1 <= x < 11 mutable guess = 0;   do { WriteLine("Guess a nnumber between 1 and 10:"); guess = Int32.Parse(ReadLine()); } while (guess != x);   WriteLine("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.
#OCaml
OCaml
let maxsubseq = let rec loop sum seq maxsum maxseq = function | [] -> maxsum, List.rev maxseq | x::xs -> let sum = sum + x and seq = x :: seq in if sum < 0 then loop 0 [] maxsum maxseq xs else if sum > maxsum then loop sum seq sum seq xs else loop sum seq maxsum maxseq xs in loop 0 [] 0 []   let _ = maxsubseq [-1 ; -2 ; 3 ; 5 ; 6 ; -2 ; -1 ; 4; -4 ; 2 ; -1]
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#Groovy
Groovy
  def rand = new Random() // java.util.Random def range = 1..100 // Range (inclusive) def number = rand.nextInt(range.size()) + range.from // get a random number in the range   println "The number is in ${range.toString()}" // print the range   def guess while (guess != number) { // keep running until correct guess try { print 'Guess the number: ' guess = System.in.newReader().readLine() as int // read the guess in as int switch (guess) { // check the guess against number case { it < number }: println 'Your guess is too low'; break case { it > number }: println 'Your guess is too high'; break default: println 'Your guess is spot on!'; break } } catch (NumberFormatException ignored) { // catches all input that is not a number println 'Please enter a number!' } }  
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
#Java
Java
import java.util.HashSet; public class Happy{ public static boolean happy(long number){ long m = 0; int digit = 0; HashSet<Long> cycle = new HashSet<Long>(); while(number != 1 && cycle.add(number)){ m = 0; while(number > 0){ digit = (int)(number % 10); m += digit*digit; number /= 10; } number = m; } return number == 1; }   public static void main(String[] args){ for(long num = 1,count = 0;count<8;num++){ if(happy(num)){ System.out.println(num); count++; } } } }
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.
#tbas
tbas
  OPTION angle radians ' the default SUB haversine(lat1, lon1, lat2, lon2) DIM EarthRadiusKm = 6372.8 ' Earth radius in kilometers DIM latRad1 = RAD(lat1) DIM latRad2 = RAD(lat2) DIM lonRad1 = RAD(lon1) DIM lonRad2 = RAD(lon2) DIM _diffLa = latRad2 - latRad1 DIM _doffLo = lonRad2 - lonRad1 DIM sinLaSqrd = SIN(_diffLa / 2) ^ 2 DIM sinLoSqrd = SIN(_doffLo / 2) ^ 2 DIM computation = asin(sqrt(sinLaSqrd + COS(latRad1) * COS(latRad2) * sinLoSqrd)) RETURN 2 * EarthRadiusKm * computation END SUB   PRINT USING "Nashville International Airport to Los Angeles International Airport ####.########### km", haversine(36.12, -86.67, 33.94, -118.40) PRINT USING "Perth, WA Australia to Baja California, Mexico #####.########### km", haversine(-31.95, 115.86, 31.95, -115.86)  
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
#HPPPL
HPPPL
PRINT("Hello world!");
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/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
#Swift
Swift
struct Harshad: Sequence, IteratorProtocol { private var i = 0   mutating func next() -> Int? { while true { i += 1   if i % Array(String(i)).map(String.init).compactMap(Int.init).reduce(0, +) == 0 { return i } } } }   print("First 20: \(Array(Harshad().prefix(20)))") print("First over a 1000: \(Harshad().first(where: { $0 > 1000 })!)")
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
#Perl
Perl
  use strict; use warnings; use Tk;   my $main = MainWindow->new; $main->Label(-text => 'Goodbye, World')->pack; MainLoop();
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
#Phix
Phix
include pGUI.e IupOpen() IupMessage("Bye","Goodbye, World!") IupClose()
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.
#Limbo
Limbo
implement Gray;   include "sys.m"; sys: Sys; print: import sys; include "draw.m";   Gray: module { init: fn(nil: ref Draw->Context, args: list of string); # Export gray and grayinv so that this module can be used as either a # standalone program or as a library: gray: fn(n: int): int; grayinv: fn(n: int): int; };   init(nil: ref Draw->Context, args: list of string) { sys = load Sys Sys->PATH; for(i := 0; i < 32; i++) { g := gray(i); f := grayinv(g); print("%2d  %5s  %2d  %5s  %5s  %2d\n", i, binstr(i), g, binstr(g), binstr(f), f); } }   gray(n: int): int { return n ^ (n >> 1); }   grayinv(n: int): int { r := 0; while(n) { r ^= n; n >>= 1; } return r; }   binstr(n: int): string { if(!n) return "0"; s := ""; while(n) { s = (string (n&1)) + s; n >>= 1; } return s; }
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.
#Lobster
Lobster
def grey_encode(n) -> int: return n ^ (n >> 1)   def grey_decode(n) -> int: var p = n n = n >> 1 while n != 0: p = p ^ n n = n >> 1 return p   for(32) i: let g = grey_encode(i) let b = grey_decode(g) print(number_to_string(i, 10, 2) + " : " + number_to_string(i, 2, 5) + " ⇾ " + number_to_string(g, 2, 5) + " ⇾ " + number_to_string(b, 2, 5) + " : " + number_to_string(b, 10, 2))
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!
#BaCon
BaCon
  x = 1 y$ = "hello"   SWAP x, y$ PRINT y$  
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.
#C.2B.2B
C++
#include <algorithm> //std::max_element #include <iterator> //std::begin and std::end #include <functional> //std::less   template<class It, class Comp = std::less<>> //requires ForwardIterator<It> && Compare<Comp> constexpr auto max_value(It first, It last, Comp compare = std::less{}) { //Precondition: first != last return *std::max_element(first, last, compare); }   template<class C, class Comp = std::less<>> //requires Container<C> && Compare<Comp> constexpr auto max_value(const C& container, Comp compare = std::less{}) { //Precondition: !container.empty() using std::begin; using std::end; return max_value(begin(container), end(container), compare); }
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.
#BASIC
BASIC
FUNCTION gcd(a%, b%) IF a > b THEN factor = a ELSE factor = b END IF FOR l = factor TO 1 STEP -1 IF a MOD l = 0 AND b MOD l = 0 THEN gcd = l END IF NEXT l gcd = 1 END FUNCTION
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.
#Sidef
Sidef
var names = %w( a.txt b.txt c.txt )   names.map{ File(_) }.each { |file| say file.edit { |line| line.gsub("Goodbye London!", "Hello New York!") } }
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#Tcl
Tcl
package require Tcl 8.5 package require fileutil   # Parameters to the replacement set from "Goodbye London!" set to "Hello New York!" # Which files to replace set fileList [list a.txt b.txt c.txt]   # Make a command fragment that performs the replacement on a supplied string set replacementCmd [list string map [list $from $to]] # Apply the replacement to the contents of each file foreach filename $fileList { fileutil::updateInPlace $filename $replacementCmd }
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.
#Transd
Transd
#lang transd   MainModule: { _start: (λ (with files ["a.txt" "b.txt" "c.txt"] fs FileStream() (for f in files do (open-r fs f) (with s (replace (read-text fs) "Goodbye London!" "Hello New York!") (close fs) (open-w fs f) (write fs (to-bytes s) (size s))))) ) }
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).
#C.2B.2B
C++
#include <iostream> #include <vector> #include <utility>   std::vector<int> hailstone(int i) { std::vector<int> v; while(true){ v.push_back(i); if (1 == i) break; i = (i % 2) ? (3 * i + 1) : (i / 2); } return v; }   std::pair<int,int> find_longest_hailstone_seq(int n) { std::pair<int, int> maxseq(0, 0); int l; for(int i = 1; i < n; ++i){ l = hailstone(i).size(); if (l > maxseq.second) maxseq = std::make_pair(i, l); } return maxseq; }   int main () {   // Use the routine to show that the hailstone sequence for the number 27 std::vector<int> h27; h27 = hailstone(27); // has 112 elements int l = h27.size(); std::cout << "length of hailstone(27) is " << l; // starting with 27, 82, 41, 124 and std::cout << " first four elements of hailstone(27) are "; std::cout << h27[0] << " " << h27[1] << " " << h27[2] << " " << h27[3] << std::endl; // ending with 8, 4, 2, 1 std::cout << " last four elements of hailstone(27) are " << h27[l-4] << " " << h27[l-3] << " " << h27[l-2] << " " << h27[l-1] << std::endl;   std::pair<int,int> m = find_longest_hailstone_seq(100000);   std::cout << "the longest hailstone sequence under 100,000 is " << m.first << " with " << m.second << " elements." <<std::endl;   return 0; }
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In 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).
#Java
Java
import java.math.BigInteger; import java.util.PriorityQueue;   final class Hamming { private static BigInteger THREE = BigInteger.valueOf(3); private static BigInteger FIVE = BigInteger.valueOf(5);   private static void updateFrontier(BigInteger x, PriorityQueue<BigInteger> pq) { pq.offer(x.shiftLeft(1)); pq.offer(x.multiply(THREE)); pq.offer(x.multiply(FIVE)); }   public static BigInteger hamming(int n) { if (n <= 0) throw new IllegalArgumentException("Invalid parameter"); PriorityQueue<BigInteger> frontier = new PriorityQueue<BigInteger>(); updateFrontier(BigInteger.ONE, frontier); BigInteger lowest = BigInteger.ONE; for (int i = 1; i < n; i++) { lowest = frontier.poll(); while (frontier.peek().equals(lowest)) frontier.poll(); updateFrontier(lowest, frontier); } return lowest; }   public static void main(String[] args) { System.out.print("Hamming(1 .. 20) ="); for (int i = 1; i < 21; i++) System.out.print(" " + hamming(i)); System.out.println("\nHamming(1691) = " + hamming(1691)); System.out.println("Hamming(1000000) = " + hamming(1000000)); } }
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#NetRexx
NetRexx
/* NetRexx */   options replace format comments java crossref savelog symbols nobinary   guessThis = (Math.random * 10 + 1) % 1 guess = -1 prompt = [ - 'Try guessing a number between 1 and 10', - 'Wrong; try again...' - ] promptIdx = int 0   loop label g_ until guess = guessThis say prompt[promptIdx] promptIdx = 1 parse ask guess . if guess = guessThis then do say 'Well guessed!' guess 'is the correct number.' leave g_ end end g_   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
#NewLISP
NewLISP
; guess-number.lsp ; oofoe 2012-01-19 ; http://rosettacode.org/wiki/Guess_the_number   (seed (time-of-day)) ; Initialize random number generator from clock. (setq number (+ 1 (rand 10)))   (println "I'm thinking of a number between 1 and 10. Can you guess it?") (print "Type in your guess and hit [enter]: ") (while (!= number (int (read-line))) (print "Nope! Try again: ")) (println "Well guessed! Congratulations!")   (exit)
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.
#Oz
Oz
declare fun {MaxSubSeq Xs}   fun {Step [Sum0 Seq0 MaxSum MaxSeq] X} Sum = Sum0 + X Seq = X|Seq0 in if Sum > MaxSum then %% found new maximum [Sum Seq Sum Seq] elseif Sum < 0 then %% discard negative subseqs [0 nil MaxSum MaxSeq] else [Sum Seq MaxSum MaxSeq] end end   [_ _ _ MaxSeq] = {FoldL Xs Step [0 nil 0 nil]} in {Reverse MaxSeq} end in {Show {MaxSubSeq [~1 ~2 3 5 6 ~2 ~1 4 ~4 2 1]}}
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#PARI.2FGP
PARI/GP
grsub(v)={ my(mn=1,mx=#v,r=0,at,c); if(vecmax(v)<=0,return([1,0])); while(v[mn]<=0,mn++); while(v[mx]<=0,mx--); for(a=mn,mx, c=0; for(b=a,mx, c+=v[b]; if(c>r,r=c;at=[a,b]) ) ); at };
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)
#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 = case compare ans guess of LT -> putStrLn "Too high. Guess again." >> return False EQ -> putStrLn "You got it!" >> return True GT -> putStrLn "Too low. Guess again." >> return False   -- Repeatedly read until the input *starts* with a number. (Since -- we use "reads" we allow garbage to follow it, though.) ask = do line <- getLine case reads line of ((num,_):_) -> return num otherwise -> putStrLn "Please enter a number." >> ask   main = do ans <- randomRIO (1,100) :: IO Int putStrLn "Try to guess my secret number between 1 and 100." ask `until_` answerIs ans  
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
#JavaScript
JavaScript
function happy(number) { var m, digit ; var cycle = [] ;   while(number != 1 && cycle[number] !== true) { cycle[number] = true ; m = 0 ; while (number > 0) { digit = number % 10 ; m += digit * digit ; number = (number - digit) / 10 ; } number = m ; } return (number == 1) ; }   var cnt = 8 ; var number = 1 ;   while(cnt-- > 0) { while(!happy(number)) number++ ; document.write(number + " ") ; number++ ; }
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.
#Tcl
Tcl
package require Tcl 8.5 proc haversineFormula {lat1 lon1 lat2 lon2} { set rads [expr atan2(0,-1)/180] set R 6372.8 ;# In kilometers   set dLat [expr {($lat2-$lat1) * $rads}] set dLon [expr {($lon2-$lon1) * $rads}] set lat1 [expr {$lat1 * $rads}] set lat2 [expr {$lat2 * $rads}]   set a [expr {sin($dLat/2)**2 + sin($dLon/2)**2*cos($lat1)*cos($lat2)}] set c [expr {2*asin(sqrt($a))}] return [expr {$R * $c}] }   # Don't bother with too much inappropriate accuracy! puts [format "distance=%.1f km" [haversineFormula 36.12 -86.67 33.94 -118.40]]