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/Elliptic_curve_arithmetic
Elliptic curve arithmetic
Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a nutshell, an elliptic curve is a...
#Haskell
Haskell
import Data.Monoid import Control.Monad (guard) import Test.QuickCheck (quickCheck)
Give a code snippet in #Haskell Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a...
christopher/rosetta-code
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#OCaml
OCaml
#include <stdio.h> #include <string.h> #include <caml/mlvalues.h> #include <caml/callback.h>   extern int Query (char * Data, size_t * Length) { static value * closure_f = NULL; if (closure_f == NULL) { closure_f = caml_named_value("Query function cb"); } value ret = caml_callback(*closure_f, Val_uni...
Give a code snippet in #OCaml This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11...
#Haskell
Haskell
import Data.List import Control.Arrow import Control.Monad   nlsRaw = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31" ++ " 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63" ++ " 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53" ++ " 114 96 25 109 7 31...
Give a code snippet in #Haskell Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 3...
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...
#Arturo
Arturo
point: #[ x: 10 y: 20 ]   print point
Give a code snippet in #Arturo 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. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#Erlang
Erlang
#! /usr/bin/escript   -define(LOG2E, 1.44269504088896340735992).   main(_) -> Self = escript:script_name(), {ok, Contents} = file:read_file(Self), io:format("My entropy is ~p~n", [entropy(Contents)]).   entropy(Data) -> Frq = count(Data), maps:fold(fun(_, C, E) -> P = C / byte_size...
Give a code snippet in #Erlang Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#Bracmat
Bracmat
( get$("unixdict.txt",STR):?list & 1:?product & whl ' ( @(!list:(%?word:?w) \n ?list) & :?sum & whl ' ( @(!w:%?let ?w) & (!let:~#|str$(N !let))+!sum:?sum ) & !sum^!word*!product:?product ) & lst$(product,"product.txt",NEW) & 0:?max & :?group & (  !product  :  ? * ?...
Give a code snippet in #Bracmat When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in...
christopher/rosetta-code
http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
Catmull–Clark subdivision surface
Implement the Catmull-Clark surface subdivision (description on Wikipedia), which is an algorithm that maps from a surface (described as a set of points and a set of polygons with vertices at those points) to another more refined surface. The resulting surface will always consist of a mesh of quadrilaterals. The proce...
#C
C
vertex face_point(face f) { int i; vertex v;   if (!f->avg) { f->avg = vertex_new(); foreach(i, v, f->v) if (!i) f->avg->pos = v->pos; else vadd(f->avg->pos, v->pos);   vdiv(f->avg->pos, len(f->v)); } return f->avg; }   #define hole_edge(e) (len(e->f)==1) vertex edge_point(edge e) { int i; face f;...
Give a code snippet in #C Implement the Catmull-Clark surface subdivision (description on Wikipedia), which is an algorithm that maps from a surface (described as a set of points and a set of polygons with vertices at those points) to another more refined surface. The resulting surface will always consist of a mesh of...
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" /...
#Wren
Wren
import "/pattern" for Pattern import "/fmt" for Conv   var xml = "<Students> <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" /> <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" /> <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" /> <Student Name=\"Dave\" Gender=\"M\...
Give a code snippet in #Wren 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="...
christopher/rosetta-code
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Erlang
Erlang
  os:getenv( "HOME" ).  
Give a code snippet in #Erlang Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
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...
#CoffeeScript
CoffeeScript
blockList = [ 'BO', 'XK', 'DQ', 'CP', 'NA', 'GT', 'RE', 'TG', 'QD', 'FS', 'JW', 'HU', 'VI', 'AN', 'OB', 'ER', 'FS', 'LY', 'PC', 'ZM' ]   canMakeWord = (word="") -> # Create a shallow clone of the master blockList blocks = blockList.slice 0 # Check if blocks contains letter checkBlocks = (letter) -> ...
Give a code snippet in #CoffeeScript 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/The_sieve_of_Sundaram
The sieve of Sundaram
The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram. Starting with the ordered set of +ve integers, mark every third starting a...
#Go
Go
package main   import ( "fmt" "math" "rcu" "time" )   func sos(n int) []int { if n < 3 { return []int{} } var primes []int k := (n-3)/2 + 1 marked := make([]bool, k) // all false by default limit := (int(math.Sqrt(float64(n)))-3)/2 + 1 for i := 0; i < limit; i++ { ...
Give a code snippet in #Go The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram. Starting with the ordered set of +ve integers,...
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#Elena
Elena
import extensions'scripting;   public program() { lscript.interpret("system'console.writeLine(""Hello World"")"); }
Give a code snippet in #Elena Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applica...
christopher/rosetta-code
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11...
#JavaScript
JavaScript
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" > <title>stem and leaf plot</title> <script type='text/javascript'>   function has_property(obj, propname) { return typeof(obj[propname]) === "u...
Give a code snippet in #JavaScript Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 6...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#D
D
import std.stdio, std.range, std.algorithm, std.complex; import std.math: PI;   auto nthRoots(in int n) pure nothrow { return n.iota.map!(k => expi(PI * 2 * (k + 1) / n)); }   void main() { foreach (immutable i; 1 .. 6) writefln("#%d: [%(%5.2f, %)]", i, i.nthRoots); }
Give a code snippet in #D The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
christopher/rosetta-code
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Dim i As Integer Dim l As Long Dim s As Short Dim b As Byte Print "An integer occupies "; SizeOf(i); " bytes" Print "A long occupies "; SizeOf(l); " bytes" Print "A short occupies "; SizeOf(s); " bytes" Print "A byte occupies "; SizeOf(b); " byte"   ' or use type directly rather than a va...
Give a code snippet in #FreeBASIC Demonstrate how to get the size of a variable. See also: Host introspection
christopher/rosetta-code
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:...
#APL
APL
  md5←{ ⍝ index origin zero ⎕IO←0 ⍝ decoding UTF-8 & padding M←(⊢,(0⍴⍨512|448-512|≢))1,⍨l←,⍉(8⍴2)⊤'UTF-8'⎕UCS ⍵ ⍝ add length M,←,⍉(8⍴2)⊤⌽(8⍴256)⊤≢l ⍝ init registers A←16⊥6 7 4 5 2 3 0 1 B←16⊥14 15 12 13 10 11 8 9 C←16⊥9 8 11 10 13 12 15 14 D←16⊥1 0 3 2 5 4 7 6 ...
Give a code snippet in #APL Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wi...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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) In information theory and computer science, the Levenshtein ...
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { \\ Iterative with two matrix rows function LevenshteinDistance(s$,t$) { if len(s$)<len(t$) then swap s$, t$ n=len(t$) m=len(s$) dim base 0, v0(n+1), v1(n+1) Rem dim sw() ' we can use stack of values to make the swap. for i=0 to n : v0(i)=i:next for i=0 to m-1 v1(0)=i+1 for j=0 ...
Give a code snippet in #M2000_Interpreter This page uses content from Wikipedia. The original article was at Levenshtein distance. 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) In information th...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_easy
Abbreviations, easy
This task is an easier (to code) variant of the Rosetta Code task:   Abbreviations, simple. For this task, the following   command table   will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find ...
#Delphi
Delphi
  program Abbreviations_Easy;   {$APPTYPE CONSOLE}   uses System.SysUtils;   const _TABLE_ = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy ' + 'COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find ' + 'NFind NFINDUp NFUp CFind FINdup FUp FOrward ...
Give a code snippet in #Delphi This task is an easier (to code) variant of the Rosetta Code task:   Abbreviations, simple. For this task, the following   command table   will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPl...
christopher/rosetta-code
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded c...
#Visual_Basic
Visual Basic
Function IsValidISIN(ByVal ISIN As String) As Boolean Dim s As String, c As String Dim i As Long If Len(ISIN) = 12 Then For i = 1 To Len(ISIN) c = UCase$(Mid(ISIN, i, 1)) Select Case c Case "A" To "Z" If i = 12 Then Exit Function s = s & CStr(Asc(c) - 55) Case "0"...
Give a code snippet in #Visual_Basic An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the ...
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...
#Objective-C
Objective-C
NSArray *collect; //... for(Type i in collect){ NSLog(@"%@", i); }
Give a code snippet in #Objective-C 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  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Death_Star
Death Star
Task Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction. (This will basically produce a shape like a "death star".) Related tasks draw a sphere draw a cuboid draw a rotating cube write language name in 3D ASCII
#Julia
Julia
# run in REPL using GLMakie   function deathstar() n = 60 θ = [0; (0.5: n - 0.5) / n; 1] φ = [(0: 2n - 2) * 2 / (2n - 1); 2] # if x is +0.9 radius units, replace it with the coordinates of sphere surface # at (1.2,0,0) center, radius 0.5 units x = [(x1 = cospi(φ)*sinpi(θ)) > 0.9 ? 1.2 - x1 * 0.5...
Give a code snippet in #Julia Task Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction. (This will basically produce a shape like a "death star".) Related tasks draw a sphere draw a cuboid draw a rotating cube write language na...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#Smalltalk
Smalltalk
  (0 to: 4) combinations: 3 atATimeDo: [ :x | Transcript cr; show: x printString].   "output on Transcript: #(0 1 2) #(0 1 3) #(0 1 4) #(0 2 3) #(0 2 4) #(0 3 4) #(1 2 3) #(1 2 4) #(1 3 4) #(2 3 4)"  
Give a code snippet in #Smalltalk Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0...
christopher/rosetta-code
http://rosettacode.org/wiki/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#Qi
Qi
  (define gcd A 0 -> A A B -> (gcd B (MOD A B)))   (define lcm A B -> (/ (* A B) (gcd A B)))  
Give a code snippet in #Qi Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has bo...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. 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 Write a function to compute the arithmetic-geomet...
#Sidef
Sidef
func agm(a, g) { loop { var (a1, g1) = ((a+g)/2, sqrt(a*g)) [a1,g1] == [a,g] && return a (a, g) = (a1, g1) } }   say agm(1, 1/sqrt(2))
Give a code snippet in #Sidef This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. 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 Write a function t...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#PureBasic
PureBasic
result = ReadFile(#PB_Any, "input.txt") If result>0 : Debug "this local file exists" Else : Debug "result=" +Str(result) +" so this local file is missing" EndIf   result = ReadFile(#PB_Any, "/input.txt") If result>0 : Debug "this root file exists" Else : Debug "result=" +Str(result) +" so this root file is missing...
Give a code snippet in #PureBasic Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works...
christopher/rosetta-code
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the widt...
#Raku
Raku
say "Floating points: (Nums)"; say "Error: " ~ (2**-53).Num;   sub infix:<±+> (Num $a, Num $b) { my \ε = (2**-53).Num; $a - ε + $b, $a + ε + $b, }   printf "%4.16f .. %4.16f\n", (1.14e0 ±+ 2e3);   say "\nRationals:";   say ".1 + .2 is exactly equal to .3: ", .1 + .2 === .3;   say "\nLarge denominators require e...
Give a code snippet in #Raku Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additional...
christopher/rosetta-code
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task ...
#Simula
Simula
  BEGIN   CLASS BOOLARRAY(N); INTEGER N; BEGIN BOOLEAN ARRAY DATA(0:N-1); END BOOLARRAY;   CLASS INTARRAY(N); INTEGER N; BEGIN INTEGER ARRAY DATA(0:N-1); END INTARRAY;   REF(BOOLARRAY) PROCEDURE SIEVE(LIMIT); INTEGER LIMIT; BEGIN REF(BOOLARRAY) C; ...
Give a code snippet in #Simula Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn...
christopher/rosetta-code
http://rosettacode.org/wiki/Josephus_problem
Josephus problem
Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\displaystyle 0} , removing eve...
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion   set "prison=41" %== Number of prisoners ==% set "step=3" %== The step... ==% set "survive=1" %== Number of survivors ==% call :josephus   set "prison=41" set "step=3" set "survive=3" call :josephus pause exit /b 0   %== The Procedure ==% :josephus set "surv_list=" for /l ...
Give a code snippet in #Batch_File Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0...
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 ...
#F.23
F#
open System   let longest xs ys = if List.length xs > List.length ys then xs else ys   let rec lcs a b = match a, b with | [], _ | _, [] -> [] | x::xs, y::ys -> if x = y then x :: lcs xs ys else longest (lcs a ys) (lcs xs b)   [<EntryPoint>] let main argv ...
Give a code snippet in #F.23 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 string...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#BASIC
BASIC
PRINT 17 PRINT &O21 PRINT &H11
Give a code snippet in #BASIC Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be...
christopher/rosetta-code
http://rosettacode.org/wiki/Rendezvous
Rendezvous
Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
#Erlang
Erlang
  -module( rendezvous ).   -export( [task/0] ).   task() -> Printer_pid = erlang:spawn( fun() -> printer(1, 5) end ), Reserve_printer_pid = erlang:spawn( fun() -> printer(2, 5) end ), Monitor_pid = erlang:spawn( fun() -> printer_monitor(Printer_pid, Reserve_printer_pid) end ), erlang:spawn( fun() -> pri...
Give a code snippet in #Erlang Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#Cach.C3.A9_ObjectScript
Caché ObjectScript
USER>Set cmd="Write ""Hello, World!""" USER>Xecute cmd Hello, World! USER>Set fnc="(num1, num2) Set res=num1+num2 Quit res" USER>Write $Xecute(fnc, 2, 3) 5
Give a code snippet in #Cach.C3.A9_ObjectScript Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return v...
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...
#Delphi
Delphi
program Loop;   {$APPTYPE CONSOLE}   var I: Integer;   begin I:= 0; repeat Inc(I); Write(I:2); until I mod 6 = 0; Writeln; Readln; end.
Give a code snippet in #Delphi 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/...
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...
#Wren
Wren
import "random" for Random import "/set" for Set import "/ioutil" for Input   var MAX_GUESSES = 20 // say var r = Random.new() var num // generate a 4 digit random number from 1234 to 9876 with no zeros or repeated digits while (true) { num = (1234 + r.int(8643)).toString if (!num.contains("0") && Set.new(num)...
Give a code snippet in #Wren 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 g...
christopher/rosetta-code
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   wher...
#Axiom
Axiom
qi := quatern$Quaternion(Integer);   Type: ((Integer,Integer,Integer,Integer) -> Quaternion(Integer)) q  := qi(1,2,3,4);   Type: Quaternion(Integer) q1 := qi(2,3,4,5);   Type: Quaternion(Integer) q2 := q...
Give a code snippet in #Axiom Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number ...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Io
Io
#!/usr/bin/env io   main := method( program := System args at(0)   ("Program: " .. program) println )   if (System args size > 0 and System args at(0) containsSeq("scriptname"), main)
Give a code snippet in #Io The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script nam...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#GAP
GAP
# We will compute the sum exactly   # Computing an approximation of a rationnal (giving a string) # Value is truncated toward zero Approx := function(x, d) local neg, a, b, n, m, s; if x < 0 then x := -x; neg := true; else neg := false; fi; a := NumeratorRat(x); b := DenominatorRat(x); n := QuoInt(a, b); ...
Give a code snippet in #GAP Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#ERRE
ERRE
PROGRAM ODD_EVEN   ! works for -2^15 <= n% < 2^15   FUNCTION ISODD%(N%) ISODD%=(N% AND 1)<>0 END FUNCTION   ! works for -2^38 <= n# <= 2^38 FUNCTION ISODD#(N#) ISODD#=N#<>2*INT(N#/2) END FUNCTION   BEGIN IF ISODD%(14) THEN PRINT("14 is odd") ELSE PRINT("14 is even") END IF IF ISODD%(15) THEN PRINT("15 i...
Give a code snippet in #ERRE Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divid...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string
Strip control codes and extended characters from a string
Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters stripped In ASCII, the control codes ...
#TXR
TXR
(defun strip-controls (str) (regsub #/[\x0-\x1F\x7F]+/ "" str))   (defun strip-controls-and-extended (str) (regsub #/[^\x20-\x7F]+/ "" str))
Give a code snippet in #TXR Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters stripped ...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#Visual_Basic_.NET
Visual Basic .NET
Function BinarySearch(ByVal A() As Integer, ByVal value As Integer) As Integer Dim low As Integer = 0 Dim high As Integer = A.Length - 1 Dim middle As Integer = 0   While low <= high middle = (low + high) / 2 If A(middle) > value Then high = middle - 1 ElseIf A(middle...
Give a code snippet in #Visual_Basic_.NET A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer ha...
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...
#Vedit_macro_language
Vedit macro language
Buf_Switch(Buf_Free) #90 = Time_Tick // seed for random number generator #91 = 10 // random numbers in range 0 to 9 while (EOB_pos < 4) { // 4 digits needed Call("RANDOM") BOF Ins_Char(Return_Value + '0') Replace("(.)(.*)\1", "\1\2", REGEXP+BEGIN+...
Give a code snippet in #Vedit_macro_language 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 play...
christopher/rosetta-code
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ...
#ooRexx
ooRexx
  -- REXX program to check if a number (base 10) is self-describing. parse arg x y . if x=='' then exit if y=='' then y=x -- 10 digits is the maximum size number that works here, so cap it numeric digits 10 y=min(y, 9999999999)   loop number = x to y loop i = 1 to number~length digit = number~subchar(i) -...
Give a code snippet in #ooRexx Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when d...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The...
#Raku
Raku
my @header = <&nbsp; X Y Z>; my $rows = 5;   sub tag ($tag, $string, $param?) { return "<$tag" ~ ($param ?? " $param" !! '') ~ ">$string" ~ "</$tag>" };   my $table = tag('tr', ( tag('th', $_) for @header));   for 1 .. $rows -> $row { $table ~= tag('tr', ( tag('td', $row, 'align="right"') ~ (tag('td', (^1000...
Give a code snippet in #Raku Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with...
christopher/rosetta-code
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#Scala
Scala
  object VanEck extends App {   def vanEck(n: Int): List[Int] = {   def vanEck(values: List[Int]): List[Int] = if (values.size < n) vanEck(math.max(0, values.indexOf(values.head, 1)) :: values) else values   vanEck(List(0)).reverse }   val vanEck1000 = vanEck(1000) println(s"...
Give a code snippet in #Scala The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Icon_and_Unicon
Icon and Unicon
procedure main() # demonstrate and describe function calling syntax and semantics   # normal procedure/function calling   f() # no arguments, also command context f(x) # fixed number of arguments f(x,h,w) # variable number of arguments (varargs) y...
Give a code snippet in #Icon_and_Unicon Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function...
christopher/rosetta-code
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#Scala
Scala
object LLT extends App { import Stream._   def primeSieve(s: Stream[Int]): Stream[Int] = s.head #:: primeSieve(s.tail filter { _ % s.head != 0 }) val primes = primeSieve(from(2))   def mersenne(p: Int): BigInt = (BigInt(2) pow p) - 1   def s(mp: BigInt, p: Int): BigInt = { if (p == 1) 4 else ((s(mp, p - 1...
Give a code snippet in #Scala Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sexy_primes
Sexy primes
This page uses content from Wikipedia. The original article was at Sexy_prime. 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) In mathematics, sexy primes are prime numbers that differ from each ot...
#zkl
zkl
var [const] BI=Import("zklBigNum"); // libGMP const N=1_000_035, M=N+24; // M allows prime group to span N, eg N=100, (97,103) const OVR=6; // 6 if prime group can NOT span N, else 0 ps,p := Data(M+50).fill(0), BI(1); // slop at the end (for reverse wrap around) while(p.nextPrime()<=M){ ps[p]=1 } // bitmap of primes  ...
Give a code snippet in #zkl This page uses content from Wikipedia. The original article was at Sexy_prime. 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) In mathematics, sexy primes are prime num...
christopher/rosetta-code
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute z...
#11l
11l
V k = 21.0 print(‘K ’k) print(‘C ’(k - 273.15)) print(‘F ’(k * 1.8 - 459.67)) print(‘R ’(k * 1.8))
Give a code snippet in #11l There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 ke...
christopher/rosetta-code
http://rosettacode.org/wiki/Pentagram
Pentagram
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and backg...
#Ring
Ring
  # Project : Pentagram   load "guilib.ring"   paint = null   new qapp { win1 = new qwidget() { setwindowtitle("Pentagram") setgeometry(100,100,500,600) label1 = new qlabel(win1) { setgeometry(10,10,400,400) ...
Give a code snippet in #Ring A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Faulhaber%27s_triangle
Faulhaber's triangle
Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1 − j {\displaystyle \sum _{k...
#JavaScript
JavaScript
(() => {   // Order of Faulhaber's triangle -> rows of Faulhaber's triangle // faulHaberTriangle :: Int -> [[Ratio Int]] const faulhaberTriangle = n => map(x => tail( scanl((a, x) => { const ys = map((nd, i) => ratioMult(nd, Ratio(x, i + 2)...
Give a code snippet in #JavaScript Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p...
christopher/rosetta-code
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "...
#Julia
Julia
const jobs = 12   mutable struct Environment seq::Int cnt::Int Environment() = new(0, 0) end   const env = [Environment() for i in 1:jobs] const currentjob = [1]   seq() = env[currentjob[1]].seq cnt() = env[currentjob[1]].cnt seq(n) = (env[currentjob[1]].seq = n) cnt(n) = (env[currentjob[1]].cnt = n)   func...
Give a code snippet in #Julia According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a pro...
christopher/rosetta-code
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#PicoLisp
PicoLisp
(de encode (Str) (let Table (chop "abcdefghijklmnopqrstuvwxyz") (mapcar '((C) (dec (prog1 (index C Table) (rot Table @) ) ) ) (chop Str) ) ) )   (de decode (Lst) (let Table (chop "abcdefghijklmnopqrstuvwxyz") (pack ...
Give a code snippet in #PicoLisp Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is use...
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...
#Phix
Phix
constant s = "alphaBETA" ?upper(s) ?lower(s)
Give a code snippet in #Phix 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 re...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#Rust
Rust
  fn pascal_triangle(n: u64) {   for i in 0..n { let mut c = 1; for _j in 1..2*(n-1-i)+1 { print!(" "); } for k in 0..i+1 { print!("{:2} ", c); c = c * (i-k)/(k+1); } println!(); } }  
Give a code snippet in #Rust Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either ...
christopher/rosetta-code
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Type MyClass Private: myInt_ As Integer Public: Declare Constructor(myInt_ As Integer) Declare Property MyInt() As Integer Declare Function Treble() As Integer End Type   Constructor MyClass(myInt_ As Integer) This.myInt_ = myInt_ End Constructor   Property MyClass.MyInt() As ...
Give a code snippet in #FreeBASIC In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the...
christopher/rosetta-code
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the follow...
#Raku
Raku
class Automaton { has $.rule; has @.cells; has @.code = $!rule.fmt('%08b').flip.comb».Int;   method gist { "|{ @!cells.map({+$_ ?? '#' !! ' '}).join }|" }   method succ { self.new: :$!rule, :@!code, :cells( @!code[ 4 «*« @!cells.rotate(-1)  »+«...
Give a code snippet in #Raku Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Ring
Ring
see "Goodbye, World!"
Give a code snippet in #Ring Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standa...
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see...
#Forth
Forth
: f-" ( a b snippet" -- ) [char] " parse ( code len ) 2dup 2>r evaluate swap 2r> evaluate - . ;   2 3 f-" dup *" \ 5 (3*3 - 2*2)
Give a code snippet in #Forth x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and...
christopher/rosetta-code
http://rosettacode.org/wiki/Perlin_noise
Perlin noise
The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random   mapping of   R d ...
#Phix
Phix
with javascript_semantics constant ph = x"97 A0 89 5B 5A 0F 83 0D C9 5F 60 35 C2 E9 07 E1"& x"8C 24 67 1E 45 8E 08 63 25 F0 15 0A 17 BE 06 94"& x"F7 78 EA 4B 00 1A C5 3E 5E FC DB CB 75 23 0B 20"& x"39 B1 21 58 ED 95 38 57 AE 14 7D 88 AB A8 44 AF"& x"4A A5 47 86 8B...
Give a code snippet in #Phix The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random ...
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...
#Common_Lisp
Common Lisp
CL-USER> (cffi:load-foreign-library "libX11.so") #<CFFI::FOREIGN-LIBRARY {1004F4ECC1}> CL-USER> (cffi:foreign-funcall "XOpenDisplay" :string #+sbcl (sb-posix:getenv "DISPLAY") #-sbcl ":0.0" :pointer) #.(SB-SYS:INT-SAP #...
Give a code snippet in #Common_Lisp 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 l...
christopher/rosetta-code
http://rosettacode.org/wiki/Distributed_programming
Distributed programming
Write two programs (or one program with two modes) which run on networked computers, and send some messages between them. The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example ...
#JavaScript
JavaScript
var net = require('net')   var server = net.createServer(function (c){ c.write('hello\r\n') c.pipe(c) // echo messages back })   server.listen(3000, 'localhost')  
Give a code snippet in #JavaScript Write two programs (or one program with two modes) which run on networked computers, and send some messages between them. The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not desig...
christopher/rosetta-code
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls
Numbers with equal rises and falls
When a number is written in base 10,   adjacent digits may "rise" or "fall" as the number is read   (usually from left to right). Definition Given the decimal digits of the number are written as a series   d:   A   rise   is an index   i   such that   d(i)  <  d(i+1)   A   fall    is an index   i   such that   ...
#Wren
Wren
import "/fmt" for Fmt   var risesEqualsFalls = Fn.new { |n| if (n < 10) return true var rises = 0 var falls = 0 var prev = -1 while (n > 0) { var d = n%10 if (prev >= 0) { if (d < prev) { rises = rises + 1 } else if (d > prev) { ...
Give a code snippet in #Wren When a number is written in base 10,   adjacent digits may "rise" or "fall" as the number is read   (usually from left to right). Definition Given the decimal digits of the number are written as a series   d:   A   rise   is an index   i   such that   d(i)  <  d(i+1)   A   fall    ...
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...
#FBSL
FBSL
#APPTYPE CONSOLE   FUNCTION Fibonacci(n) IF n < 0 THEN RETURN "Nuts!" ELSE RETURN Fib(n) END IF FUNCTION Fib(m) IF m < 2 THEN Fib = m ELSE Fib = Fib(m - 1) + Fib(m - 2) END IF END FUNCTION END FUNCTION   PRINT Fibonacci(-1.5) PRINT Fibonacci(1.5) PRINT Fibonacci(13.666)   PAUSE
Give a code snippet in #FBSL 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 unwante...
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. ...
#TXR
TXR
(glob "/etc/*.conf")
Give a code snippet in #TXR Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, no...
christopher/rosetta-code
http://rosettacode.org/wiki/Heronian_triangles
Heronian triangles
Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b + c 2 . {\displaystyle s...
#Java
Java
import java.util.ArrayList;   public class Heron { public static void main(String[] args) { ArrayList<int[]> list = new ArrayList<>();   for (int c = 1; c <= 200; c++) { for (int b = 1; b <= c; b++) { for (int a = 1; a <= b; a++) {   if (gcd(gcd(a, b),...
Give a code snippet in #Java Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#Ursala
Ursala
#import std #import flo   data = ari10(1.,10.) # arithmetic progression, length 10 with endpoints 1 and 10   a = mean data g = exp mean ln* data h = div/1. mean div/*1. data   #cast %eLbX   main = ^(~&,ordered not fleq) <a,g,h>
Give a code snippet in #Ursala Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ld...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I befo...
#Liberty_BASIC
Liberty BASIC
  FruitList$(0)="apple" 'assign 2 cells of a list array FruitList$(1)="orange" dimension=dimension(FruitList$()) 'first get the dimension of the array if dimension>3 then print "Sorry, program only written for array dimensions of 3 or less." end end if call elements FruitList$(), dimension 'next get the size o...
Give a code snippet in #Liberty_BASIC Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Lett...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Simple_moving_average
Averages/Simple moving average
Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an avera...
#PARI.2FGP
PARI/GP
sma_per(n)={ sma_v=vector(n); sma_i = 0; n->if(sma_i++>#sma_v,sma_v[sma_i=1]=n;0,sma_v[sma_i]=n;0)+sum(i=1,#sma_v,sma_v[i])/#sma_v };
Give a code snippet in #PARI.2FGP Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#OCaml
OCaml
let maxsubseq = let rec loop sum seq maxsum maxseq = function | [] -> maxsum, List.rev maxseq | x::xs -> let sum = sum + x and seq = x :: seq in if sum < 0 then loop 0 [] maxsum maxseq xs else if sum > maxsum then loop sum seq sum seq xs el...
Give a code snippet in #OCaml Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are ...
christopher/rosetta-code
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point...
#Scala
Scala
import java.awt.{ Color, geom,Graphics2D ,Rectangle} import scala.math.hypot import scala.swing.{MainFrame,Panel,SimpleSwingApplication} import scala.swing.Swing.pair2Dimension import scala.util.Random   object CirculairConstrainedRandomPoints extends SimpleSwingApplication { //min/max of display-x resp. y val dx0,...
Give a code snippet in #Scala Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" cir...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_letter-first_letter
Last letter-first letter
A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the category, they fall out of the ga...
#Elixir
Elixir
defmodule LastLetter_FirstLetter do def search(names) do first = Enum.group_by(names, &String.first/1) sequences = Enum.reduce(names, [], fn name,acc -> add_name(first, acc, [name]) end) max = Enum.max_by(sequences, &length/1) |> length max_seqs = Enum.filter(sequences, fn seq -> length(seq) == max en...
Give a code snippet in #Elixir A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the c...
christopher/rosetta-code
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit ...
#Rust
Rust
  fn sedol(input: &str) -> Option<String> { let weights = vec![1, 3, 1, 7, 3, 9, 1]; let valid_chars = "0123456789BCDFGHJKLMNPQRSTVWXYZ";   if input.len() != 6 { return None; }   // could be done by regex if needed for c in input.chars() { if !valid_chars.contains(c) { ...
Give a code snippet in #Rust Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#AutoIt
AutoIt
  Dim $a[10] ConsoleWrite('array before permutation:' & @CRLF) For $i = 0 To 9 $a[$i] = Random(20,100,1) ConsoleWrite($a[$i] & ' ') Next ConsoleWrite(@CRLF)   _Permute($a) ConsoleWrite('array after permutation:' & @CRLF) For $i = 0 To UBound($a) -1 ConsoleWrite($a[$i] & ' ') Next ConsoleWrite(@CRLF)     Func _Permut...
Give a code snippet in #AutoIt The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_block_comments
Strip block comments
A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at least handle simple, non-ne...
#PHP
PHP
  function strip_block_comments( $test_string ) { $pattern = "/^.*?(\K\/\*.*?\*\/)|^.*?(\K\/\*.*?^.*\*\/)$/mXus"; return preg_replace( $pattern, '', $test_string ); }   echo "Result: '" . strip_block_comments( " /** * Some comments * longer comments here that we can parse. * * Rahoo */ function subroutine() { ...
Give a code snippet in #PHP A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should a...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program copystr64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM6...
Give a code snippet in #AArch64_Assembly This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a stri...
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#Objeck
Objeck
use IO; use Structure;   bundle Default { class HappyNumbers { function : native : IsHappy(n : Int) ~ Bool { cache := IntVector->New(); sum := 0; while(n <> 1) { if(cache->Has(n)) { return false; };   cache->AddBack(n); while(n <> 0) { ...
Give a code snippet in #Objeck From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly...
christopher/rosetta-code
http://rosettacode.org/wiki/String_append
String append
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 |...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
(* mutable strings are not supported *) s1 = "testing"; s1 = s1 <> " 123"; s1
Give a code snippet in #Mathematica.2FWolfram_Language 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 | L...
christopher/rosetta-code
http://rosettacode.org/wiki/Color_of_a_screen_pixel
Color of a screen pixel
Task Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
#C.2B.2B.2FCLI
C++/CLI
using namespace System; using namespace System::Drawing; using namespace System::Windows::Forms;   [STAThreadAttribute] int main() { Point^ MousePoint = gcnew Point(); Control^ TempControl = gcnew Control(); MousePoint = TempControl->MousePosition; Bitmap^ TempBitmap = gcnew Bitmap(1,1); Graphics^ g = Graphics::Fr...
Give a code snippet in #C.2B.2B.2FCLI Task Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
christopher/rosetta-code
http://rosettacode.org/wiki/Idiomatically_determine_all_the_characters_that_can_be_used_for_symbols
Idiomatically determine all the characters that can be used for symbols
Idiomatically determine all the characters that can be used for symbols. The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to name, ...
#Haskell
Haskell
varid → (small {small | large | digit | ' }) / reservedid conid → large {small | large | digit | ' } reservedid → case | class | data | default | deriving | do | else | foreign | if | import | in | infix | infixl | infixr | instance | let | module | newtype | of | then | type ...
Give a code snippet in #Haskell Idiomatically determine all the characters that can be used for symbols. The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a compute...
christopher/rosetta-code
http://rosettacode.org/wiki/String_comparison
String 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 |...
#Forth
Forth
: str-eq ( str len str len -- ? ) compare 0= ; : str-neq ( str len str len -- ? ) compare 0<> ; : str-lt ( str len str len -- ? ) compare 0< ; : str-gt ( str len str len -- ? ) compare 0> ; : str-le ( str len str len -- ? ) compare 0<= ; : str-ge ( str len str len -- ? ) compare 0>= ;
Give a code snippet in #Forth 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/Sorting_algorithms/Merge_sort
Sorting algorithms/Merge 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 ...
#Ruby
Ruby
def merge_sort(m) return m if m.length <= 1   middle = m.length / 2 left = merge_sort(m[0...middle]) right = merge_sort(m[middle..-1]) merge(left, right) end   def merge(left, right) result = [] until left.empty? || right.empty? result << (left.first<=right.first ? left.shift : right.shift) end re...
Give a code snippet in #Ruby 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/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...
#Delphi.2FPascal
Delphi/Pascal
program RomanNumeralsDecode;   {$APPTYPE CONSOLE}   function RomanToInteger(const aRoman: string): Integer; function DecodeRomanDigit(aChar: Char): Integer; begin case aChar of 'M', 'm': Result := 1000; 'D', 'd': Result := 500; 'C', 'c': Result := 100; 'L', 'l': Result := 50; 'X', ...
Give a code snippet in #Delphi.2FPascal 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 separ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Line_printer
Hello world/Line printer
Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Open Lpt "Lpt:" As #1 '' prints to default printer Print #1, "Hello World!" Close #1
Give a code snippet in #FreeBASIC Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With ...
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...
#ERRE
ERRE
  PROGRAM AMB   ! ! for rosettacode.org !   !$KEY   DIM SET1$[2],SET2$[2],SET3$[2],SET4$[2]   FUNCTION WORDS_OK(STRING1$,STRING2$) WORDS_OK=(RIGHT$(STRING1$,1)=LEFT$(STRING2$,1)) END FUNCTION   PROCEDURE AMB(SET1$[],SET2$[],SET3$[],SET4$[]->RESULT$) RESULT$="" ! Empty string, e.g. fail FOR A=0 TO 2 DO FOR B=0...
Give a code snippet in #ERRE 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/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguis...
#Phix
Phix
without js -- allocate() forward function A(integer k, object x1, x2, x3, x4, x5) function B(sequence s) object {kptr,x1,x2,x3,x4} = s integer k = peek4s(kptr)-1 poke4(kptr,k) return A(k,{kptr,x1,x2,x3,x4},x1,x2,x3,x4) end function function A(integer k, object x1, x2, x3, x4, x5) if k<=0 then ...
Give a code snippet in #Phix Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim...
christopher/rosetta-code
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#Julia
Julia
for line in eachline("data/fasta.txt") if startswith(line, '>') print(STDOUT, "\n$(line[2:end]): ") else print(STDOUT, "$line") end end
Give a code snippet in #Julia In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Roset...
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...
#Maxima
Maxima
load("descriptive"); mean([2, 7, 11, 17]);
Give a code snippet in #Maxima 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 est...
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 |...
#Axe
Axe
Lbl FUNC If r₁<r₂ Disp "LESS THAN",i End If r₁=r₂ Disp "EQUAL TO",i End If r₁>r₂ Disp "GREATER THAN",i End Return
Give a code snippet in #Axe 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 Co...
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) ...
#Clojure
Clojure
  (doseq [x (range 1 101)] (println x (str (when (zero? (mod x 3)) "fizz") (when (zero? (mod x 5)) "buzz"))))  
Give a code snippet in #Clojure 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   FizzBu...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Pascal
Pascal
program TokenizeString;   {$mode objfpc}{$H+}   uses SysUtils, Classes; const TestString = 'Hello,How,Are,You,Today'; var Tokens: TStringList; I: Integer; begin // Uses FCL facilities, "harder" algorithm not implemented Tokens := TStringList.Create; try Tokens.Delimiter := ','; Tokens.DelimitedTex...
Give a code snippet in #Pascal Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks r...
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#CoffeeScript
CoffeeScript
  halve = (n) -> Math.floor n / 2 double = (n) -> n * 2 is_even = (n) -> n % 2 == 0   multiply = (a, b) -> prod = 0 while a > 0 prod += b if !is_even a a = halve a b = double b prod   # tests do -> for i in [0..100] for j in [0..100] throw Error("broken for #{i} * #{j}") if multiply(i,j) !...
Give a code snippet in #CoffeeScript Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 ...
#Forth
Forth
[UNDEFINED] cell- [IF] : cell- 1 cells - ; [THEN]   defer precedes ( addr addr -- flag ) variable (sorted?) \ is the array sorted?   : (compare) ( a1 a2 -- a1 a2) over @ over @ precedes \ flag if swapped if over over over @ over @ ...
Give a code snippet in #Forth 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/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-bla...
#Racket
Racket
  #lang racket   ;; Using short names to make the code line up nicely (struct N (color left value right) #:prefab)   (define (balance t) (match t [(N 'B (N 'R (N 'R a x b) y c) z d) (N 'R (N 'B a x b) y (N 'B c z d))] [(N 'B (N 'R a x (N 'R b y c)) z d) (N 'R (N 'B a x b) y (N 'B c z d))] [(N 'B a x (N 'R...
Give a code snippet in #Racket Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#Idris
Idris
module Main   import Data.Vect   dotProduct : (Num a) => Vect n a -> Vect n a -> a dotProduct = (sum .) . zipWith (*)   main : IO () main = printLn $ dotProduct [1,2,3] [1,2,3]  
Give a code snippet in #Idris Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1...
christopher/rosetta-code
http://rosettacode.org/wiki/Biorhythms
Biorhythms
For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia, but the main takeaway is that u...
#FreeBASIC
FreeBASIC
#define floor(x) ((x*2.0-0.5) Shr 1) #define pi (4 * Atn(1))   Function Gregorian(db As String) As Integer Dim As Integer M, Y, D Y = Valint(Left(db,4)) : M = Valint(Mid(db,6,2)) : D = Valint(Right(db,2)) Dim As Integer N = (M+9) - Int((M+9)/12) * 12 Dim As Integer W = Y - Int(N/10) Dim As Integer ...
Give a code snippet in #FreeBASIC For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikiped...
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Brainf.2A.2A.2A
Brainf***
bool? value = null
Give a code snippet in #Brainf.2A.2A.2A Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#Nim
Nim
proc halve(x: int): int = x div 2 proc double(x: int): int = x * 2 proc odd(x: int): bool = x mod 2 != 0   proc ethiopian(x, y: int): int = var x = x var y = y   while x >= 1: if odd(x): result += y x = halve x y = double y   echo ethiopian(17, 34)
Give a code snippet in #Nim Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and wri...
christopher/rosetta-code
http://rosettacode.org/wiki/Test_a_function
Test a function
Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
#Phix
Phix
with javascript_semantics requires("0.8.2") function is_palindrome(sequence s) return s==reverse(s) end function --set_test_verbosity(TEST_QUIET) -- default, no output when third call removed --set_test_verbosity(TEST_SUMMARY) -- first and last line only [w or w/o ""] --set_test_verb...
Give a code snippet in #Phix Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
christopher/rosetta-code
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#BASIC
BASIC
'setup DIM foo(10) AS LONG DIM n AS LONG, x AS LONG FOR n = LBOUND(foo) TO UBOUND(foo) foo(n) = INT(RND*99999) NEXT RANDOMIZE TIMER   'random selection x = INT(RND * ((UBOUND(foo) - LBOUND(foo)) + 1))   'output PRINT x, foo(x)
Give a code snippet in #BASIC Demonstrate how to pick a random element from a list.
christopher/rosetta-code
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute z...
#Swift
Swift
  func KtoC(kelvin : Double)->Double{   return kelvin-273.15 }   func KtoF(kelvin : Double)->Double{   return ((kelvin-273.15)*1.8)+32 }   func KtoR(kelvin : Double)->Double{   return ((kelvin-273.15)*1.8)+491.67 }   var k// input print("\(k) Kelvin") var c=KtoC(kelvin : k) print("\(c) Celsius") var f=KtoF(...
Give a code snippet in #Swift There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 ...
christopher/rosetta-code