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,   a...
#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,   a...
#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::i...
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#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;  ...
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#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...
#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] i...
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 score...
#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 T...
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#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 $ ta...
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#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-elli...
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#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( ...
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/...
#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: h...
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<...
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The follow...
#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 follow...
#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,TX...
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 r...
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 ...
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#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 tas...
#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 ...
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#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 u...
#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 ...
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 ...
#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 !! ...
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#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,   a...
#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 th...
#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() ...
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#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...
#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() ...
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#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, ...
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#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 di...
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#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...
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/...
#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 follow...
#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 follow...
#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\tG...
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 t...
#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 tas...
#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 fse...
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 #ou...
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(...
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#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;   ...
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 u...
#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 u...
#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 ...
#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 ord...
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#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...
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#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 th...
#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 ...
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...
#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); ...
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#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, g...
#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 - lon1r...
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#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   "'Hav...
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/...
#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', ...
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The follow...
#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   ...
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#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 tas...
#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 ...
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!"); ...
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#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) { ...
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 ...
#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,   a...
#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()); ...
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#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 el...
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...
#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 ...
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#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);...
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#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 ...
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/...
#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("Firs...
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 follow...
#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; };...
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The follow...
#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,...
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#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: firs...
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#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 $...
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) ...
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#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...
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 ...
#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<BigInt...
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#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] promptId...
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#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 (!...
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#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] ...
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#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...
#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 ...
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#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 ; } ...
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#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 [ex...