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
response_seed
stringclasses
1 value
instruction_seed
stringlengths
27
14.4k
_source
stringclasses
1 value
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Ruby
Ruby
text = <<EOS #### # # # # # # # #### # # ### # # # # # # # # # # # # # # # # # # # ### ### # # # EOS   def banner3D_1(text, shift=-1) txt = text.each_line.map{|line| line.gsub('#','__/').gsub(' ',' ')} offset = Array.new(txt.size){|i...
Give a code snippet in #Ruby Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
christopher/rosetta-code
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping
Sutherland-Hodgman polygon clipping
The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a...
#C
C
#include <stdio.h> #include <stdlib.h> #include <math.h>   typedef struct { double x, y; } vec_t, *vec;   inline double dot(vec a, vec b) { return a->x * b->x + a->y * b->y; }   inline double cross(vec a, vec b) { return a->x * b->y - a->y * b->x; }   inline vec vsub(vec a, vec b, vec res) { res->x = a->x - b->x; r...
Give a code snippet in #C The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displaye...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /...
#Bracmat
Bracmat
( :?names & ( get$("students.xml",X,ML)  :  ? ( ( Student . (? (Name.?name) ?,) | ? (Name.?name) ? ) & !names !name:?names & ~ )  ? | !names ) )
Give a code snippet in #Bracmat Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gende...
christopher/rosetta-code
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#J
J
NB. Create a "Point" class coclass'Point'   NB. Define its constructor create =: 3 : 0 'X Y' =: y )   NB. Instantiate an instance (i.e. an object) cocurrent 'base' P =: 10 20 conew 'Point'   NB. Interrogate its members X__P 10 Y__P 20
Give a code snippet in #J Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Relat...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Go
Go
package raster   import ( "fmt" "io" "os" )   // WriteTo outputs 8-bit P6 PPM format to an io.Writer. func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { // magic number if _, err = fmt.Fprintln(w, "P6"); err != nil { return }   // comments for _, c := range b.Comments { ...
Give a code snippet in #Go Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Lambdatalk
Lambdatalk
  1. direct:   {S.map {lambda {:i} {if {= {% :i 15} 0} then fizzbuzz else {if {= {% :i 3} 0} then fizz else {if {= {% :i 5} 0} then buzz else :i}}}} {S.serie 1 100}} -> 1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 17 fizz 19 buzz fizz 22 23 fizz buzz 26 fizz 28 29 fizzbuzz 31...
Give a code snippet in #Lambdatalk Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   Fiz...
christopher/rosetta-code
http://rosettacode.org/wiki/Top_rank_per_group
Top rank per group
Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett...
#XPL0
XPL0
proc Sort(Array, Field, Size); \Sort Array in descending order by Field int Array, Field, Size, I, J, T; [for J:= Size-1 downto 0 do for I:= 0 to J-1 do if Array(I,Field) < Array(I+1,Field) then [T:= Array(I); Array(I):= Array(I+1); Array(I+1):= T]; ];   int Data, I, I0, Dept, N, Cnt; [Data:...
Give a code snippet in #XPL0 Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,S...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Avail
Avail
Error: "Goodbye, World!";
Give a code snippet in #Avail Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out"...
christopher/rosetta-code
http://rosettacode.org/wiki/Vogel%27s_approximation_method
Vogel's approximation method
Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem. The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that: A will require 30 hours ...
#Tcl
Tcl
package require Tcl 8.6   # A sort that works by sorting by an auxiliary key computed by a lambda term proc sortByFunction {list lambda} { lmap k [lsort -index 1 [lmap k $list { list $k [uplevel 1 [list apply $lambda $k]] }]] {lindex $k 0} }   # A simple way to pick a “best” item from a list proc minimax {list...
Give a code snippet in #Tcl Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem. The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate tha...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_join
Hash join
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash join" algorithm, and demonstrate tha...
#TXR
TXR
(defvar age-name '((27 Jonah) (18 Alan) (28 Glory) (18 Popeye) (28 Alan)))   (defvar nemesis-name '((Jonah Whales) (Jonah Spiders) (Alan Ghosts) (Alan Zombies) ...
Give a code snippet in #TXR An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash join" a...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#AmigaE
AmigaE
PROC main() DEF t[100]: ARRAY, pass, door FOR door := 0 TO 99 DO t[door] := FALSE FOR pass := 0 TO 99 door := pass WHILE door <= 99 t[door] := Not(t[door]) door := door + pass + 1 ENDWHILE ENDFOR FOR door := 0 TO 99 DO WriteF('\d is \s\n', door+1, ...
Give a code snippet in #AmigaE There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ....
christopher/rosetta-code
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#Stata
Stata
. clear all . set obs 100000 number of observations (_N) was 0, now 100,000 . gen x=runiform() . summarize x   Variable | Obs Mean Std. Dev. Min Max -------------+--------------------------------------------------------- x | 100,000 .4991874 .2885253 1.18e-06 .9...
Give a code snippet in #Stata Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections ...
#OCaml
OCaml
type 'a dlink = { mutable data: 'a; mutable next: 'a dlink option; mutable prev: 'a dlink option; }   let dlink_of_list li = let f prev_dlink x = let dlink = { data = x; prev = None; next = prev_dlink } in begin match prev_dlink with | None -> () | Some prev_dlink -> ...
Give a code snippet in #OCaml Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Cr...
christopher/rosetta-code
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression...
#Run_BASIC
Run BASIC
string$ = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" beg = 1 i = 1 [loop] s$ = mid$(string$,beg,1) while mid$(string$,i,1) = s$ i = i + 1 wend press$ = press$ ; i-beg;s$ beg = i if i < len(string$) then goto [loop] print "Compressed:";press$   beg = 1 i = 1 [expand] while mid$(press$...
Give a code snippet in #Run_BASIC Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. 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) Task Provide a function to find the closest two p...
#Elixir
Elixir
defmodule Closest_pair do # brute-force algorithm: def bruteForce([p0,p1|_] = points), do: bf_loop(points, {distance(p0, p1), {p0, p1}})   defp bf_loop([_], acc), do: acc defp bf_loop([h|t], acc), do: bf_loop(t, bf_loop(h, t, acc))   defp bf_loop(_, [], acc), do: acc defp bf_loop(p0, [p1|t], {minD, minP}) d...
Give a code snippet in #Elixir This page uses content from Wikipedia. The original article was at Closest pair of points problem. 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) Task Provide a fu...
christopher/rosetta-code
http://rosettacode.org/wiki/Faulhaber%27s_formula
Faulhaber's formula
In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expressions, starting with p = 0. R...
#Maxima
Maxima
sum1(p):=sum(stirling2(p,k)*pochhammer(n-k+1,k+1)/(k+1),k,0,p)$ sum2(p):=sum((-1)^j*binomial(p+1,j)*bern(j)*n^(p-j+1),j,0,p)/(p+1)$   makelist(expand(sum1(p)-sum2(p)),p,1,10); [0,0,0,0,0,0,0,0,0,0]   for p from 0 thru 9 do print(expand(sum2(p)));
Give a code snippet in #Maxima In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expres...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#AutoHotkey
AutoHotkey
numbers = 1,2,3,4,5 product := 1 loop, parse, numbers, `, { sum += A_LoopField product *= A_LoopField } msgbox, sum = %sum%`nproduct = %product%
Give a code snippet in #AutoHotkey Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#Jsish
Jsish
prompt$ jsish -e 'require("Roman"); puts(Roman.fromRoman("MDCLXVI"));' 1666
Give a code snippet in #Jsish Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, st...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#Nanoquery
Nanoquery
for item in collection println item end
Give a code snippet in #Nanoquery Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   L...
christopher/rosetta-code
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#Oberon-2
Oberon-2
  MODULE CommaQuibbling; IMPORT NPCT:Args, Strings, Out;   VAR str: ARRAY 256 OF CHAR;   PROCEDURE Do(VAR s: ARRAY OF CHAR); VAR aux: ARRAY 128 OF CHAR; i,params: LONGINT; BEGIN params := Args.Number() - 1; CASE params OF 0: COPY("{}",s) |1: Args.At(1,aux); ...
Give a code snippet in #Oberon-2 Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body...
#M2000_Interpreter
M2000 Interpreter
  For i=1 to 10 step 2 : Print i : Next i  
Give a code snippet in #M2000_Interpreter Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations int I; [RanSeed(12345); \set random number generator seed to 12345 for I:= 1 to 5 do [IntOut(0, Ran(1_000_000)); CrLf(0)]; ]
Give a code snippet in #XPL0 The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const array float: list1 is [] (3.0, 1.0, 4.0, 1.0, 5.0, 9.0); const array float: list2 is 0 times 0.0;   const func float: squaredSum (in array float: floatList) is func result var float: sum is 0.0; local var float: number is 0.0; begin for number r...
Give a code snippet in #Seed7 Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#jq
jq
def svg: "<svg width='100%' height='100%' version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'>" ;   # A radial gradient to make a circle look like a sphere. # "colors" should be [startColor, intermediateColor, endColor] # or null for ["white", "teal", "black"] def sphe...
Give a code snippet in #jq Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Death...
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/1
Text processing/1
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another pr...
#REXX
REXX
/*REXX program to process instrument data from a data file. */ numeric digits 20 /*allow for bigger (precision) numbers.*/ ifid='READINGS.TXT' /*the name of the input file. */ ofid='READINGS.OUT' /* " " " " output " ...
Give a code snippet in #REXX This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Often data is produced by one program, in the wrong format for later use by another program or person. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a v...
#Common_Lisp
Common Lisp
(define-condition amb-failure () () (:report "No amb alternative succeeded."))   (defun invoke-ambiguously (function thunks) "Call function with successive values produced by successive functions in thunks until some invocation of function does not signal an amb-failure." (do ((thunks thunks (rest thunks))) ...
Give a code snippet in #Common_Lisp Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite aut...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_puzzle
Sum and product puzzle
Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in th...
#Nim
Nim
import sequtils, sets, sugar, tables   var xycandidates = toSeq(2..98) sums = collect(initHashSet, for s in 5..100: {s}) # Set of possible sums. factors: Table[int, seq[(int, int)]] # Mapping product -> list of factors.   # Build the factor mapping. for i in 0..<xycandidates.high: let x = xycan...
Give a code snippet in #Nim Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P k...
christopher/rosetta-code
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string....
#Smalltalk
Smalltalk
String subclass: Mutant [ <shape: #character>   Target := Mutant from: 'METHINKS IT IS LIKE A WEASEL'. Letters := ' ABCDEFGHIJKLMNOPQRSTUVWXYZ'.   Mutant class >> run: c rate: p ["Run Evolutionary algorighm, using c copies and mutate rate p." | pool parent | parent := self newRan...
Give a code snippet in #Smalltalk Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of...
christopher/rosetta-code
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String) Dim out As New List(Of String) Dim comma = False While Not String.IsNullOrEmpty(s) Dim gs = GetItem(s, depth) Dim g = gs.Item1 s = gs.Item2 I...
Give a code snippet in #Visual_Basic_.NET Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enabl...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Coloured_text
Terminal control/Coloured text
Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to cause blinking or flashing (if ...
#Julia
Julia
  using AnsiColor   function showbasecolors() for color in keys(Base.text_colors) print_with_color(color, " ", string(color), " ") end println() end   function showansicolors() for fore in keys(AnsiColor.COLORS) print(@sprintf("%15s ", fore)) for back in keys(AnsiColor.COLORS) ...
Give a code snippet in #Julia Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#Zig
Zig
const std = @import("std");   pub fn main() !void { const stdout_wr = std.io.getStdOut().writer(); const string = "alphaBETA"; var lower: [string.len]u8 = undefined; var upper: [string.len]u8 = undefined; for (string) |char, i| { lower[i] = std.ascii.toLower(char); upper[i] = std.asc...
Give a code snippet in #Zig Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not rev...
christopher/rosetta-code
http://rosettacode.org/wiki/Square_but_not_cube
Square but not cube
Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
#BASIC
BASIC
10 DEFINT C,S,Q,R,N: C=1: S=1: Q=1: R=1: N=1 20 IF N>30 THEN END 30 S=Q*Q 40 IF S>C THEN R=R+1: C=R*R*R: GOTO 40 50 IF S<C THEN N=N+1: PRINT S; 60 Q=Q+1 70 GOTO 20
Give a code snippet in #BASIC Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   numL = 0 numR = 0 loop label running forever say 'Provide two integers [or anything else to stop]:' parse ask numL numR . if \numL.datatype('w') | \numR.datatype('w') then leave running if numL < numR then say numL 'is less than' num...
Give a code snippet in #NetRexx Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#BBC_BASIC
BBC BASIC
DEF PROC_SelectionSort(Size%) FOR I% = 1 TO Size%-1 lowest% = I% FOR J% = (I% + 1) TO Size% IF data%(J%) < data%(lowest%) lowest% = J% NEXT J% IF I%<>lowest% SWAP data%(I%),data%(lowest%) NEXT I% ENDPROC
Give a code snippet in #BBC_BASIC Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Icon_and_Unicon
Icon and Unicon
procedure main()   s := "A simple string" p := "string$" # regular expression   s ? write(image(s),if ReFind(p) then " matches " else " doesn't match ",image(p))   s[j := ReFind(p,s):ReMatch(p,s,j)] := "replacement" write(image(s)) end   link regexp # link to IPL regexp
Give a code snippet in #Icon_and_Unicon Task   match a string against a regular expression   substitute part of a string using a regular expression
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Stata
Stata
. clear . matrix a=(2,9,4,7,5,3,6,1,8)' . qui svmat a . sort a . list   +----+ | a1 | |----| 1. | 1 | 2. | 2 | 3. | 3 | 4. | 4 | 5. | 5 | |----| 6. | 6 | 7. | 7 | 8. | 8 | 9. | 9 | +----+
Give a code snippet in #Stata Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick so...
christopher/rosetta-code
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n ...
#Prolog
Prolog
  load(Program, Fractions) :- re_split("[ ]+", Program, Split), odd_items(Split, TextualFractions), maplist(convert_frac, TextualFractions, Fractions).   odd_items(L, L) :- L = [_], !. % remove the even elements from a list. odd_items([X,_|L], [X|R]) :- odd_items(L, R).   convert_frac(Text, Frac) :- re_mat...
Give a code snippet in #Prolog FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initi...
christopher/rosetta-code
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...
#Ada
Ada
type Grayscale_Image is array (Positive range <>, Positive range <>) of Luminance;
Give a code snippet in #Ada 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. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#Ioke
Ioke
ackermann = method(m,n, cond( m zero?, n succ, n zero?, ackermann(m pred, 1), ackermann(m pred, ackermann(m, n pred))) )
Give a code snippet in #Ioke The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { ...
christopher/rosetta-code
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: ...
#ALGOL_W
ALGOL W
begin real procedure rk4 ( real procedure f ; real value y, x, dx ) ; begin  % Fourth-order Runge-Kutta method % real dy1, dy2, dy3, dy4; dy1 := dx * f(x, y); dy2 := dx * f(x + dx / 2.0, y + dy1 / 2.0); dy3 := dx * f(x + dx / 2.0, y + dy2 / 2.0); dy4 := dx * f(x + dx, y + dy3)...
Give a code snippet in #ALGOL_W Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This ...
christopher/rosetta-code
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Nim
Nim
import db_sqlite   let db = open(":memory:", "", "", "")   # Setup db.exec(sql"CREATE TABLE players (name, score, active, jerseyNum)") db.exec(sql"INSERT INTO players VALUES (?, ?, ?, ?)", "name", 0, "false", 99)   # Update the row. db.exec(sql"UPDATE players SET name=?, score=?, active=? WHERE jerseyNum=?", "S...
Give a code snippet in #Nim SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don'...
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program character64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesAR...
Give a code snippet in #AArch64_Assembly Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unic...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is c...
#Julia
Julia
  #this example works on Windows ccall( (:GetDoubleClickTime, "User32"), stdcall, Uint, (), )   ccall( (:clock, "libc"), Int32, ())
Give a code snippet in #Julia Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign languag...
christopher/rosetta-code
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#EchoLisp
EchoLisp
  (define (trabb-fun n) (+ (* 5 n n n) (sqrt(abs n))))   (define (check-trabb n) (if (number? n) (if (<= (trabb-fun n) 400) (printf "🌱 f(%d) = %d" n (trabb-fun n)) (printf "❌ f(%d) = %d" n (trabb-fun n))) (error "not a number" n)))   (define (trabb (numlist null)) (while (< (length numlist) 11) (set! num...
Give a code snippet in #EchoLisp The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 195...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#Sidef
Sidef
var value = 0; do { say ++value; } while (value % 6);
Give a code snippet in #Sidef Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/D...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#Delphi
Delphi
"Hello World".Length()
Give a code snippet in #Delphi Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme con...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Ursa
Ursa
stop
Give a code snippet in #Ursa Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/...
christopher/rosetta-code
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an...
#Liberty_BASIC
Liberty BASIC
nomainwin mainwin 50 20   WindowHeight =620 WindowWidth =690   open "Graphics library" for graphics as #a   #a, "trapclose [quit]"   #a "down"   Turn$ ="R" Pace =100 s = 16   [again] print Turn$   #a "cls ; home ; north ; down ; fill black"   for i =1 to len( Turn$)...
Give a code snippet in #Liberty_BASIC Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon fol...
christopher/rosetta-code
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#AppleScript
AppleScript
on fibonacci(n) -- "Anonymous recursion" task. -- For the sake of the task, a needlessly anonymous local script object containing a needlessly recursive handler. -- The script could easily (and ideally should) be assigned to a local variable. script property one : 1 property sequence : {}   ...
Give a code snippet in #AppleScript While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The ...
#Common_Lisp
Common Lisp
(defun tokenize-stream (stream) (labels ((whitespace-p (char) (find char #(#\space #\newline #\return #\tab))) (consume-whitespace () (loop while (whitespace-p (peek-char nil stream nil #\a)) do (read-char stream))) (read-integer () (loop...
Give a code snippet in #Common_Lisp Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval o...
christopher/rosetta-code
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an ob...
#Neko
Neko
/** <doc> <p>Neko uses <i>null</i> for undefined variables, and also as a programmer accessible value.</p> <p>The <i>null</i> value can be treated as a boolean value with the builtin $istrue, and tests as false.</p> </doc> */   var n = null if n == null $print("n is null\n") if $not($istrue(n)) $print("and test...
Give a code snippet in #Neko Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your langua...
christopher/rosetta-code
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#Oz
Oz
declare fun {RotChar C} if C >= &A andthen C =< &Z then &A + (C - &A + 13) mod 26 elseif C >= &a andthen C =< &z then &a + (C - &a + 13) mod 26 else C end end   fun {Rot13 S} {Map S RotChar} end in {System.showInfo {Rot13 "NOWHERE Abjurer 42"}} {System.showInfo {Rot13 {Rot13 "NO...
Give a code snippet in #Oz Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 en...
christopher/rosetta-code
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#BASIC
BASIC
escala = 1 / 81 zeroX = 160 zeroY = 100 maxiter = 32   CR = -.798 CI = .1618   SCREEN 13 FOR x = 0 TO 2 * zeroX - 1 FOR y = 0 TO 2 * zeroY - 1 zreal = (x - zeroX) * escala zimag = (zeroY - y) * escala FOR iter = 1 TO maxiter BR = CR + zreal * zreal - zimag * zimag zim...
Give a code snippet in #BASIC Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#ALGOL_68
ALGOL 68
# reads the line with number "number" (counting from 1) # # from the file named "file name" and returns the text of the # # in "line". If an error occurs, the result is FALSE and a # # message is returned in "err". If no error occurs, TRUE is # # returned # ...
Give a code snippet in #ALGOL_68 Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store i...
christopher/rosetta-code
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#WYLBUR
WYLBUR
Any Year Calendar -------------------- S M T W T F S
Give a code snippet in #WYLBUR Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#XPL0
XPL0
code CrLf=9; code real RlOut=48;   func real Mean(A, N); real A; int N; real S; int I; [if N=0 then return 0.0; S:= 0.0; for I:= 0 to N-1 do S:= S+A(I); return S/float(N); ]; \Mean   real Test; [Test:= [1.0, 2.0, 5.0, -5.0, 9.5, 3.14159]; RlOut(0, Mean(Test, 6)); CrLf(0); ]
Give a code snippet in #XPL0 Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an estab...
christopher/rosetta-code
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#Phix
Phix
with javascript_semantics sequence collection = {} collection = append(collection,"one") collection = prepend(collection,2) ? collection -- {2,"one"}
Give a code snippet in #Phix This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Cre...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_common_subsequence
Longest common subsequence
Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of ...
#Julia
Julia
longest(a::String, b::String) = length(a) ≥ length(b) ? a : b   """ julia> lcsrecursive("thisisatest", "testing123testing") "tsitest" """ # Recursive function lcsrecursive(xstr::String, ystr::String) if length(xstr) == 0 || length(ystr) == 0 return "" end   x, xs, y, ys = xstr[1], xstr[2:end], ystr[...
Give a code snippet in #Julia Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strin...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#Wren
Wren
var sentenceType = Fn.new { |s| if (s.count == 0) return "" var types = [] for (c in s) { if (c == "?") { types.add("Q") } else if (c == "!") { types.add("E") } else if (c == ".") { types.add("S") } } if (!"?!.".contains(s[-1])) typ...
Give a code snippet in #Wren Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctu...
christopher/rosetta-code
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. C...
#Raku
Raku
constant $zero = sub (Code $f) { sub ( $x) { $x }}   constant $succ = sub (Code $n) { sub (Code $f) { sub ( $x) { $f($n($f)($x)) }}}   constant $add = sub (Code $n) { sub (Code $m) { sub (Code $f) { s...
Give a code snippet in #Raku Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Tern
Tern
let list = [1, 22, 3, 24, 35, 6];   for(i in list) { println(i); }  
Give a code snippet in #Tern This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrie...
christopher/rosetta-code
http://rosettacode.org/wiki/Law_of_cosines_-_triples
Law of cosines - triples
The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(γ) = C2 Specific angles For an angle of of   90º   this becomes the more familiar ...
#AWK
AWK
  # syntax: GAWK -f LAW_OF_COSINES_-_TRIPLES.AWK # converted from C BEGIN { description[1] = "90 degrees, a*a + b*b = c*c" description[2] = "60 degrees, a*a + b*b - a*b = c*c" description[3] = "120 degrees, a*a + b*b + a*b = c*c" split("0,1,-1",coeff,",") main(13,1,0) main(1000,0,1) # 10,000 tak...
Give a code snippet in #AWK The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(γ) = C2 Specific angles For an angle of of   90º   th...
christopher/rosetta-code
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#Retro
Retro
:w/l [ $. eq? [ #0 ] [ #1 ] choose , ] s:for-each ;   'World d:create '.................... w/l '.................... w/l '.................... w/l '..ooo............... w/l '....o............... w/l '...o................ w/l '.................... w/l '.................... w/l '.................... w/...
Give a code snippet in #Retro The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Go
Go
// File digit.go   package digit   import ( "math/big" "strconv" )   func SumString(n string, base int) (int, error) { i, ok := new(big.Int).SetString(n, base) if !ok { return 0, strconv.ErrSyntax } if i.Sign() < 0 { return 0, strconv.ErrRange } if i.BitLen() <= 64 { return Sum(i.Uint64(), base), nil } ...
Give a code snippet in #Go Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
christopher/rosetta-code
http://rosettacode.org/wiki/Main_step_of_GOST_28147-89
Main step of GOST 28147-89
GOST 28147-89 is a standard symmetric encryption based on a Feistel network. The structure of the algorithm consists of three levels:   encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;   cycles - 32-З, 32-Р and 16-З, is a repetition of the ...
#Nim
Nim
import sequtils, strutils   const K1 = [byte 4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3] K2 = [byte 14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9] K3 = [byte 5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11] K4 = [byte 7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6...
Give a code snippet in #Nim GOST 28147-89 is a standard symmetric encryption based on a Feistel network. The structure of the algorithm consists of three levels:   encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;   cycles - 32-З, 32-Р and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Duffinian_numbers
Duffinian numbers
A Duffinian number is a composite number k that is relatively prime to its sigma sum σ. The sigma sum of k is the sum of the divisors of k. E.G. 161 is a Duffinian number. It is composite. (7 × 23) The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161. Duffinian numbers are very common. It is not u...
#Julia
Julia
using Primes   function σ(n) f = [one(n)] for (p,e) in factor(n) f = reduce(vcat, [f*p^j for j in 1:e], init=f) end return sum(f) end   isDuffinian(n) = !isprime(n) && gcd(n, σ(n)) == 1   function testDuffinians() println("First 50 Duffinian numbers:") foreach(p -> print(rpad(p[2], 4), p...
Give a code snippet in #Julia A Duffinian number is a composite number k that is relatively prime to its sigma sum σ. The sigma sum of k is the sum of the divisors of k. E.G. 161 is a Duffinian number. It is composite. (7 × 23) The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161. Duffinian number...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Cowgol
Cowgol
include "cowgol.coh";   var i: uint8 := 1; while i <= 100 loop if i % 15 == 0 then print("FizzBuzz"); elseif i % 5 == 0 then print("Buzz"); elseif i % 3 == 0 then print("Fizz"); else print_i8(i); end if; print_nl(); i := i + 1; end loop;
Give a code snippet in #Cowgol Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuz...
christopher/rosetta-code
http://rosettacode.org/wiki/Merge_and_aggregate_datasets
Merge and aggregate datasets
Merge and aggregate datasets Task Merge and aggregate two datasets as provided in   .csv   files into a new resulting dataset. Use the appropriate methods and data structures depending on the programming language. Use the most common libraries only when built-in functionality is not sufficient. Note Either lo...
#Julia
Julia
using CSV, DataFrames, Statistics   # load data from csv files #df_patients = CSV.read("patients.csv", DataFrame) #df_visits = CSV.read("visits.csv", DataFrame)   # create DataFrames from text that is hard coded, so use IOBuffer(String) as input str_patients = IOBuffer("""PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003...
Give a code snippet in #Julia Merge and aggregate datasets Task Merge and aggregate two datasets as provided in   .csv   files into a new resulting dataset. Use the appropriate methods and data structures depending on the programming language. Use the most common libraries only when built-in functionality is not...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#Nim
Nim
import math, sequtils, strformat, strutils, times   proc getStep(n: int64): int64 {.inline.} = result = 1 + n shl 2 - n shr 1 shl 1   proc primeFac(n: int64): seq[int64] = var maxq = int64(sqrt(float(n))) var d = 1 var q: int64 = 2 + (n and 1) # Start with 2 or 3 according to oddity. while q <= maxq and n %...
Give a code snippet in #Nim The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitcoin/public_point_to_address
Bitcoin/public point to address
Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion. The encoding steps are: take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed st...
#C
C
#include <stdio.h> #include <string.h> #include <ctype.h> #include <openssl/sha.h> #include <openssl/ripemd.h>   #define COIN_VER 0 const char *coin_err;   typedef unsigned char byte;   int is_hex(const char *s) { int i; for (i = 0; i < 64; i++) if (!isxdigit(s[i])) return 0; return 1; }   void str_to_byte(const c...
Give a code snippet in #C Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion. The encoding steps are: take the X and Y coordinates of the given public point, and concatenate them in order ...
christopher/rosetta-code
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#Amazing_Hopper
Amazing Hopper
  #include <flow.h> #include <flow-term.h>   #define SPACE(_T_,_N_) REPLICATE( " ", {_T_}DIV-INTO(_N_) )   DEF-MAIN(argv,argc) CLR-SCR GOSUB( Print Grey Scale ) END   RUTINES   DEF-FUN( Print Grey Scale ) SET( nrcolors, 8 ) SET( direction, 1 ) MSET( quarter, color ) LOCATE( 0, 0 ) FOR( LT?( quarter, ...
Give a code snippet in #Amazing_Hopper The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey u...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
Find palindromic numbers in both binary and ternary bases
Find palindromic numbers in both binary and ternary bases You are encouraged to solve this task according to the task description, using any language you may know. Task   Find and show (in decimal) the first six numbers (non-negative integers) that are   palindromes   in   both:   base 2   base 3   Display   0   ...
#Tcl
Tcl
proc format_%t {n} { while {$n} { append r [expr {$n % 3}] set n [expr {$n / 3}] } if {![info exists r]} {set r 0} string reverse $r }
Give a code snippet in #Tcl Find palindromic numbers in both binary and ternary bases You are encouraged to solve this task according to the task description, using any language you may know. Task   Find and show (in decimal) the first six numbers (non-negative integers) that are   palindromes   in   both:   base ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Raku
Raku
my @strings = <Here are some sample strings to be sorted>; put @strings.sort:{.chars, .lc}; put sort -> $x { $x.chars, $x.lc }, @strings;
Give a code snippet in #Raku Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Klingphix
Klingphix
include ..\Utilitys.tlhy   ( 1 2 3 4 ) [dup *] map   pstack   " " input
Give a code snippet in #Klingphix Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#M2000_Interpreter
M2000 Interpreter
  Module ABC { can_make_word("A") can_make_word("BaRk") can_make_word("BOOK") can_make_word("TREAT") can_make_word("CommoN") can_make_word("SQUAD") Gosub can_make_word("CONFUSE") ' we can use Gosub before Sub can_make_word(c$) local b$=ucase$(c$) ...
Give a code snippet in #M2000_Interpreter ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A comp...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#PL.2FSQL
PL/SQL
DECLARE string VARCHAR2(50) := 'Hello, world!'; stringlength NUMBER; BEGIN stringlength := LENGTHB(string); END;
Give a code snippet in #PL.2FSQL Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme c...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#EchoLisp
EchoLisp
  (for ((i (in-range 0 15 2))) (write i)) 0 2 4 6 8 10 12 14   (for ((q (in-range 0 15 14/8))) (write q)) 0 7/4 7/2 21/4 7 35/4 21/2 49/4 14   (for ((x (in-range 0 15 PI))) (write x)) 0 3.141592653589793 6.283185307179586 9.42477796076938 12.566370614359172  
Give a code snippet in #EchoLisp Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/...
christopher/rosetta-code
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial ...
#Raku
Raku
constant expansions = [1], [1,-1], -> @prior { [|@prior,0 Z- 0,|@prior] } ... *;   sub polyprime($p where 2..*) { so expansions[$p].[1 ..^ */2].all %% $p }   # Showing the expansions:   say ' p: (x-1)ᵖ'; say '-----------';   sub super ($n) { $n.trans: '0123456789' => '⁰¹²³⁴⁵⁶⁷⁸⁹'; }   for ^13 -> $d { ...
Give a code snippet in #Raku The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the c...
christopher/rosetta-code
http://rosettacode.org/wiki/SOAP
SOAP
In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified...
#Ruby
Ruby
require 'soap/wsdlDriver'   wsdl = SOAP::WSDLDriverFactory.new("http://example.com/soap/wsdl") soap = wsdl.create_rpc_driver   response1 = soap.soapFunc(:elementName => "value") puts response1.soapFuncReturn   response2 = soap.anotherSoapFunc(:aNumber => 42) puts response2.anotherSoapFuncReturn
Give a code snippet in #Ruby In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect onc...
christopher/rosetta-code
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a v...
#Rust
Rust
use std::ops::Add; struct Amb<'a> { list: Vec<Vec<&'a str>>, } fn main() { let amb = Amb { list: vec![ vec!["the", "that", "a"], vec!["frog", "elephant", "thing"], vec!["walked", "treaded", "grows"], vec!["slowly", "quickly"], ], }; match a...
Give a code snippet in #Rust Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"...
christopher/rosetta-code
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#BBC_BASIC
BBC BASIC
  REM Implementation of Langton's ant for Rosetta Code fieldsize%=100 REM Being pedantic, this will actually result in a field of 101 square, REM since arrays start at 0, and my implementation allows them to use it DIM field&(fieldsize%,fieldsize%)  : REM variables with an & suffix are by...
Give a code snippet in #BBC_BASIC Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with...
christopher/rosetta-code
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Racket
Racket
  #lang scribble/manual (require (for-label "sandwiches.rkt"))   @defproc[(make-sandwich [ingredients (listof ingredient?)]) sandwich?]{ Returns a sandwich given the right ingredients. }  
Give a code snippet in #Racket See also Related task: Comments Related task: Here_document
christopher/rosetta-code
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 ...
#Scala
Scala
def fs[X](f:X=>X)(s:Seq[X]) = s map f def f1(x:Int) = x * 2 def f2(x:Int) = x * x   def fsf[X](f:X=>X) = fs(f) _ val fsf1 = fsf(f1) // or without the fsf intermediary: val fsf1 = fs(f1) _ val fsf2 = fsf(f2) // or without the fsf intermediary: val fsf2 = fs(f2) _   assert(fsf1(List(0,1,2,3)) == List(0,2,4,6)) assert(fsf...
Give a code snippet in #Scala Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original functio...
christopher/rosetta-code
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bit...
#Swift
Swift
import Foundation   func entropy(of x: String) -> Double { return x .reduce(into: [String: Int](), {cur, char in cur[String(char), default: 0] += 1 }) .values .map({i in Double(i) / Double(x.count) } as (Int) -> Double) .map({p in -p * log2(p) } as (Double) -> Double) .reduce(0.0, +) }  ...
Give a code snippet in #Swift Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), ...
christopher/rosetta-code
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 ...
#Java
Java
import java.util.Arrays;   public class PartialApplication { interface IntegerFunction { int call(int arg); }   // Original method fs(f, s). static int[] fs(IntegerFunction f, int[] s) { int[] r = new int[s.length]; for (int i = 0; i < s.length; i++) r[i] = f.call(s[i]); return r; }   interface Seque...
Give a code snippet in #Java Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#J
J
require 'misc'   plural=: conjunction define (":m),' ',n,'s'#~1~:m )   bullcow=:monad define number=. 1+4?9 whilst. -.guess-:number do. guess=. 0 "."0 prompt 'Guess my number: ' if. (4~:#guess)+.(4~:#~.guess)+.0 e.guess e.1+i.9 do. if. 0=#guess do. smoutput 'Giving up.' return. ...
Give a code snippet in #J Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the gues...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Raven
Raven
define println use $s $s print "\n" print   "0123456789" as $str   $str 3 2 extract println # at 4th pos get 2 chars $str 8 4 extract println # at 9th pos get 4 chars (when only 1 char available)     $str 3 $str length extract println # at 4th pos get all chars to end of str $str 3 0x7FFFFFFF extr...
Give a code snippet in #Raven Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#Clay
Clay
ackermann(m, n) { if(m == 0) return n + 1; if(n == 0) return ackermann(m - 1, 1);   return ackermann(m - 1, ackermann(m, n - 1)); }
Give a code snippet in #Clay The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { ...
christopher/rosetta-code
http://rosettacode.org/wiki/Padovan_sequence
Padovan sequence
The Padovan sequence is similar to the Fibonacci sequence in several ways. Some are given in the table below, and the referenced video shows some of the geometric similarities. Comment Padovan Fibonacci Named after. Richard Padovan Leonardo of Pisa: Fibonacci Recurrence initial values....
#Swift
Swift
import Foundation   class PadovanRecurrence: Sequence, IteratorProtocol { private var p = [1, 1, 1] private var n = 0   func next() -> Int? { let pn = n < 3 ? p[n] : p[0] + p[1] p[0] = p[1] p[1] = p[2] p[2] = pn n += 1 return pn } }   class PadovanFloor: S...
Give a code snippet in #Swift The Padovan sequence is similar to the Fibonacci sequence in several ways. Some are given in the table below, and the referenced video shows some of the geometric similarities. Comment Padovan Fibonacci Named after. Richard Padovan Leonardo of Pisa: Fibonacci ...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#AArch64_Assembly
AArch64 Assembly
.text .global _start   _start: mov x0, #0 mov x8, #93 svc #0
Give a code snippet in #AArch64_Assembly Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#zkl
zkl
x=1; // comment ala C++ x=2; # ala scripts /* ala C, these comments are parsed (also ala C) */ /* can /* be */ nested */ #if 0 also ala C (and parsed) #endif #<<<# "here" comment, unparsed #<<<#
Give a code snippet in #zkl Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/JortSort
JortSort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Ring
Ring
  aList = [4,2,3,1] see jortSort(aList) + nl   func jortSort array originalArray = array array = sort(array) for i= 1 to len(originalArray) if originalArray[i] != array[i] return false ok next return true  
Give a code snippet in #Ring Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5...
#PicoLisp
PicoLisp
# Generate all proper divisors. (de propdiv (N) (head -1 (filter '((X) (=0 (% N X))) (range 1 N) )) )   # Obtaining the values from 1 to 10 inclusive. (mapcar propdiv (range 1 10)) # Output: # (NIL (1) (1) (1 2) (1) (1 2 3) (1) (1 2 4) (1 3) (1 2 5))
Give a code snippet in #PicoLisp The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper di...
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#EasyLang
EasyLang
func mul_inv a b . x1 . b0 = b x1 = 1 if b <> 1 while a > 1 q = a div b t = b b = a mod b a = t t = x0 x0 = x1 - q * x0 x1 = t . if x1 < 0 x1 += b0 . . . func remainder . n[] a[] r . prod = 1 sum = 0 for i range len n[] prod *= n[i] . ...
Give a code snippet in #EasyLang Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix
Sum of elements below main diagonal of matrix
Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
#Perl
Perl
#!/usr/bin/perl   use strict; use warnings; use List::Util qw( sum );   my $matrix = [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]];   my $lowersum = sum map @{ $matrix->[$_] }[0 .. $_ - 1], 1 .. $#$matrix; print "lower sum = $lowersum\n";
Give a code snippet in #Perl Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat...
#Elixir
Elixir
defmodule Average do def mode(list) do gb = Enum.group_by(list, &(&1)) max = Enum.map(gb, fn {_,val} -> length(val) end) |> Enum.max for {key,val} <- gb, length(val)==max, do: key end end   lists = [[3,1,4,1,5,9,2,6,5,3,5,8,9], [1, 2, "qwe", "asd", 1, 2, "qwe", "asd", 2, "qwe"]] Enum.each(lists...
Give a code snippet in #Elixir Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if p...
christopher/rosetta-code
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations int Size, Prime, I, Kill; char Flag; [Size:= IntIn(0); Flag:= Reserve(Size+1); for I:= 2 to Size do Flag(I):= true; for I:= 2 to Size do if Flag(I) then \found a prime [Prime:= I; IntOut(0, Prime); CrLf(0); ...
Give a code snippet in #XPL0 This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   al...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#Phix
Phix
integer x = 0 while 1 do x += 1 ?x if mod(x,6)=0 then exit end if end while
Give a code snippet in #Phix Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Do...
christopher/rosetta-code
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar tricker...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Sub main() Print "Hello from main!" End Sub   main Sleep
Give a code snippet in #FreeBASIC Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languag...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Continuous
Knapsack problem/Continuous
A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the item has a reduced price after...
#GNU_APL
GNU APL
⍝ Data Items←'beef' 'pork' 'ham' 'greaves' 'flitch' 'brawn' 'welt' 'salami' 'sausage' Weights←3.8 5.4 3.6 2.4 4 2.5 3.7 3 5.9 Prices←36 43 90 45 30 56 67 95 98   ⍝ Solution Order←⍒Worth←Prices÷Weights ⍝ 'Worth' is each item value for 1 kg. diff←{¯1↓(⍵,0)-0,⍵} ⍝ 'diff' betw...
Give a code snippet in #GNU_APL A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   t...
christopher/rosetta-code