task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#AntLang
AntLang
gcd[33; 77]
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.
#Julia
Julia
filenames = ["f1.txt", "f2.txt"] for filename in filenames txt = read(filename, String) open(filename, "w") do f write(f, replace(txt, "Goodbye London!" => "Hello New York!")) end 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.
#Kotlin
Kotlin
// version 1.2.0   import java.io.File   fun main(args: Array<String>) { val files = arrayOf("file1.txt", "file2.txt") for (file in files) { val f = File(file) var text = f.readText() println(text) text = text.replace("Goodbye London!", "Hello New York!") f.writeText(text...
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.
#Lasso
Lasso
#!/usr/bin/lasso9   local(files = array('f1.txt', 'f2.txt'))   with filename in #files let file = file(#filename) let content = #file -> readbytes do { #file -> dowithclose => { #content -> replace('Goodbye London!', 'Hello New York!') #file -> opentruncate #file -> writebytes(#content) } }
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...
#BASIC
BASIC
10 HOME   100 N = 27 110 GOSUB 400"HAILSTONE 120 DEF FN L(I) = E(I + 4 * (I < 0)) 130IFL=112AND(S(0)=27ANDS(1)=82ANDS(2)=41ANDS(3)=124)AND(FNL(M-3)=8ANDFNL(M-2)=4ANDFNL(M-1)=2ANDFNL(M)=1)THENPRINT"THE HAILSTONE SEQUENCE FOR THE NUMBER 27 HAS 112 ELEMENTS STARTING WITH 27, 82, 41, 124 AND ENDING WITH 8, 4, 2, 1" 140 PRI...
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...
#PicoLisp
PicoLisp
# Convert color image (PPM) to greyscale image (PGM) (de ppm->pgm (Ppm) (mapcar '((Y) (mapcar '((C) (/ (+ (* (car C) 2126) # Red (* (cadr C) 7152) # Green (* (caddr C) 722) ) # Blue ...
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...
#PL.2FI
PL/I
  do j = 1 to hbound(image,1); do i = 0 to hbound(image,2); color = image(i,j); R = substr(color, 17, 8); G = substr(color, 9, 8); B = substr(color, 1, 8); grey = trunc(0.2126*R + 0.7152*G + 0.0722*B); greybits = grey; image(i,j) = substr(greybits, length(greybits)-7, 8); ...
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...
#PureBasic
PureBasic
Procedure ImageGrayout(image) Protected w, h, x, y, r, g, b, gray, color   w = ImageWidth(image) h = ImageHeight(image) StartDrawing(ImageOutput(image)) For x = 0 To w - 1 For y = 0 To h - 1 color = Point(x, y) r = Red(color) g = Green(color) b = Blue(color) gray = 0...
http://rosettacode.org/wiki/Go_Fish
Go Fish
Write a program to let the user play Go Fish against a computer opponent. Use the following rules: Each player is dealt nine cards to start with. On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more. If t...
#Racket
Racket
  Red [ Title: "Go Fish" Author: "gltewalt" ]   chand: []  ;-- c and p = computer and player cguesses: [] phand: [] cbooks: 0 pbooks: 0 gf: { *************** * GO FISH * *************** } pip: ["a" "2" "3" "4" "5" "6" "7" "8" "9" "10" "j" "q" "k"] ;-- suits are not relevant pile: []  ;-- whe...
http://rosettacode.org/wiki/Go_Fish
Go Fish
Write a program to let the user play Go Fish against a computer opponent. Use the following rules: Each player is dealt nine cards to start with. On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more. If t...
#Raku
Raku
  Red [ Title: "Go Fish" Author: "gltewalt" ]   chand: []  ;-- c and p = computer and player cguesses: [] phand: [] cbooks: 0 pbooks: 0 gf: { *************** * GO FISH * *************** } pip: ["a" "2" "3" "4" "5" "6" "7" "8" "9" "10" "j" "q" "k"] ;-- suits are not relevant pile: []  ;-- whe...
http://rosettacode.org/wiki/Go_Fish
Go Fish
Write a program to let the user play Go Fish against a computer opponent. Use the following rules: Each player is dealt nine cards to start with. On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more. If t...
#Red
Red
  Red [ Title: "Go Fish" Author: "gltewalt" ]   chand: []  ;-- c and p = computer and player cguesses: [] phand: [] cbooks: 0 pbooks: 0 gf: { *************** * GO FISH * *************** } pip: ["a" "2" "3" "4" "5" "6" "7" "8" "9" "10" "j" "q" "k"] ;-- suits are not relevant pile: []  ;-- whe...
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 ...
#Factor
Factor
USING: accessors deques dlists fry kernel make math math.order ; IN: rosetta.hamming   TUPLE: hamming-iterator 2s 3s 5s ;   : <hamming-iterator> ( -- hamming-iterator ) hamming-iterator new 1 1dlist >>2s 1 1dlist >>3s 1 1dlist >>5s ;   : enqueue ( n hamming-iterator -- ) [ [ 2 * ] [ 2s>>...
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...
#Kotlin
Kotlin
// version 1.0.5-2   fun main(args: Array<String>) { val n = (1 + java.util.Random().nextInt(10)).toString() println("Guess which number I've chosen in the range 1 to 10\n") do { print(" Your guess : ") } while (n != readLine()) println("\nWell 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...
#LabVIEW
LabVIEW
writeln "Guess a number from 1 to 10"   val .n = toString random 10 for { val .guess = read ">> ", RE/^0*(?:[1-9]|10)(?:\.0+)?$/, "bad data\n", 7, ZLS if .guess == ZLS { writeln "too much bad data" break } if .guess == .n { writeln "That's it." break } writeln "no...
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...
#Java
Java
import java.util.Scanner; import java.util.ArrayList;   public class Sub{ private static int[] indices;   public static void main(String[] args){ ArrayList<Long> array= new ArrayList<Long>(); //the main set Scanner in = new Scanner(System.in); while(in.hasNextLong()) array.add(in.nextLon...
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...
#Euphoria
Euphoria
include get.e   constant lower_limit = 0, upper_limit = 100   integer number, guess number = rand(upper_limit-lower_limit+1)+lower_limit   printf(1,"Guess the number between %d and %d: ", lower_limit & upper_limit) while 1 do guess = floor(prompt_number("", lower_limit & upper_limit)) if number = guess then ...
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...
#Scheme
Scheme
(define minimum 1) (define maximum 100)   (display "Enter a number from ")(display minimum) (display " to ")(display maximum)(display ": ") (define number (read))   (define input "")   (do ((guess (round (/ (+ maximum minimum) 2)) (round (/ (+ maximum minimum) 2)))) ((string= input "=")) (dis...
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...
#Fortran
Fortran
program happy   implicit none integer, parameter :: find = 8 integer :: found integer :: number   found = 0 number = 1 do if (found == find) then exit end if if (is_happy (number)) then found = found + 1 write (*, '(i0)') number end if number = number + 1 end do   c...
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...
#Racket
Racket
  #lang racket (require math) (define earth-radius 6371)   (define (distance lat1 long1 lat2 long2) (define (h a b) (sqr (sin (/ (- b a) 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 (...
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...
#Raku
Raku
class EarthPoint { has $.lat; # latitude has $.lon; # longitude   has $earth_radius = 6371; # mean earth radius has $radian_ratio = pi / 180;   # accessors for radians method latR { $.lat * $radian_ratio } method lonR { $.lon * $radian_ratio }   method 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
#Halon
Halon
echo "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/...
#REXX
REXX
/*REXX program finds the first A Niven numbers; it also finds first Niven number > B.*/ parse arg A B . /*obtain optional arguments from the CL*/ if A=='' | A==',' then A= 20 /*Not specified? Then use the default.*/ if B=='' | B==',' then B= 1000 ...
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Nemerle
Nemerle
ncc -reference:System.Windows.Forms goodbye.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
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   import javax.swing.   msgText = 'Goodbye, World!' JOptionPane.showMessageDialog(null, msgText)  
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...
#F.23
F#
  // Functıons to translate bınary to grey code and vv. Nigel Galloway: December 7th., 2018 let grayCode,invGrayCode=let fN g (n:uint8)=n^^^(n>>>g) in ((fN 1),(fN 1>>fN 2>>fN 4))  
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...
#Factor
Factor
USING: math.ranges locals ; IN: rosetta-gray   : gray-encode ( n -- n' ) dup -1 shift bitxor ;   :: gray-decode ( n! -- n' ) n :> p! [ n -1 shift dup n! 0 = not ] [ p n bitxor p! ] while p ;   : main ( -- ) -1 32 [a,b] [ dup [ >bin ] [ gray-encode ] bi [ >bin ] [ gray-decode ] bi 4array . ] each ;...
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
#Nim
Nim
import osproc   # Output string and error code let (lsalStr, errCode) = execCmdEx("ls -al")   echo "Error code: " & $errCode echo "Output: " & lsalStr     # Output string only let lsStr = execProcess("ls")   echo "Output: " & lsStr  
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
#Objeck
Objeck
class Test { function : Main(args : String[]) ~ Nil { output := System.Runtime->CommandOutput("ls -l"); each(i : output) { output[i]->PrintLine(); }; } }  
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
#ooRexx
ooRexx
/* Execute a system command and retrieve its output into a stem. */ trace normal   /* Make the default values for the stem null strings. */ text. = ''   /* Issue the system command. "address command" is optional.) */ address command 'ls -l | rxqueue'   /* Remember the return code from the command. */ ls_rc = r...
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...
#Amazing_Hopper
Amazing Hopper
  #include <flow.h>   DEF-MAIN(argv,argc) DIM(10) AS-INT-RAND( 10, random array ) SET( single var, 0.5768 )   PRNL( "SINGLE VAR: ", single var, "\nRANDOM ARRAY: ", random array )   single var <-> random array   PRNL( "SINGLE VAR: ", single var, "\nRANDOM ARRAY: ", random array ) END  
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Batch_File
Batch File
::max.cmd @echo off setlocal enabledelayedexpansion set a=.%~1 if "%a%" equ "." set /p a="Input stream: " call :max res %a% echo %res% endlocal goto :eof   :max set %1=%2 :loop shift /2 if "%2" equ "" goto :eof if %2 gtr !%1! set res=%2 goto loop
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...
#APL
APL
33 49865 ∨ 77 69811 11 9973
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.
#Liberty_BASIC
Liberty BASIC
  nomainwin   file$( 1) ="data1.txt" file$( 2) ="data2.txt" file$( 3) ="data3.txt"     for i =1 to 3 open file$( i) for input as #i orig$ =input$( #i, lof( #i)) close #i   dummy$ =FindReplace$( orig$, "Goodbye London!", "Hello New York!", 1)   open "RC" +file$( i) for output as #o #o dum...
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.
#Lua
Lua
filenames = { "f1.txt", "f2.txt" }   for _, fn in pairs( filenames ) do fp = io.open( fn, "r" ) str = fp:read( "*all" ) str = string.gsub( str, "Goodbye London!", "Hello New York!" ) fp:close()   fp = io.open( fn, "w+" ) fp:write( str ) fp:close() end
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion echo. ::Task #1 call :hailstone 111 echo Task #1: (Start:!sav!) echo !seq! echo. echo Sequence has !cnt! elements. echo. ::Task #2 call :hailstone 27 echo Task #2: (Start:!sav!) echo !seq! echo. echo Sequence has !cnt! elements. echo. pause>nul exit /b 0 ::The Function :hailst...
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...
#Python
Python
# String masquerading as ppm file (version P3) import io ppmfileout = io.StringIO('')   def togreyscale(self): for h in range(self.height): for w in range(self.width): r, g, b = self.get(w, h) l = int(0.2126 * r + 0.7152 * g + 0.0722 * b) self.set(w, h, Colour(l, l, l))  ...
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#R
R
# Conversion from Grey to RGB uses the following code setAs("pixmapGrey", "pixmapRGB", function(from, to){ z = new(to, as(from, "pixmap")) z@red = from@grey z@green = from@grey z@blue = from@grey z@channels = c("red", "green", "blue") z })   # Conversion from RGB to grey uses built-in coefficien...
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 ...
#Forth
Forth
\ manipulating and computing with Hamming numbers:   : extract2 ( h -- l ) 40 rshift ;   : extract3 ( h -- m ) 20 rshift $fffff and ;   : extract5 ( h -- n ) $fffff and ;   ' + alias h* ( h1 h2 -- h )   : h. { h -- } ." 2^" h extract2 0 .r ." *3^" h extract3 0 .r ." *5^" h extract5 . ;   \ 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...
#langur
langur
writeln "Guess a number from 1 to 10"   val .n = toString random 10 for { val .guess = read ">> ", RE/^0*(?:[1-9]|10)(?:\.0+)?$/, "bad data\n", 7, ZLS if .guess == ZLS { writeln "too much bad data" break } if .guess == .n { writeln "That's it." break } writeln "no...
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...
#Lasso
Lasso
local( number = integer_random(10, 1), status = false, guess )   // prompt for a number stdout('Guess a number between 1 and 10: ')   while(not #status) => { #guess = null   // the following bits wait until the terminal gives you back a line of input while(not #guess or #guess -> size == 0) => { #guess = file_s...
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...
#JavaScript
JavaScript
function MaximumSubsequence(population) { var maxValue = 0; var subsequence = [];   for (var i = 0, len = population.length; i < len; i++) { for (var j = i; j <= len; j++) { var subsequence = population.slice(i, j); var value = sumValues(subsequence); if (value > ...
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...
#F.23
F#
  open System   [<EntryPoint>] let main argv = let aim = let from = 1 let upto = 100 let rnd = System.Random() Console.WriteLine("Hi, you have to guess a number between {0} and {1}",from,upto) rnd.Next(from,upto)   let mutable correct = false while not correct do   ...
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...
#Seed7
Seed7
$ include "seed7_05.s7i"; $ include "keybd.s7i";   const proc: main is func local var boolean: okay is FALSE; var boolean: quit is FALSE; var integer: low is 1; var integer: high is 1000; var integer: guess is 0; var char: command is ' '; begin writeln("Choose a number between 1 and 1000...
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...
#Sidef
Sidef
var min = 1 var max = 99 var tries = 0 var guess = pick(min..max)   print <<"EOT".chomp \n=>> Think of a number between #{min} and #{max} and I'll guess it!\n Press <ENTER> when are you ready... EOT   STDIN.readline   loop { print <<-EOT.chomp \n=>> My guess is: #{guess} Is your number higher, lower, or equal? ...
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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function isHappy(n As Integer) As Boolean If n < 0 Then Return False ' Declare a dynamic array to store previous sums. ' If a previous sum is duplicated before a sum of 1 is reached ' then the number can't be "happy" as the cycle will just repeat Dim prevSums() As Integer Dim As Integer...
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...
#Raven
Raven
define PI -1 acos   define toRadians use $degree $degree PI * 180 /   define haversine use $lat1, $lon1, $lat2, $lon2 6372.8 as $R # In kilometers $lat2 $lat1 - toRadians as $dLat $lon2 $lon1 - toRadians as $dLon $lat1 toRadians as $lat1 $lat2 toRadians as $lat2   $dLat 2 / sin $dLat 2 / s...
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...
#REXX
REXX
/*REXX program calculates the distance between Nashville and Los Angles airports.*/ call pi; numeric digits length(pi) % 2 /*use half of PI dec. digits for output*/ say " Nashville: north 36º 7.2', west 86º 40.2' = 36.12º, -86.67º" say " Los Angles: north 33º 56.4', west 118º 24.0' ...
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
#Harbour
Harbour
? "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/...
#Ring
Ring
  i = 1 count = 0 while true sum = 0 if niven(i) = 1 if count < 20 see "" + i + " is a Niven number" + nl count +=1 ok if i > 1000 see "" + i + " is a Niven number" exit ok ok i + =1 end   func niven nr nrString = string(nr) for j = 1 to len(nrString) sum = su...
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
#newLISP
newLISP
; hello-gui.lsp ; oofoe 2012-01-18   ; Initialize GUI server. (load (append (env "NEWLISPDIR") "/guiserver.lsp")) (gs:init)   ; Create window frame. (gs:frame 'Goodbye 100 100 300 200 "Goodbye!") (gs:set-resizable 'Goodbye nil) (gs:set-flow-layout 'Goodbye "center")   ; Add final message. (gs:label 'Message "Goodbye, W...
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...
#Forth
Forth
: >gray ( n -- n' ) dup 2/ xor ; \ n' = n xor (n logically right shifted 1 time) \ 2/ is Forth divide by 2, ie: shift right 1 : gray> ( n -- n ) 0 1 31 lshift ( -- g b mask ) begin >r ...
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...
#Fortran
Fortran
PROGRAM GRAY IMPLICIT NONE INTEGER IGRAY,I,J,K CHARACTER*5 A,B,C DO 10 I=0,31 J=IGRAY(I,1) K=IGRAY(J,-1) CALL BINARY(A,I,5) CALL BINARY(B,J,5) CALL BINARY(C,K,5) PRINT 99,I,A,B,C,K 10 CONTINUE 99 FORMAT(I2,3H : ,A5,4H => ,A5,4H => ,A5,3H : ,I2) ...
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
#PARI.2FGP
PARI/GP
externstr("time/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
#Perl
Perl
my @directories = grep { chomp; -d } `ls`; for (@directories) { chomp; ...; # Operate on directories }
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
#Phix
Phix
without js -- system_exec, file i/o constant tmp = "hostname.txt", cmd = iff(platform()=WINDOWS?"hostname":"uname -n") {} = system_exec(sprintf("%s > %s",{cmd,tmp}),4) string host = trim(get_text(tmp)) {} = delete_file(tmp) ?host
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...
#AmigaE
AmigaE
PROC swap(a,b) IS b,a   PROC main() DEF v1, v2, x v1 := 10 v2 := 20 v1, v2 := swap(v1,v2) WriteF('\d \d\n', v1,v2) -> 20 10 v1 := [ 10, 20, 30, 40 ] v2 := [ 50, 60, 70, 80 ] v1, v2 := swap(v1,v2) ForAll({x}, v1, `WriteF('\d ',x)) -> 50 60 70 80 WriteF('\n') ForAll({x}, v2, `WriteF('\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.
#BBC_BASIC
BBC BASIC
ListOfValues$ = "13, 0, -6, 2, 37, -10, 12" PRINT "Maximum value = " ; FNmax(ListOfValues$) END   DEF FNmax(list$) LOCAL index%, number, max max = VAL(list$) REPEAT index% = INSTR(list$, ",", index%+1) number = VAL(MID$(list$, index%+1)) IF number > 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...
#AppleScript
AppleScript
-- gcd :: Int -> Int -> Int on gcd(a, b) if b ≠ 0 then gcd(b, a mod b) else if a < 0 then -a else a end if end if end 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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
listOfFiles = {"a.txt", "b.txt", "c.txt"}; Do[ filename = listOfFiles[[i]]; filetext = Import[filename, "Text"]; filetext = StringReplace[filetext, "Goodbye London!" -> "Hello New York!"]; Export[filename, filetext, "Text"] , {i, 1, Length[listOfFiles]}]
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.
#newLISP
newLISP
  (define (replace-in-file filename this bythat) (set 'content (read-file filename)) (when (string? content) (replace this content bythat) (write-file filename content) ) )   (set 'files '("a.txt" "b.txt" "c.txt" "missing")) (dolist (fname files) (replace-in-file fname "Goodbye London!" "Hello New...
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.
#Nim
Nim
import strutils   let fr = "Goodbye London!" let to = "Hello, New York!"   for fn in ["a.txt", "b.txt", "c.txt"]: fn.writeFile fn.readFile.replace(fr, to)
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...
#beeswax
beeswax
>@:N q >%"d3~@.PNp d~2~pL~1F{<T_
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...
#Racket
Racket
  #lang racket (require racket/draw)   (define (gray->color gray-bm) (define gray-dc (new bitmap-dc% [bitmap gray-bm])) (define-values (w h) (send gray-dc get-size)) (define width (exact-floor w)) (define height (exact-floor h)) (define color-bm (make-bitmap width height)) (define color-dc (new bitmap-dc% [...
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...
#Raku
Raku
sub MAIN ($filename = 'default.ppm') {   my $in = open($filename, :r, :enc<iso-8859-1>) or die $in;   my ($type, $dim, $depth) = $in.lines[^3];   my $outfile = $filename.subst('.ppm', '.pgm'); my $out = open($outfile, :w, :enc<iso-8859-1>) or die $out;   $out.say("P5\n$dim\n$depth");   for $in.l...
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 ...
#Fortran
Fortran
program Hamming_Test use big_integer_module implicit none   call Hamming(1,20) write(*,*) call Hamming(1691) write(*,*) call Hamming(1000000)   contains   subroutine Hamming(first, last)   integer, intent(in) :: first integer, intent(in), optional :: last integer :: i, n, i2, i3, i5, lim type(big_...
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...
#LFE
LFE
  (defmodule guessing-game (export (main 0)))   (defun get-player-guess () (let (((tuple 'ok (list guessed)) (: io fread '"Guess number: " '"~d"))) guessed))   (defun check-guess (answer guessed) (cond ((== answer guessed) (: io format '"Well-guessed!!~n")) ((/= answer 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...
#Liberty_BASIC
Liberty BASIC
number = int(rnd(0) * 10) + 1 input "Guess the number I'm thinking of between 1 and 10. "; guess while guess <> number input "Incorrect! Try again! "; guess wend print "Congratulations, well guessed! The number was "; number;"."
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#jq
jq
def subarray_sum: . as $arr | reduce range(0; length) as $i ( {"first": length, "last": 0, "curr": 0, "curr_first": 0, "max": 0}; $arr[$i] as $e | (.curr + $e) as $curr | . + (if $e > $curr then {"curr": $e, "curr_first": $i} else {"curr": $curr} end) | if .curr > .max then . +...
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...
#Jsish
Jsish
/* Greatest Subsequential Sum, in Jsish */ function sumValues(arr) { var result = 0; for (var i = 0, len = arr.length; i < len; i++) result += arr[i]; return result; }   function greatestSubsequentialSum(population:array):array { var maxValue = (population[0]) ? population[0] : 0; var subsequence =...
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...
#Factor
Factor
USING: formatting fry io kernel math math.parser math.ranges prettyprint random ; IN: guessnumber   : game-step ( target -- ? ) readln string>number [ 2dup = [ 2drop f "Correct!" ] [ < "high" "low" ? "Guess too %s, try again." sprintf t swap ] if ]...
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...
#Smalltalk
Smalltalk
Object subclass: #NumberGuesser instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Rosettacode'  
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...
#Standard_ML
Standard ML
structure GuessNumberHelper : MONO_ARRAY = struct type elem = order type array = int * int fun length (lo, hi) = hi - lo fun sub ((lo, hi), i) = let val n = lo + i in print ("My guess is: " ^ Int.toString (lo+i) ^ ". Is it too high, too low, or correct? (H/L/C) "); let val str ...
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...
#Frege
Frege
module Happy where   import Prelude.Math -- ugh, since Frege doesn't have Set, use Map instead import Data.Map (member, insertMin, empty emptyMap)   digitToInteger :: Char -> Integer digitToInteger c = fromInt $ (ord c) - (ord '0')   isHappy :: Integer -> Bool isHappy = p emptyMap where p _ 1n = true p s 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...
#Ring
Ring
  decimals(8) see haversine(36.12, -86.67, 33.94, -118.4) + nl   func haversine x1, y1, x2, y2 r=0.01745 x1= x1*r x2= x2*r y1= y1*r y2= y2*r dy = y2-y1 dx = x2-x1 a = pow(sin(dx/2),2) + cos(x1) * cos(x2) * pow(sin(dy/2),2) c = 2 * asin(sqrt(a)) d = 6372.8 * c retur...
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...
#Ruby
Ruby
include Math   Radius = 6371 # rough radius of the Earth, in kilometers   def spherical_distance(start_coords, end_coords) lat1, long1 = deg2rad *start_coords lat2, long2 = deg2rad *end_coords 2 * Radius * asin(sqrt(sin((lat2-lat1)/2)**2 + cos(lat1) * cos(lat2) * sin((long2 - long1)/2)**2)) end   def deg2rad(lat...
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
#Hare
Hare
use fmt;   export fn main() void = { fmt::println("Hello, world!")!; };
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#Ruby
Ruby
harshad = 1.step.lazy.select { |n| n % n.digits.sum == 0 }   puts "The first 20 harshard numbers are: \n#{ harshad.first(20) }" puts "The first harshard number > 1000 is #{ harshad.find { |n| n > 1000 } }"  
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Nim
Nim
import dialogs, gtk2 gtk2.nim_init()   info(nil, "Hello 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...
#FreeBASIC
FreeBASIC
' version 18-01-2017 ' compile with: fbc -s console   Function gray2bin(g As UInteger) As UInteger   Dim As UInteger b = g   While g g Shr= 1 b Xor= g Wend   Return b   End Function   Function bin2gray(b As UInteger) As UInteger   Return b Xor (b Shr 1)   End Function   ' ------=< M...
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
#Phixmonti
Phixmonti
"hostname.txt" var hname "hostname > " hname chain cmd hname "r" fopen dup fgets print fclose "del " hname chain cmd
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
#PicoLisp
PicoLisp
: (in '(uname "-om") (line T)) -> "aarch64 Android"
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
#PowerShell
PowerShell
  [string[]]$volume = cmd /c vol   $volume  
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
#PureBasic
PureBasic
If OpenConsole("ls") rp=RunProgram("ls", "-l", "",#PB_Program_Open|#PB_Program_Read) While ProgramRunning(rp) If AvailableProgramOutput(rp) r$+ReadProgramString(rp)+#LF$ EndIf Wend CloseProgram(rp) PrintN(r$) Input() EndIf  
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...
#AppleScript
AppleScript
set {x,y} to {y,x}
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.
#bc
bc
define m(a[], n) { auto m, i   m = a[0] for (i = 1; i < n; i++) { if (a[i] > m) m = a[i] } return(m) }
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...
#Applesoft_BASIC
Applesoft BASIC
0 A = ABS(INT(A)) 1 B = ABS(INT(B)) 2 GCD = A * NOT NOT B 3 FOR B = B + A * NOT B TO 0 STEP 0 4 A = GCD 5 GCD = B 6 B = A - INT (A / GCD) * GCD 7 NEXT 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.
#Objeck
Objeck
class ReplaceAll { function : Main(args : String[]) ~ Nil { files := ["text1.txt", "text2.txt"]; each(f : files) { input := System.IO.File.FileReader->ReadFile(files[f]); output := input->ReplaceAll("Goodbye London!", "Hello New York!"); System.IO.File.FileWriter->WriteFile(files[f], output)...
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.
#OpenEdge.2FProgress
OpenEdge/Progress
FUNCTION replaceText RETURNS LOGICAL ( i_cfile_list AS CHAR, i_cfrom AS CHAR, i_cto AS CHAR ):   DEF VAR ii AS INT. DEF VAR lcfile AS LONGCHAR.   DO ii = 1 TO NUM-ENTRIES( i_cfile_list ): COPY-LOB FROM FILE ENTRY( ii, i_cfile_list ) TO lcfile. lcfile = REPLACE( lcfile...
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...
#Befunge
Befunge
93*:. v > :2%v > v+1*3_2/ >" ",:.v v< <v v-1:< < +1\_$1+v^ \ v .,+94<>^>::v >" "03pv  :* p v67:" "< 0: 1 >p78p25 *^*p0 v!-1: <<*^< 9$_:0\ ^-^< v v01g00:< 1 4 >g"@"*+`v^ <+ v01/"@":_ $ ^, >p"@"%00p\$:^. vg01g00 ,+49< >"@"*+.@  
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...
#REXX
REXX
/*REXX program converts a RGB (red─green─blue) image into a grayscale/greyscale image.*/ blue= '00 00 ff'x /*define the blue color (hexadecimal).*/ @.= blue /*set the entire image to blue color.*/ width= 60 ...
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...
#Ruby
Ruby
class RGBColour def to_grayscale luminosity = Integer(0.2126*@red + 0.7152*@green + 0.0722*@blue) self.class.new(luminosity, luminosity, luminosity) end end   class Pixmap def to_grayscale gray = self.class.new(@width, @height) @width.times do |x| @height.times do |y| gray[x,y] = sel...
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 ...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' The biggest integer which FB supports natively is 8 bytes so unable ' to calculate 1 millionth Hamming number without using an external ' "bigint" library such as GMP   Function min(x As Integer, y As Integer) As Integer Return IIf(x < y, x, y) End Function   Function hamming(n As Integer) As 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...
#LiveCode
LiveCode
command guessTheNumber local tNumber, tguess put random(10) into tNumber repeat until tguess is tNumber ask question "Please enter a number between 1 and 10" titled "Guess the number" if it is not empty then put it into tguess if tguess is tNumber then ...
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...
#Locomotive_Basic
Locomotive Basic
10 RANDOMIZE TIME:num=INT(RND*10+1):guess=0 20 PRINT "Guess the number between 1 and 10." 30 WHILE num<>guess 40 INPUT "Your guess? ", guess 50 WEND 60 PRINT "That's correct!"
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...
#Julia
Julia
function gss(arr::Vector{<:Number}) smax = hmax = tmax = 0 for head in eachindex(arr), tail in head:length(arr) s = sum(arr[head:tail]) if s > smax smax = s hmax, tmax = head, tail end end return arr[hmax:tmax] end   arr = [-1, -2, 3, 5, 6, -2, -1, 4, -4, ...
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...
#Kotlin
Kotlin
// version 1.1   fun gss(seq: IntArray): Triple<Int, Int, Int> { if (seq.isEmpty()) throw IllegalArgumentException("Array cannot be empty") var sum: Int var maxSum = seq[0] var first = 0 var last = 0 for (i in 1 until seq.size) { sum = 0 for (j in i until seq.size) { ...
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...
#Fantom
Fantom
  class Main { public static Void main () { Int lowerLimit := 1 Int higherLimit := 100   Int target := (lowerLimit..higherLimit).random Int guess while (guess != target) { echo ("Enter a guess: ") try { // read in a line of input, and try to interpret as an Int ...
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...
#Swift
Swift
import Cocoa   var found = false let fh = NSFileHandle.fileHandleWithStandardInput() println("Enter an integer between 1 and 100 for me to guess: ") let data = fh.availableData var num:Int! var low = 0.0 var high = 100.0 var lastGuess:Double!     if let numFromData = NSString(data: data, encoding: NSUTF8StringEncoding)...
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...
#Tcl
Tcl
set from 1 set to 10 fconfigure stdout -buffering none while 1 { set guess [expr {($from+$to) / 2}] puts -nonewline "Guess: $guess\tWas it lower (<) equal (=) or higher (>)? " switch -- [gets stdin] { < { set from [expr {$guess + 1}] } > { set to [expr {$guess - 1}] } = { puts "Found it: $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...
#F.C5.8Drmul.C3.A6
Fōrmulæ
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...