task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#Run_BASIC
Run BASIC
D2R = atn(1)/45 diam = 2 * 6372.8 Lg1m2 = ((-86.67)-(-118.4)) * D2R Lt1 = 36.12 * D2R ' degrees to rad Lt2 = 33.94 * D2R dz = sin(Lt1) - sin(Lt2) dx = cos(Lg1m2) * cos(Lt1) - cos(Lt2) dy = sin(Lg1m2) * cos(Lt1) hDist = asn((dx^2 + dy^2 + dz^2)^0.5 /2) * diam print "Haversine dis...
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...
#Rust
Rust
  use std::f64;   static R: f64 = 6372.8;   struct Point { lat: f64, lon: f64, }   fn haversine(mut origin: Point, mut destination: Point) -> f64 { origin.lon -= destination.lon; origin.lon = origin.lon.to_radians(); origin.lat = origin.lat.to_radians(); destination.lat = destination.lat.to_radi...
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
#Haskell
Haskell
  main = putStrLn "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/...
#Run_BASIC
Run BASIC
while count < 20 h = h + 1 if neven(h) = 0 then count = count + 1 print count;": ";h end if wend   h = 1000 while 1 = 1 h = h + 1 if neven(h) = 0 then print h exit while end if wend   function neven(h) h$ = str$(h) for i = 1 to len(h$) d = d + val(mid$(h$,i,1)) next i neven = h mod d end fu...
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
#NS-HUBASIC
NS-HUBASIC
10 LOCATE 6,11 20 PRINT "GOODBYE, WORLD!"
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Nyquist
Nyquist
;nyquist plug-in ;version 4 ;type tool ;name "Goodbye World"   (print "Goodbye, World!")
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The follow...
#Frink
Frink
  for i=0 to 31 { gray = binaryToGray[i] back = grayToBinary[gray] println[(i->binary) + "\t" + (gray->binary) + "\t" + (back->binary)] }  
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...
#Go
Go
package main   import "fmt"   func enc(b int) int { return b ^ b>>1 }   func dec(g int) (b int) { for ; g != 0; g >>= 1 { b ^= g } return }   func main() { fmt.Println("decimal binary gray decoded") for b := 0; b < 32; b++ { g := enc(b) d := dec(g) fmt.Print...
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
#Python
Python
>>> import subprocess >>> returned_text = subprocess.check_output("dir", shell=True, universal_newlines=True) >>> type(returned_text) <class 'str'> >>> print(returned_text) Volume in drive C is Windows Volume Serial Number is 44X7-73CE   Directory of C:\Python33   04/07/2013 06:40 <DIR> . 04/07/2013 06...
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
#Quackery
Quackery
/O> $ / ... import subprocess ... string_to_stack(str(subprocess.check_output('ls'),encoding='utf-8')) ... / python ... reverse echo$ ... ykq.kcudeltrut yrdnus yp.yrekcauq ykq.Xsnoisnetxe ykq.targib fdp.yrekcauQ fo kooB ehT fdp.tnirp rof yrekcauQ fo kooB ehT txt.TSRIF EM DAER fdp.ecnerefeR kciuQ yrekcauQ
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...
#Arc
Arc
(mac myswap (a b) (w/uniq gx `(let ,gx a (= a b) (= b ,gx))))   (with (a 1 b 2) (myswap a b) (prn "a:" a #\Newline "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.
#Befunge
Befunge
001pv < >&:01g`#v_1+#^_01g.@ ^p10 <
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...
#Arendelle
Arendelle
< a , b > ( r , @a ) [ @r != 0 , ( r , @a % @b ) { @r != 0 , ( a , @b ) ( b , @r ) } ] ( return , @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.
#Pascal
Pascal
Program StringReplace;   uses Classes, StrUtils;   const fileName: array[1..3] of string = ('a.txt', 'b.txt', 'c.txt'); matchText = 'Goodbye London!'; replaceText = 'Hello New York!';   var AllText: TStringlist; i, j: integer;   begin for j := low(fileName) to high(fileName) do begin AllText := TStri...
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.
#Perl
Perl
perl -pi -e "s/Goodbye London\!/Hello New York\!/g;" a.txt b.txt c.txt
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...
#BQN
BQN
Collatz ← ⥊⊸{ 𝕨𝕊1: 𝕨; (𝕨⊸∾ 𝕊 ⊢) (2|𝕩)⊑⟨𝕩÷2⋄1+3×𝕩⟩ }   Collatz1 ← ⌽∘{ 1: ⟨1⟩; 𝕩∾˜𝕊(2|𝕩)⊑⟨𝕩÷2⋄1+3×𝕩⟩ }   •Show Collatz1 5   •Show (⊑∾≠){𝕩⊑˜⊑⍒≠¨𝕩}Collatz1¨1+↕99999
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...
#Scala
Scala
object BitmapOps { def luminosity(c:Color)=(0.2126*c.getRed + 0.7152*c.getGreen + 0.0722*c.getBlue+0.5).toInt   def grayscale(bm:RgbBitmap)={ val image=new RgbBitmap(bm.width, bm.height) for(x <- 0 until bm.width; y <- 0 until bm.height; l=luminosity(bm.getPixel(x,y))) image.setPixel(x, y, ne...
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...
#Sidef
Sidef
require('Image::Imlib2')   func tograyscale(img) { var (width, height) = (img.width, img.height) var gimg = %s'Image::Imlib2'.new(width, height) for y,x in (^height ~X ^width) { var (r, g, b) = img.query_pixel(x, y) var gray = int(0.2126*r + 0.7152*g + 0.0722*b) gimg.set_color(gray, ...
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 ...
#FunL
FunL
native scala.collection.mutable.Queue   val hamming = q2 = Queue() q3 = Queue() q5 = Queue()   def enqueue( n ) = q2.enqueue( n*2 ) q3.enqueue( n*3 ) q5.enqueue( n*5 )   def stream = val n = min( min(q2.head(), q3.head()), q5.head() )   if q2.head() == n then q2.dequeue() if q3.head() ...
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...
#LOLCODE
LOLCODE
HAI 1.3   VISIBLE "SEED ME, FEMUR! "! I HAS A seed, GIMMEH seed   HOW IZ I randomizin seed R MOD OF SUM OF 1 AN PRODUKT OF 69069 AN seed AN 10 IF U SAY SO   I IZ randomizin MKAY I HAS A answer ITZ SUM OF seed AN 1 I HAS A guess   IM IN YR guesser VISIBLE "WUTS MY NUMBR? "! GIMMEH guess, guess IS NOW A NUMBR...
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...
#Lua
Lua
math.randomseed( os.time() ) n = math.random( 1, 10 )   print( "I'm thinking of a number between 1 and 10. Try to guess it: " )   repeat x = tonumber( io.read() )   if x == n then print "Well guessed!" else print "Guess again: " end until x == n
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...
#Liberty_BASIC
Liberty BASIC
  'Greatest_subsequential_sum   N= 20 'number of elements   randomize 0.52 for K = 1 to 5 a$ = using("##",int(rnd(1)*12)-5) for i=2 to N a$ = a$ +","+using("##",int(rnd(1)*12)-5) next call maxsumseq a$ next K   sub maxsumseq a$ sum=0 maxsum=0 sumStart=1 end1 =0 start1 =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...
#FOCAL
FOCAL
01.01 S T=0 01.02 A "LOWER LIMIT",L 01.03 A "UPPER LIMIT",H 01.04 I (H-L)1.05,1.05,1.06 01.05 T "INVALID RANGE",!;G 1.02 01.06 S S=FITR(L+FRAN()*(H-L+1)) 01.10 A "GUESS",G 01.11 I (H-G)1.13,1.12,1.12 01.12 I (G-L)1.13,1.14,1.14 01.13 T "OUT OF RANGE",!;G 1.1 01.14 S T=T+1 01.15 I (G-S)1.16,1.17,1.18 01.16 T "TOO LOW!",...
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...
#UNIX_Shell
UNIX Shell
read -p "Lower bound: " lower read -p "Upper bound: " upper moves=0 PS3="> " while :; do ((moves++)) guess=$(( lower + (upper-lower)/2 )) echo "Is it $guess?" select ans in "too small" "too big" "got it!"; do case $ans in "got it!") break 2 ;; "too big") upper=$(( upp...
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...
#Go
Go
package main   import "fmt"   func happy(n int) bool { m := make(map[int]bool) for n > 1 { m[n] = true var x int for x, n = n, 0; x > 0; x /= 10 { d := x % 10 n += d * d } if m[n] { return false } } return true }   func main() { for found, n := 0, 1; found < 8; n++ { if happy(n) { fmt.Pri...
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...
#SAS
SAS
  options minoperator;   %macro haver(lat1, long1, lat2, long2, type=D, dist=K);   %if %upcase(&type) in (D DEG DEGREE DEGREES) %then %do; %let convert = constant('PI')/180; %end; %else %if %upcase(&type) in (R RAD RADIAN RADIANS) %then %do; %let convert = 1; %end; %else %do; %put ERROR - Enter RADIANS or ...
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
#Haxe
Haxe
trace("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/...
#Rust
Rust
  fn is_harshad (n : u32) -> bool { let sum_digits = n.to_string() .chars() .map(|c| c.to_digit(10).unwrap()) .fold(0, |a, b| a+b); n % sum_digits == 0 }   fn main() { for i in (1u32..).filter(|num| is_harshad(*num)).take(20) { printl...
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
#Objeck
Objeck
  use Qt;   bundle Default { class QtExample { function : Main(args : String[]) ~ Nil { app := QAppliction->New(); win := QWidget->New(); win->Resize(400, 300); win->SetWindowTitle("Goodbye, World!"); win->Show(); app->Exec(); app->Delete(); } } }  
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...
#Groovy
Groovy
def grayEncode = { i -> i ^ (i >>> 1) }   def grayDecode; grayDecode = { int code -> if(code <= 0) return 0 def h = grayDecode(code >>> 1) return (h << 1) + ((code ^ h) & 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...
#Haskell
Haskell
import Data.Bits import Data.Char import Numeric import Control.Monad import Text.Printf   grayToBin :: (Integral t, Bits t) => t -> t grayToBin 0 = 0 grayToBin g = g `xor` (grayToBin $ g `shiftR` 1)   binToGray :: (Integral t, Bits t) => t -> t binToGray b = b `xor` (b `shiftR` 1)   showBinary :: (Integral t, Show t) ...
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
#R
R
  system("wc -l /etc/passwd /etc/group", intern = TRUE)  
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
#Racket
Racket
#lang racket/base   (require racket/system (only-in racket/port with-output-to-string) tests/eli-tester)   (test  ;; system runs command and outputs to current output port (which is stdout unless we catch it) (system "ls /etc/motd") => #t  ;; it throws an error on non-zero exit code (so I need to cat...
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
#Raku
Raku
say run($command, $arg1, $arg2, :out).out.slurp;
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
#REXX
REXX
/*REXX program executes a system command and displays the results (from an array). */ parse arg xxxCmd /*obtain the (system) command from CL.*/ trace off /*suppress REXX error msgs for fails. */ @.= 0 ...
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#Arturo
Arturo
swap: function [a,b]-> @[b,a]   c: 1 d: 2 print [c d]   [c,d]: swap c d print [c d]
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.
#BQN
BQN
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...
#Arturo
Arturo
print gcd [10 15]
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.
#Phix
Phix
without js -- file i/o procedure global_replace(string s, string r, sequence file_list) for i=1 to length(file_list) do string filename = file_list[i] integer fn = open(filename,"rb") if fn=-1 then ?9/0 end if -- message/retry? string text = get_text(fn) close(fn) t...
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.
#PicoLisp
PicoLisp
(for File '(a.txt b.txt c.txt) (call 'mv File (tmp File)) (out File (in (tmp File) (while (echo "Goodbye London!") (prin "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...
#Bracmat
Bracmat
( ( hailstone = L len .  !arg:?L & whl ' ( !arg:~1 & (!arg*1/2:~/|3*!arg+1):?arg & !arg !L:?L ) & (!L:? [?len&!len.!L) ) & ( reverse = L e .  :?L & whl'(!arg:%?e ?arg&!e !L:?L) & !L ) & hailstone$27:(?len.?list) & reverse$!list:?fir...
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...
#Tcl
Tcl
package require Tk   proc grayscale image { set w [image width $image] set h [image height $image] for {set x 0} {$x<$w} {incr x} { for {set y 0} {$y<$h} {incr y} { lassign [$image get $x $y] r g b set l [expr {int(0.2126*$r + 0.7152*$g + 0.0722*$b)}] $image put [...
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...
#Vedit_macro_language
Vedit macro language
// Convert RGB image to grayscale (8 bit/pixel) // #10 = buffer that contains image data // On return: // #20 = buffer for the new grayscale image   :RGB_TO_GRAYSCALE: File_Open("|(VEDIT_TEMP)\gray.data", OVERWRITE+NOEVENT+NOMSG) #20 = Buf_Num BOF Del_Char(ALL) Buf_Switch(#10) Repeat(File_Size/3) { #9 = Cu...
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 ...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "math/big" )   func min(a, b *big.Int) *big.Int { if a.Cmp(b) < 0 { return a } return b }   func hamming(n int) []*big.Int { h := make([]*big.Int, n) h[0] = big.NewInt(1) two, three, five := big.NewInt(2), big.NewInt(3), big.NewInt(5) next2, 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...
#M2000_Interpreter
M2000 Interpreter
  Module QBASIC_Based { supervisor: GOSUB initialize GOSUB guessing GOTO continue   initialize: \\ Not need to RANDOMIZE TIMER \\ we can use Random(1, 100) to get a number from 1 to 100 n = 0: r = INT(RND * 100 + 1): g = 0: c$ = "" RETURN   guessing: WHI...
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...
#Maple
Maple
GuessNumber := proc() local number; randomize(): printf("Guess a number between 1 and 10 until you get it right:\n:"); number := rand(1..10)(); while parse(readline()) <> number do printf("Try again!\n:"); end do: printf("Well guessed! The answer was %d.\n", number); end proc:
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...
#Lua
Lua
function sumt(t, start, last) return start <= last and t[start] + sumt(t, start+1, last) or 0 end function maxsub(ary, idx) local idx = idx or 1 if not ary[idx] then return {} end local maxsum, last = 0, idx for i = idx, #ary do if sumt(ary, idx, i) > maxsum then maxsum, last = sumt(ary, idx, i), i end en...
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...
#Fortran
Fortran
program Guess_a_number implicit none   integer, parameter :: limit = 100 integer :: guess, number real :: rnum   write(*, "(a, i0, a)") "I have chosen a number between 1 and ", limit, & " and you have to try to guess it." write(*, "(a/)") "I will score your guess by indicating whe...
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...
#VBA
VBA
  Sub GuessNumberPlayer() Dim iGuess As Integer, iLow As Integer, iHigh As Integer, iCount As Integer Dim vSolved As Variant On Error GoTo ErrHandler MsgBox "Pick a number between 1 and 100. I will guess it!", vbInformation + vbOKOnly, "Rosetta Code | Guess the Number Player" iCount = 0 iLow = 1 iHigh = 100 Do While No...
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...
#Wren
Wren
import "io" for Stdin, Stdout import "/str" for Char   var hle var lowest = 1 var highest = 20 var guess = 10 System.print("Please choose a number between 1 and 20 but don't tell me what it is yet\n")   while (true) { System.print("My guess is %(guess)") while (true) { System.write("Is this higher/lower...
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...
#Groovy
Groovy
Number.metaClass.isHappy = { def number = delegate as Long def cycle = new HashSet<Long>() while (number != 1 && !cycle.contains(number)) { cycle << number number = (number as String).collect { d = (it as Long); d * d }.sum() } number == 1 }   def matches = [] for (int i = 0; matches...
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...
#Scala
Scala
import math._   object Haversine { val R = 6372.8 //radius in km   def haversine(lat1:Double, lon1:Double, lat2:Double, lon2:Double)={ val dLat=(lat2 - lat1).toRadians val dLon=(lon2 - lon1).toRadians   val a = pow(sin(dLat/2),2) + pow(sin(dLon/2),2) * cos(lat1.toRadians) * cos(lat2.toRadians) ...
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
#hexiscript
hexiscript
println "Hello world!"
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#Scala
Scala
object Harshad extends App { val harshads = Stream.from(1).filter(i => i % i.toString.map(_.asDigit).sum == 0)   println(harshads.take(20).toList) println(harshads.filter(_ > 1000).head) }
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
#Objective-C
Objective-C
NSAlert *alert = [[NSAlert alloc] init]; [alert setMessageText:@"Goodbye, World!"]; [alert runModal];
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
#OCaml
OCaml
let delete_event evt = false   let destroy () = GMain.Main.quit ()   let main () = let window = GWindow.window in let _ = window#set_title "Goodbye, World" in let _ = window#event#connect#delete ~callback:delete_event in let _ = window#connect#destroy ~callback:destroy in let _ = window#show () in GMain.Mai...
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...
#Icon_and_Unicon
Icon and Unicon
link bitint   procedure main() every write(right(i := 0 to 10,4),":",right(int2bit(i),10)," -> ", right(g := gEncode(i),10)," -> ", right(b := gDecode(g),10)," -> ", right(bit2int(b),10)) en...
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
#Ring
Ring
  system("dir C:\Ring\doc")  
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
#Ruby
Ruby
str = `ls` arr = `ls`.lines
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
#Run_BASIC
Run BASIC
a$ = shell$("dir") ' Returns the directory info into a$ print a$ ' prints the directory  
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
#Rust
Rust
use std::process::Command; use std::io::{Write, self};   fn main() { let output = Command::new("/bin/cat") .arg("/etc/fstab") .output() .expect("failed to execute process");   io::stdout().write(&output.stdout); }
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
#Scala
Scala
import scala.io.Source   val command = "cmd /c echo Time at %DATE% %TIME%" val p = Runtime.getRuntime.exec(command) val sc = Source.fromInputStream(p.getInputStream) println(sc.mkString)
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...
#AutoHotkey
AutoHotkey
Swap(ByRef Left, ByRef Right) { temp := Left Left := Right Right := temp }
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.
#Bracmat
Bracmat
( biggest = max .  !arg: |  !arg:%?max ?arg & !arg:? (%@:>!max:?max) (?&~) | !max ) & out$("1:" biggest$(5 100000 -5 aap 3446 NOOT mies 0)) & out$("2:" biggest$) & out $ ( "3:" biggest $ (5 100000 -5 43756243978569758/13 3365864921428443 87512487957139516/27 3446) ...
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...
#ATS
ATS
(********************************************************************) (*   GCD of two integers, by Stein’s algorithm: https://en.wikipedia.org/w/index.php?title=Binary_GCD_algorithm&oldid=1072393147   This is an implementation without proofs of anything.   The implementations shown here require the GCC builtin...
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.
#PowerBASIC
PowerBASIC
$matchtext = "Goodbye London!" $repltext = "Hello New York!"   FUNCTION PBMAIN () AS LONG DIM L0 AS INTEGER, filespec AS STRING, linein AS STRING   L0 = 1 WHILE LEN(COMMAND$(L0)) filespec = DIR$(COMMAND$(L0)) WHILE LEN(filespec) OPEN filespec FOR BINARY AS 1 line...
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.
#PowerShell
PowerShell
  $listfiles = @('file1.txt','file2.txt') $old = 'Goodbye London!' $new = 'Hello New York!' foreach($file in $listfiles) { (Get-Content $file).Replace($old,$new) | Set-Content $file }  
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.
#PureBasic
PureBasic
Procedure GRTISF(List File$(), Find$, Replace$) Protected Line$, Out$, OutFile$, i ForEach File$() fsize=FileSize(File$()) If fsize<=0: Continue: EndIf If ReadFile(0, File$()) i=0 ; ; generate a temporary file in a safe way Repeat file$=GetTemporaryDirectory()+base$+"_"+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 conje...
#Brainf.2A.2A.2A
Brainf***
>>>>>>,>,>,<<   [ .[-<+>] ] > [ .[-<+>] ] > [ .[-<+>] ] <<<<     >------------------------------------------------[<<+>>-]> [ <<< [<+>-]< [>++++++++++<-]> >>> ------------------------------------------------ [<<<+>>>-]> [ <<<< [<+>-]< [>++++++++++<-]> >>>> ...
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...
#Visual_Basic
Visual Basic
Option Explicit   Private Type BITMAP bmType As Long bmWidth As Long bmHeight As Long bmWidthBytes As Long bmPlanes As Integer bmBitsPixel As Integer bmBits As Long End Type   Private Type RGB Red As Byte Green As Byte Blue As Byte Alpha As Byte End Type   Private Type RGBColor Color As Long End...
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 ...
#Go
Go
package main   import ( "fmt" "math/big" )   func min(a, b *big.Int) *big.Int { if a.Cmp(b) < 0 { return a } return b }   func hamming(n int) []*big.Int { h := make([]*big.Int, n) h[0] = big.NewInt(1) two, three, five := big.NewInt(2), big.NewInt(3), big.NewInt(5) next2, 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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
number = RandomInteger[{1, 10}]; While[guess =!= number, guess = Input["Guess my number"]]; Print["Well guessed!"]
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#MATLAB
MATLAB
number = ceil(10*rand(1)); [guess, status] = str2num(input('Guess a number between 1 and 10: ','s'));   while (~status || guess ~= number) [guess, status] = str2num(input('Guess again: ','s')); end disp('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 th...
#M4
M4
divert(-1) define(`setrange',`ifelse(`$3',`',$2,`define($1[$2],$3)`'setrange($1, incr($2),shift(shift(shift($@))))')') define(`asize',decr(setrange(`a',1,-1,-2,3,5,6,-2,-1,4,-4,2,-1))) define(`get',`defn(`$1[$2]')') define(`for', `ifelse($#,0,``$0'', `ifelse(eval($2<=$3),1, `pushdef(`$1',$2)$4`'popdef(`$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 th...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Sequences[m_]:=Prepend[Flatten[Table[Partition[Range[m],n,1],{n,m}],1],{}] MaximumSubsequence[x_List]:=Module[{sums}, sums={x[[#]],Total[x[[#]]]}&/@Sequences[Length[x]]; First[First[sums[[Ordering[sums,-1,#1[[2]]<#2[[2]]&]]]]] ]
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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Randomize Dim n As Integer = Int(Rnd * 20) + 1 Dim guess As Integer   Print "Guess which number I've chosen in the range 1 to 20" Print Do Input " Your guess : "; guess If guess > n AndAlso guess <= 20 Then Print "Your guess is higher than the chosen number, try again " ElseIf guess = n Th...
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...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations int Hi, Lo, Guess; [Text(0, "Think of a number between 1 and 100 then press a key."); if ChIn(1) then []; Lo:= 1; Hi:= 101; loop [Guess:= (Lo+Hi)/2; Text(0, "^M^JIs it "); IntOut(0, Guess); Text(0, " (Y = yes, H = too high, L = too low)? "); ...
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...
#zkl
zkl
println("Pick a number between 0 and 100 and remember it."); low,high,g := 0,100, 20; while(True){ r:=ask("I guess %d; is that high, low or =? ".fmt(g)).strip().toLower(); if(r=="="){ println("Yea!"); break; } if(r[0]=="h") high=g-1 else low=g+1; if(low==high){ println("Yea! the number is ",low); break; } ...
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...
#Harbour
Harbour
PROCEDURE Main() LOCAL i := 8, nH := 0    ? hb_StrFormat( "The first %d happy numbers are:", i )  ?   WHILE i > 0 IF IsHappy( ++nH ) ?? hb_NtoS( nH ) + " " --i ENDIF END   RETURN   STATIC FUNCTION IsHappy( nNumber ) STATIC aUnhappy := {} LOCAL nDigit, nSum := 0, cNumber := hb_NtoS( n...
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...
#Scheme
Scheme
(define earth-radius 6371) (define pi (acos -1))   (define (distance lat1 long1 lat2 long2) (define (h a b) (expt (sin (/ (- b a) 2)) 2)) (* 2 earth-radius (asin (sqrt (+ (h lat1 lat2) (* (cos lat1) (cos lat2) (h long1 long2)))))))   (define (deg-to-rad d m s) (* (/ pi 180) (+ d (/ m 60) (/ s 3600))))   (distance (deg-...
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
#HicEst
HicEst
WRITE() '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/...
#Scheme
Scheme
#!/usr/local/bin/gosh   ;; Show the first 20 niven numbers and the ;; first one greater than 1000. (define (main args) (display (iota-filtered 20 1 niven?))(newline) (display (iota-filtered 1 1001 niven?))(newline))   ;; Return a list of length n ;; for numbers starting at start ;; that satisfy the predicate f...
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
#Ol
Ol
  (import (lib winapi)) (MessageBox #f (c-string "Hello, World!") (c-string "Rosettacode") #x40)  
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
#OpenEdge.2FProgress
OpenEdge/Progress
MESSAGE "Goodbye, World!" VIEW-AS ALERT-BOX.
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...
#J
J
G2B=: ~:/\&.|:
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...
#Java
Java
  public class Gray { public static long grayEncode(long n){ return n ^ (n >>> 1); }   public static long grayDecode(long n) { long p = n; while ((n >>>= 1) != 0) p ^= n; return p; } public static void main(String[] args){ System.out.println("i\tBinary\tGray\tDecoded"); for(int i = -1; i < 32;i++){ ...
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#Sidef
Sidef
var output = `ls` # `output` is a string var lines = `ls`.lines # `lines` is an array
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
#Stata
Stata
program shellout, rclass tempfile f tempname m shell `0' > `f' file open `m' using "`f'", read binary file seek `m' eof file seek `m' query local n=r(loc) if `n'>0 { file seek `m' tof file read `m' %`n's s file close `m' return local out "`s'" } 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
#Swift
Swift
import Foundation   let process = Process()   process.launchPath = "/usr/bin/env" process.arguments = ["pwd"]   let pipe = Pipe() process.standardOutput = pipe   process.launch()   let data = pipe.fileHandleForReading.readDataToEndOfFile() let output = String.init(data: data, encoding: String.Encoding.utf8)   print(out...
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
#Standard_ML
Standard ML
val useOS = fn input => let val text = String.translate (fn #"\"" => "\\\""|n=>str n ) input ; val shellCommand = " echo " ^ text ^ "| gzip -c " ; val fname = "/tmp/fConv" ^ (String.extract (Time.toString (Posix.ProcEnv.time()),7,NONE) ); val me = ( Posix.FileSys.mkfifo ...
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
#Tcl
Tcl
set data [exec ls -l] puts "read [string length $data] bytes and [llength [split $data \n]] lines"
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...
#AWK
AWK
  # syntax: GAWK -f GENERIC_SWAP.AWK BEGIN { printf("%s version %s\n",ARGV[0],PROCINFO["version"]) foo = 1 bar = "a" printf("\n%s %s\n",foo,bar) rc = swap("foo","bar") # ok printf("%s %s %s\n",foo,bar,rc?"ok":"ng") printf("\n%s %s\n",foo,bar) rc = swap("FOO","BAR") # ng printf("%s %s...
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.
#Brat
Brat
max = { list | list.reduce { n, max | true? n > max { max = n } { max } } }   p max [3 4 1 2]
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...
#AutoHotkey
AutoHotkey
GCD(a,b) { Return b=0 ? Abs(a) : Gcd(b,mod(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.
#Python
Python
import fileinput   for line in fileinput.input(inplace=True): print(line.replace('Goodbye London!', 'Hello New York!'), end='')  
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#Racket
Racket
  #!/usr/bin/env racket #lang racket   (define from-string #f) (define to-string #f)   (command-line #:once-each [("-f") from "Text to remove" (set! from-string from)] [("-t") to "Text to put instead" (set! to-string to)] #:args files (unless from-string (error "No `from' string specified")) (unless to-string (...
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.
#Raku
Raku
slurp($_).subst('Goodbye London!', 'Hello New York!', :g) ==> spurt($_) for <a.txt b.txt c.txt>;
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...
#Brat
Brat
hailstone = { num | sequence = [num] while { num != 1 } { true? num % 2 == 0 { num = num / 2 } { num = num * 3 + 1 } sequence << num }   sequence }   #Check sequence for 27 seq = hailstone 27 true? (seq[0,3] == [27 82 41 124] && seq[-1, -4] == [8 4 2 1]) { p "Sequence for 27 is correct...
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...
#Visual_Basic_.NET
Visual Basic .NET
  Imports System.Drawing.Imaging   Public Function Grayscale(ByVal Map As Bitmap) As Bitmap   Dim oData() As Integer = GetData(Map) Dim oReturn As New Bitmap(Map.Width, Map.Height, Map.PixelFormat) Dim a As Integer = 0 Dim r As Integer = 0 Dim g As Integer = 0 Dim b As Integer = 0 Dim l As...
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 ...
#Groovy
Groovy
class Hamming {   static final ONE = BigInteger.ONE static final THREE = BigInteger.valueOf(3) static final FIVE = BigInteger.valueOf(5)   static void main(args) { print 'Hamming(1 .. 20) =' (1..20).each { print " ${hamming it}" } println "\nHamming(1691) = ${...