task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
response_seed
stringclasses
1 value
instruction_seed
stringlengths
27
14.4k
_source
stringclasses
1 value
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#C
C
/* * Write Entire File -- RossetaCode -- dirty hackish solution */ #define _CRT_SECURE_NO_WARNINGS // turn off MS Visual Studio restrictions #include <stdio.h>   int main(void) { return 0 >= fputs("ANY STRING TO WRITE TO A FILE AT ONCE.", freopen("sample.txt","wb",stdout)); }  
Give a code snippet in #C Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#F.C5.8Drmul.C3.A6
Fōrmulæ
func addsub(x, y int) (int, int) { return x + y, x - y }
Give a code snippet in #F.C5.8Drmul.C3.A6 Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#ReScript
ReScript
let fruits = ["apple", "banana", "coconut", "orange", "lychee"]   let pickRand = arr => { let len = Js.Array.length(arr) let i = Js.Math.random_int(0, len) arr[i] }   Js.log(pickRand(fruits))
Give a code snippet in #ReScript Demonstrate how to pick a random element from a list.
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#Objeck
Objeck
  use Structure;   bundle Default { class Median { function : Main(args : String[]) ~ Nil { numbers := FloatVector->New([4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]); DoMedian(numbers)->PrintLine();   numbers := FloatVector->New([4.1, 7.2, 1.7, 9.3, 4.4, 3.2]); DoMedian(numbers)->PrintLine(); }...
Give a code snippet in #Objeck Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values...
christopher/rosetta-code
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   b...
#Dart
Dart
main() { print(new Date.fromEpoch(0,new TimeZone.utc())); }
Give a code snippet in #Dart Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the sc...
christopher/rosetta-code
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap ...
#Rust
Rust
use std::collections::HashSet; use std::fs::File; use std::io::{self, BufRead}; use std::iter::FromIterator;   fn semordnilap(filename: &str) -> std::io::Result<()> { let file = File::open(filename)?; let mut seen = HashSet::new(); let mut count = 0; for line in io::BufReader::new(file).lines() { ...
Give a code snippet in #Rust A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#Raku
Raku
my @langs = < abap actionscript actionscript3 ada apache applescript apt_sources asm asp autoit avisynth bash basic4gl bf blitzbasic bnf boo c caddcl cadlisp cfdg cfm cil c_mac cobol cpp cpp-qt csharp css d delphi diff _div dos dot eiffel email fortran freebasic genero gettext glsl gml gnuplot groov...
Give a code snippet in #Raku Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
christopher/rosetta-code
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: ...
#Ring
Ring
  decimals(8) y = 1.0 for i = 0 to 100 t = i / 10 if t = floor(t) actual = (pow((pow(t,2) + 4),2)) / 16 see "y(" + t + ") = " + y + " error = " + (actual - y) + nl ok k1 = t * sqrt(y) k2 = (t + 0.05) * sqrt(y + 0.05 * k1) k3 = (t + 0.05) * sqrt(y + 0.05 * k2) k4 = (t + 0.10) * ...
Give a code snippet in #Ring Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equ...
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#ooRexx
ooRexx
if arg~isa(.string) & arg~left(1) == "*" then call processArg arg
Give a code snippet in #ooRexx Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Io
Io
System runCommand("ls") stdout println
Give a code snippet in #Io Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#BBC_BASIC
BBC BASIC
DIM matrix(1,1), output(1,1) matrix() = 3, 2, 2, 1   FOR power% = 0 TO 9 PROCmatrixpower(matrix(), output(), power%) PRINT "matrix()^" ; power% " = " FOR row% = 0 TO DIM(output(), 1) FOR col% = 0 TO DIM(output(), 2) PRINT output(row%,col%); NEXT ...
Give a code snippet in #BBC_BASIC Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
christopher/rosetta-code
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#ALGOL_68
ALGOL 68
MODE FIELD = REAL;   MODE VEC = [0]FIELD, MAT = [0,0]FIELD;   PROC VOID raise index error := VOID: ( print(("stop", new line)); stop );   COMMENT from http://rosettacode.org/wiki/Matrix_Transpose#ALGOL_68 END COMMENT OP ZIP = ([,]FIELD in)[,]FIELD:( [2 LWB in:2 UPB in,1 LWB in:1UPB in]FIELD out; FOR i FROM ...
Give a code snippet in #ALGOL_68 Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficie...
christopher/rosetta-code
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ...
#Wren
Wren
import "/fmt" for Fmt   class FloydWarshall { static doCalcs(weights, nVertices) { var dist = List.filled(nVertices, null) for (i in 0...nVertices) dist[i] = List.filled(nVertices, 1/0) for (w in weights) dist[w[0] - 1][w[1] - 1] = w[2] var next = List.filled(nVertices, null) ...
Give a code snippet in #Wren The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already bee...
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#Phix
Phix
string s1 = "at" ?s1 string s2 = "c"&s1 ?s2 string s3 = "s"&s1 ?s3 string s4 = "m"&s1 ?s4 string s5 = "The "&s2&" "&s3&" on the "&s4&"." ?s5
Give a code snippet in #Phix String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string lite...
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...
#Euphoria
Euphoria
  sequence s = {"apple","orange",2.95} -- Euphoria doesn't care what you put in a sequence   ? length(s)   3 -- three objects   ? length(s[1])   5 -- apple has 5 characters   ? length(s[1][$])   1 -- 'e' is an atomic value     ? length(s[$])   1 -- 2.95 is an atomic value    
Give a code snippet in #Euphoria 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 fr...
christopher/rosetta-code
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Ruby
Ruby
size = File.size('input.txt') size = File.size('/input.txt')
Give a code snippet in #Ruby Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
christopher/rosetta-code
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#Wren
Wren
import "graphics" for Canvas, Color import "dome" for Window import "math" for Math   class GreyBars { construct new(width, height) { Window.title = "Grey bars example" Window.resize(width, height) Canvas.resize(width, height) _w = width _h = height }   init() { ...
Give a code snippet in #Wren The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we ha...
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#Babel
Babel
'abcdefg' str2ar {%d nl <<} eachar
Give a code snippet in #Babel Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conv...
christopher/rosetta-code
http://rosettacode.org/wiki/RIPEMD-160
RIPEMD-160
RIPEMD-160 is another hash function; it computes a 160-bit message digest. There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. For padding the message, RIPEMD-160 acts like MD4 (RFC 1320). Find the RIPEMD-160 message digest of a string of octets. Use the ASCII encoded string “Rosetta Cod...
#Objeck
Objeck
  class Hash { function : Main(args : String[]) ~ Nil { in := "Rosetta Code"->ToByteArray(); hash := Encryption.Hash->RIPEMD160(in); hash->ToHexString()->PrintLine(); } }  
Give a code snippet in #Objeck RIPEMD-160 is another hash function; it computes a 160-bit message digest. There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. For padding the message, RIPEMD-160 acts like MD4 (RFC 1320). Find the RIPEMD-160 message digest of a string of octets. Use the A...
christopher/rosetta-code
http://rosettacode.org/wiki/Variable_size/Set
Variable size/Set
Task Demonstrate how to specify the minimum size of a variable or a data type.
#Pascal
Pascal
type correctInteger = integer attribute (size = 42);
Give a code snippet in #Pascal Task Demonstrate how to specify the minimum size of a variable or a data type.
christopher/rosetta-code
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity...
#Ring
Ring
  The next table present operators from higher precedence (Evaluated first) to lower precedence.   Operator . [] () {} - ~ :Literal [list items] ++ - - Start:End * / % + - << >> & | ^ < > <= >= = != not and or Assignment = += -= *= /= %=>>= <<= &= ^= |=   Example:   See 3+5*4 # prints 23  
Give a code snippet in #Ring This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Nautical_bell
Nautical bell
Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off a scheduler, and it is per...
#Wren
Wren
import "os" for Process import "timer" for Timer import "/date" for Date import "/fmt" for Fmt   var watches = ["First", "Middle", "Morning", "Forenoon", "Afternoon", "Dog", "First"]   var args = Process.arguments if (args.count == 0) { System.print("Please enter current time in the format (24 hour clock): hh:mm:ss...
Give a code snippet in #Wren Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Erlang
Erlang
  % This module provides basic operations on ppm files: % Read from file, create ppm in memory (from generic bitmap) and save to file. % Writing PPM files was introduced in roseta code task 'Bitmap/Write a PPM file' % but the same code is included here to provide whole set of operations on ppm % needed for purposes of ...
Give a code snippet in #Erlang Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grays...
christopher/rosetta-code
http://rosettacode.org/wiki/Jaro_similarity
Jaro similarity
The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that   0   equates to no similarities and   1   is an exact match. Definition The...
#Phix
Phix
function jaro(string str1, str2) str1 = trim(upper(str1)) str2 = trim(upper(str2)) integer len1 = length(str1), len2 = length(str2), match_distance = floor(max(len1,len2)/2)-1, match_count = 0, half_transposed = 0 if len1==0 then return len2==0 end if ...
Give a code snippet in #Phix The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that   0   equates to no similarities and   1   is an ...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you ...
#Phix
Phix
with javascript_semantics function perfect_shuffle(sequence deck) integer l = length(deck), mp = l/2, k = 1 sequence res = repeat(0,l) for i=1 to mp do res[k] = deck[i] k += 1 res[k] = deck[i+mp] k += 1 end for return res end function constant testsizes = {8, 24, 52, 100...
Give a code snippet in #Phix A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/String
Literals/String
Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Here document Other tasks r...
#S-lang
S-lang
% String literals variable c, ch, s, b, r, v;   c = 'A'; ch = '\x{1d7bc}';   printf("Double quotes\n"); s = "this is a single line string with\t\tbackslash substitutions"; () = fputs(s, stdout); () = fputs("\n", stdout);   s = "this is a single line string without\t\tbackslash substitutions"R; () = fputs(s, stdout); ()...
Give a code snippet in #S-lang Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters ...
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...
#Aime
Aime
gsss(list l, integer &start, &end, &maxsum) { integer e, f, i, sum;   end = f = maxsum = start = sum = 0; for (i, e in l) { sum += e; if (sum < 0) { sum = 0; f = i + 1; } elif (maxsum < sum) { maxsum = sum; end = i + 1; star...
Give a code snippet in #Aime 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 n...
christopher/rosetta-code
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#zkl
zkl
w:=h:=400; numParticles:=20_000; bitmap:=PPM(w+2,h+2,0); // add borders as clip regions   bitmap[w/2,h/2]=0xff|ff|ff; // plant seed bitmap.circle(w/2,h/2,h/2,0x0f|0f|0f); // plant seeds   fcn touching(x,y,bitmap){ // is (x,y) touching another pixel? // (x,y) isn't on the border/edge of bitmap so no edge c...
Give a code snippet in #zkl Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial ...
christopher/rosetta-code
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Phix
Phix
-- -- Mandlebrot set in ascii art demo. -- constant b=" .:,;!/>)|&IH%*#" atom r, i, c, C, z, Z, t, k for y=30 to 0 by -1 do C = y*0.1-1.5 puts(1,'\n') for x=0 to 74 do c = x*0.04-2 z = 0 Z = 0 r = c i = C k = 0 ...
Give a code snippet in #Phix Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file
Create a file
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#C
C
#include <stdio.h>   int main() { FILE *fh = fopen("output.txt", "w"); fclose(fh);   return 0; }
Give a code snippet in #C In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers
Chernick's Carmichael numbers
In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1: U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1) is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4). Example U(3, m) = (6m + 1) * (12m + 1) * (18m + 1) U(4, m) = U(3, m) * (2^2 * 9m + 1)...
#Julia
Julia
using Primes   function trial_pretest(k::UInt64)   if ((k % 3)==0 || (k % 5)==0 || (k % 7)==0 || (k % 11)==0 || (k % 13)==0 || (k % 17)==0 || (k % 19)==0 || (k % 23)==0) return (k <= 23) end   return true end   function gcd_pretest(k::UInt64)   if (k <= 107) return true en...
Give a code snippet in #Julia In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1: U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1) is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4). Example U(3, m) = (6m + 1) * (12m + 1) * (18m + 1) U(4...
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import "fmt"   var ( animalString = []string{"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"} stemYYString = []string{"Yang", "Yin"} elementString = []string{"Wood", "Fire", "Earth", "Metal", "Water"} stemCh = []rune("甲...
Give a code snippet in #F.C5.8Drmul.C3.A6 Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal de...
christopher/rosetta-code
http://rosettacode.org/wiki/De_Bruijn_sequences
de Bruijn sequences
The sequences are named after the Dutch mathematician   Nicolaas Govert de Bruijn. A note on Dutch capitalization:   Nicolaas' last name is   de Bruijn,   the   de   isn't normally capitalized unless it's the first word in a sentence.   Rosetta Code (more or less by default or by fiat) requires the first word in the...
#Phix
Phix
string deBruijn = "" for n=0 to 99 do string a = sprintf("%02d",n) integer a1 = a[1], a2 = a[2] if a2>=a1 then deBruijn &= iff(a1=a2?a1:a) for m=n+1 to 99 do string ms = sprintf("%02d",m) if ms[2]>a1 then deBruijn &= a&ms end if...
Give a code snippet in #Phix The sequences are named after the Dutch mathematician   Nicolaas Govert de Bruijn. A note on Dutch capitalization:   Nicolaas' last name is   de Bruijn,   the   de   isn't normally capitalized unless it's the first word in a sentence.   Rosetta Code (more or less by default or by fiat) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#Elixir
Elixir
defmodule RC do def spiral_matrix(n) do wide = length(to_char_list(n*n-1)) fmt = String.duplicate("~#{wide}w ", n) <> "~n" runs = Enum.flat_map(n..1, &[&1,&1]) |> tl delta = Stream.cycle([{0,1},{1,0},{0,-1},{-1,0}]) running(Enum.zip(runs,delta),0,-1,[]) |> Enum.with_index |> Enum.sort |> Enum...
Give a code snippet in #Elixir Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. 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 algor...
#Ring
Ring
  aList = [3,5,1,2,7,4,8,3,6,4,1] see combsort(aList)   func combsort t gapd = 1.2473 gap = len(t) swaps = 0 while gap + swaps > 1 k = 0 swaps = 0 if gap > 1 gap = floor(gap / gapd) ok for k = 1 to len(t) - gap if t[k] > t[k + gap] ...
Give a code snippet in #Ring Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. 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 so...
christopher/rosetta-code
http://rosettacode.org/wiki/Image_noise
Image noise
Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
#Phix
Phix
-- demo\rosetta\ImageNoise.exw include pGUI.e   Ihandle dlg, canvas, timer cdCanvas cddbuffer, cdcanvas   constant TITLE = "Image noise"   integer fps = 129 -- (typical value)   function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE") cdCanvasAct...
Give a code snippet in #Phix Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#zkl
zkl
var MsgHash=Import("zklMsgHash"); MsgHash.SHA256("Rosetta code")=="764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"
Give a code snippet in #zkl SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. R...
#Lua
Lua
-- needed for actual task cube.scale = function(self, sx, sy, sz) for i,v in ipairs(self.verts) do v[1], v[2], v[3] = v[1]*sx, v[2]*sy, v[3]*sz end end -- only needed for output -- (to size it for screen, given a limited camera) cube.translate = function(self, tx, ty, tz) for i,v in ipairs(self.verts) do ...
Give a code snippet in #Lua Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is a...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat...
#Factor
Factor
{ 11 9 4 9 4 9 } mode ! 9
Give a code snippet in #Factor Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if p...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is s...
#C
C
#include<stdio.h>   int main() { char ch, str[100]; int i;   do{ printf("\nEnter the string :"); fgets(str,100,stdin); for(i=0;str[i]!=00;i++) { if(str[i]=='#'||str[i]==';') { str[i]=00; break; } } printf("\nThe modified string is : %s",str); printf("\nDo you want to repeat (y/n): "); ...
Give a code snippet in #C Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. White...
christopher/rosetta-code
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#Raku
Raku
# Raku supports multi dimension arrays natively. There are no arbitrary limits on the number of dimensions or maximum indices. Theoretically, you could have an infinite number of dimensions of infinite length, though in practice more than a few dozen dimensions gets unwieldy. An infinite maximum index is a fairly commo...
Give a code snippet in #Raku For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associativ...
#Nim
Nim
import tables   let t1 = {"name": "Rocket Skates", "price": "12.75", "color": "yellow"}.toTable let t2 = {"price": "15.25", "color": "red", "year": "1974"}.toTable   var t3 = t1 # Makes a copy. for key, value in t2.pairs: t3[key] = value   echo t3
Give a code snippet in #Nim Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merg...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#NetRexx
NetRexx
/* NetRexx */   options replace format comments java crossref savelog symbols   numeric digits 210000 /*prepare for some big 'uns. */ parse arg x y . /*allow a single number or range.*/ if x == '' then do /*no input? Then assume -30-->+30*/ x = -30 y =...
Give a code snippet in #NetRexx The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions a...
christopher/rosetta-code
http://rosettacode.org/wiki/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/sub...
#Scala
Scala
def biased( n:Int ) = scala.util.Random.nextFloat < 1.0 / n   def unbiased( n:Int ) = { def loop : Boolean = { val a = biased(n); if( a != biased(n) ) a else loop }; loop }   for( i <- (3 until 7) ) println {   val m = 50000 var c1,c2 = 0   (0 until m) foreach { j => if( biased(i) ) c1 += 1; if( unbiased(i) ) c2...
Give a code snippet in #Scala P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator ...
christopher/rosetta-code
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The s...
#Raku
Raku
sub comma { $^i.flip.comb(3).join(',').flip }   sub schnitzel (\Radda, \radDA = 0) { Radda.is-prime ?? !Radda !! ?radDA ?? Radda !! sum flat (2 .. Radda.sqrt.floor).map: -> \RAdda { my \RADDA = Radda div RAdda; next if RADDA * RAdda !== Radda; RAdda !== RADDA ?? (RAdda, RADDA) !! RADDA ...
Give a code snippet in #Raku Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Superpermutation_minimisation
Superpermutation minimisation
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'...
#Raku
Raku
for 1..8 -> $len { my $pre = my $post = my $t = ''; for ('a'..'z')[^$len].permutations -> @p { $t = @p.join(''); $post ~= $t unless index($post, $t); $pre = $t ~ $pre unless index($pre, $t); } printf "%1d: %8d %8d\n", $len, $pre.chars, $post.chars; }
Give a code snippet in #Raku A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use...
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...
#Wren
Wren
import "/fmt" for Fmt   var sma = Fn.new { |period| var i = 0 var sum = 0 var storage = [] return Fn.new { |input| if (storage.count < period) { sum = sum + input storage.add(input) } sum = sum + input - storage[i] storage[i] = input i = (i...
Give a code snippet in #Wren 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#Pointless
Pointless
isPalindrome(chars) = chars == reverse(chars)
Give a code snippet in #Pointless A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibl...
christopher/rosetta-code
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects ...
#Tcl
Tcl
package require TclOO   oo::class create Delegate { method thing {} { return "delegate impl." } export thing }   oo::class create Delegator { variable delegate constructor args { my delegate {*}$args }   method delegate args { if {[llength $args] == 0} { i...
Give a code snippet in #Tcl A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:...
christopher/rosetta-code
http://rosettacode.org/wiki/Mastermind
Mastermind
Create a simple version of the board game:   Mastermind. It must be possible to:   choose the number of colors will be used in the game (2 - 20)   choose the color code length (4 - 10)   choose the maximum number of guesses the player has (7 - 20)   choose whether or not colors may be repeated in the code The (...
#Ring
Ring
  # Project : Mastermind   colors = ["A", "B", "C", "D"] places = list(2) mind = list(len(colors)) rands = list(len(colors)) master = list(len(colors)) test = list(len(colors)) guesses = 7 repeat = false nr = 0   if repeat for n = 1 to len(colors) while true rnd = random(len(colors)-1) + ...
Give a code snippet in #Ring Create a simple version of the board game:   Mastermind. It must be possible to:   choose the number of colors will be used in the game (2 - 20)   choose the color code length (4 - 10)   choose the maximum number of guesses the player has (7 - 20)   choose whether or not colors may b...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_join
Hash join
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash join" algorithm, and demonstrate tha...
#Clojure
Clojure
  (defn hash-join [table1 col1 table2 col2] (let [hashed (group-by col1 table1)] (flatten (for [r table2] (for [s (hashed (col2 r))] (merge s r))))))   (def s '({:age 27 :name "Jonah"} {:age 18 :name "Alan"} {:age 28 :name "Glory"} {:age 18 :name "Popeye"} ...
Give a code snippet in #Clojure An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash joi...
christopher/rosetta-code
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbe...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Runtime.CompilerServices   Module Module1 <Extension()> Function ToHashSet(Of T)(source As IEnumerable(Of T)) As HashSet(Of T) Return New HashSet(Of T)(source) End Function   <Extension()> Function Reverse(number As Integer) As Integer If number < 0 Then Re...
Give a code snippet in #Visual_Basic_.NET An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the  ...
christopher/rosetta-code
http://rosettacode.org/wiki/De_Bruijn_sequences
de Bruijn sequences
The sequences are named after the Dutch mathematician   Nicolaas Govert de Bruijn. A note on Dutch capitalization:   Nicolaas' last name is   de Bruijn,   the   de   isn't normally capitalized unless it's the first word in a sentence.   Rosetta Code (more or less by default or by fiat) requires the first word in the...
#Racket
Racket
#lang racket   (define (de-bruijn k n) (define a (make-vector (* k n) 0)) (define seq '()) (define (db t p) (cond [(> t n) (when (= (modulo n p) 0) (set! seq (cons (call-with-values (thunk (vector->values a 1 (add1 p))) ...
Give a code snippet in #Racket The sequences are named after the Dutch mathematician   Nicolaas Govert de Bruijn. A note on Dutch capitalization:   Nicolaas' last name is   de Bruijn,   the   de   isn't normally capitalized unless it's the first word in a sentence.   Rosetta Code (more or less by default or by fiat...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_Chess960_starting_position
Generate Chess960 starting position
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must be placed on the second rank. W...
#Julia
Julia
function generateposition() # Placeholder knights rank = ['♘', '♘', '♘', '♘', '♘', '♘', '♘', '♘'] lrank = length(rank)   # Check if a space is available isfree(x::Int) = rank[x] == '♘'   # Place the King rank[indking = rand(2:lrank-1)] = '♔'   # Place rooks rank[indrook = rand(filter...
Give a code snippet in #Julia Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must b...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#AWK
AWK
#!/usr/bin/awk -f   BEGIN { # string creation a="123\0 abc "; b="456\x09"; c="789"; printf("abc=<%s><%s><%s>\n",a,b,c);   # string comparison printf("(a==b) is %i\n",a==b)   # string copying A = a; B = b; C = c; printf("ABC=<%s><%s><%s>\n",A,B,C);   # check if string is empty if (length(a)==0) { printf...
Give a code snippet in #AWK Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings accordi...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#MiniScript
MiniScript
// simple version: sum35 = function(n) sum = 0 for i in range(3, n-1, 3) sum = sum + i end for for i in range(5, n-1, 5) if i % 3 then sum = sum + i // (skip multiples of 3 here) end for return sum end function   print sum35(1000)
Give a code snippet in #MiniScript Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
christopher/rosetta-code
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#Scala
Scala
object TruncatablePrimes { def main(args: Array[String]): Unit = { val max = 1000000   println( s"""|ltPrime: ${ltPrimes.takeWhile(_ <= max).last} |rtPrime: ${rtPrimes.takeWhile(_ <= max).last} |""".stripMargin) }   def ltPrimes: LazyList[Int] = 2 #:: LazyList.from(3, 2).filter(i...
Give a code snippet in #Scala A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatab...
christopher/rosetta-code
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#Ruby
Ruby
Shoes.app(:width => 470, :height => 380) do PI = Shoes::TWO_PI/2   strokewidth 1   def yin_yang(x, y, radius) fill black; stroke black arc x, y, radius, radius, -PI/2, PI/2   fill white; stroke white arc x, y, radius, radius, PI/2, -PI/2 oval x-radius/4, y-radius/2, radius/2-1   fill black...
Give a code snippet in #Ruby One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
christopher/rosetta-code
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#Pascal
Pascal
program project1; uses Classes, sysutils; type TCurrent = record state : string; input : char; end; TMovesTo = record state : string; output : char; moves : char; end; var ST, ET: TDateTime; C:TCurrent; M:TMovesTo; Tape, Rules:TStringList; TP:integer; //TP = Tape position Blank...
Give a code snippet in #Pascal One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machin...
christopher/rosetta-code
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#REBOL
REBOL
; Local. delete %input.txt delete-dir %docs/   ; Root. delete %/input.txt delete-dir %/docs/
Give a code snippet in #REBOL Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/sub...
#Julia
Julia
using Printf   randN(N) = () -> rand(1:N) == 1 ? 1 : 0 function unbiased(biased::Function) this, that = biased(), biased() while this == that this, that = biased(), biased() end return this end   @printf "%2s | %10s | %5s | %5s | %8s" "N" "bias./unb." "1s" "0s" "pct ratio" const nrep = 10000 for N in 3:6 ...
Give a code snippet in #Julia P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator ...
christopher/rosetta-code
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#D
D
import std.stdio, std.string, std.range, std.algorithm;   string nth(in uint n) pure { static immutable suffix = "th st nd rd th th th th th th".split; return "%d'%s".format(n, (n % 100 <= 10 || n % 100 > 20) ? suffix[n % 10] : "th"); }   void main() { foreach (r; [iota(26), iot...
Give a code snippet in #D Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show her...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_frequency
Word frequency
Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a   letter   is.   Undersc...
#Clojure
Clojure
(defn count-words [file n] (->> file slurp clojure.string/lower-case (re-seq #"\w+") frequencies (sort-by val >) (take n)))
Give a code snippet in #Clojure Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#Ruby
Ruby
"J̲o̲s̲é̲".bytesize
Give a code snippet in #Ruby Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme conta...
christopher/rosetta-code
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression...
#Raku
Raku
sub encode($str) { $str.subst(/(.) $0*/, { $/.chars ~ $0 }, :g) }   sub decode($str) { $str.subst(/(\d+) (.)/, { $1 x $0 }, :g) }   my $e = encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'); say $e; say decode($e);
Give a code snippet in #Raku Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a funct...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Nemerle
Nemerle
def original = $[1 .. 100]; def filtered = original.Filter(fun(n) {n % 2 == 0}); WriteLine($"$filtered");
Give a code snippet in #Nemerle Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/Mastermind
Mastermind
Create a simple version of the board game:   Mastermind. It must be possible to:   choose the number of colors will be used in the game (2 - 20)   choose the color code length (4 - 10)   choose the maximum number of guesses the player has (7 - 20)   choose whether or not colors may be repeated in the code The (...
#Prolog
Prolog
mastermind :- mastermind(7, 4, 8, no_duplicates).   mastermind(Colours, Length, Guesses, Duplicates) :- between(2, 20, Colours), between(4, 10, Length), between(7, 20, Guesses), member(Duplicates, [allow_duplicates, no_duplicates]),   create_board(Colours, Length, Duplicates, Board), intro(Colours, Length, Duplic...
Give a code snippet in #Prolog Create a simple version of the board game:   Mastermind. It must be possible to:   choose the number of colors will be used in the game (2 - 20)   choose the color code length (4 - 10)   choose the maximum number of guesses the player has (7 - 20)   choose whether or not colors may...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#WebAssembly
WebAssembly
(module $lowercase   (import "wasi_unstable" "fd_write" (func $fd_write (param i32 i32 i32 i32) (result i32)) )   (memory 1) (export "memory" (memory 0))   (func $main (export "_start") (local $i i32)   (i32.store (i32.const 0) (i32.const 8))  ;; offset to start of string (i32.store (i32.cons...
Give a code snippet in #WebAssembly Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task ...
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#Go
Go
package main   import "time" import "fmt"   func main() { t := time.Now() fmt.Println(t) // default format fmt.Println(t.Format("Mon Jan 2 15:04:05 2006")) // some custom format }
Give a code snippet in #Go Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Dat...
christopher/rosetta-code
http://rosettacode.org/wiki/RIPEMD-160
RIPEMD-160
RIPEMD-160 is another hash function; it computes a 160-bit message digest. There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. For padding the message, RIPEMD-160 acts like MD4 (RFC 1320). Find the RIPEMD-160 message digest of a string of octets. Use the ASCII encoded string “Rosetta Cod...
#Kotlin
Kotlin
import org.bouncycastle.crypto.digests.RIPEMD160Digest import org.bouncycastle.util.encoders.Hex import kotlin.text.Charsets.US_ASCII   fun RIPEMD160Digest.inOneGo(input : ByteArray) : ByteArray { val output = ByteArray(digestSize)   update(input, 0, input.size) doFinal(output, 0)   return output }   fu...
Give a code snippet in #Kotlin RIPEMD-160 is another hash function; it computes a 160-bit message digest. There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. For padding the message, RIPEMD-160 acts like MD4 (RFC 1320). Find the RIPEMD-160 message digest of a string of octets. Use the A...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
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. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#Racket
Racket
  #lang racket   (define (make-queue) (mcons #f #f)) (define (push! q x) (define new (mcons x #f)) (if (mcar q) (set-mcdr! (mcdr q) new) (set-mcar! q new)) (set-mcdr! q new)) (define (pop! q) (define old (mcar q)) (cond [(eq? old (mcdr q)) (set-mcar! q #f) (set-mcdr! q #f)] [else (set-mcar! q (mcdr ol...
Give a code snippet in #Racket 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. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar tricker...
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func begin writeln("hello world"); end func;
Give a code snippet in #Seed7 Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages m...
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...
#Icon_and_Unicon
Icon and Unicon
link numbers # for a/g/h means   procedure main() every put(x := [], 1 to 10) writes("x := [ "); every writes(!x," "); write("]")   write("Arithmetic mean:", a := amean!x) write("Geometric mean:",g := gmean!x) write("Harmonic mean:", h := hmean!x) write(" a >= g >= h is ", if a >= g >= h then "true" else "false") e...
Give a code snippet in #Icon_and_Unicon 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(...
christopher/rosetta-code
http://rosettacode.org/wiki/Cistercian_numerals
Cistercian numerals
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyp...
#Phix
Phix
-- -- Define each digit as {up-down multiplier, left-right multiplier, char}, -- that is starting each drawing from line 1 or 7, column 3, -- and with `/` and `\` being flipped below when necessary. -- with javascript_semantics constant ds = {{{0,0,'+'},{0,1,'-'},{0,2,'-'}}, -- 1 ...
Give a code snippet in #Phix Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself repre...
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) ...
#Smalltalk
Smalltalk
Integer extend [ fizzbuzz [ | fb | fb := '%<Fizz|>1%<Buzz|>2' % { self \\ 3 == 0. self \\ 5 == 0 }. ^fb isEmpty ifTrue: [ self ] ifFalse: [ fb ] ] ] 1 to: 100 do: [ :i | i fizzbuzz displayNl ]
Give a code snippet in #Smalltalk 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   Fizz...
christopher/rosetta-code
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#Phix
Phix
?sin(PI/2) ?sin(90*PI/180) ?cos(0) ?cos(0*PI/180) ?tan(PI/4) ?tan(45*PI/180) ?arcsin(1)*2 ?arcsin(1)*180/PI ?arccos(0)*2 ?arccos(0)*180/PI ?arctan(1)*4 ?arctan(1)*180/PI
Give a code snippet in #Phix Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evalua...
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" /...
#MATLAB
MATLAB
RootXML = com.mathworks.xml.XMLUtils.createDocument('Students'); docRootNode = RootXML.getDocumentElement; thisElement = RootXML.createElement('Student'); thisElement.setAttribute('Name','April') thisElement.setAttribute('Gender','F') thisElement.setAttribute('DateOfBirth','1989-01-02') docRootNode.appendChild(thisElem...
Give a code snippet in #MATLAB 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/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...
#Lasso
Lasso
local(x = 0) while(#x % 6 > 0 || #x == 0) => {^ ++#x '\r' // for formatting ^}
Give a code snippet in #Lasso Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/D...
christopher/rosetta-code
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth, ...
#JavaScript
JavaScript
(() => { 'use strict';   // main :: IO () const main = () => { const month = fst, day = snd; showLog( map(x => Array.from(x), (   // The month with only one remaining day,   // (A's month contains only one remaining day) ...
Give a code snippet in #JavaScript Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then t...
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.
#C.2B.2B
C++
#include <complex> #include <cmath> #include <iostream>   double const pi = 4 * std::atan(1);   int main() { for (int n = 2; n <= 10; ++n) { std::cout << n << ": "; for (int k = 0; k < n; ++k) std::cout << std::polar(1, 2*pi*k/n) << " "; std::cout << std::endl; } }
Give a code snippet in #C.2B.2B 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/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#Klingphix
Klingphix
include ..\Utilitys.tlhy   %limit %i 1000 !limit ( 1 $limit ) sequence   ( 2 $limit sqrt int ) [ !i $i get [ ( 2 $limit 1 - $i / int ) [ $i * false swap set ] for ] if ] for ( 1 $limit false ) remove pstack   "Press ENTER to end " input
Give a code snippet in #Klingphix This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#PureBasic
PureBasic
EnableExplicit Declare main() Declare.i mi(a.i, b.i)   If OpenConsole("MODULAR-INVERSE") main() : Input() : End EndIf   Macro ModularInverse(a, b) PrintN(~"\tMODULAR-INVERSE(" + RSet(Str(a),5) + "," + RSet(Str(b),5)+") = " + RSet(Str(mi(a, b)),5)) EndMacro   Procedure main() ModularInvers...
Give a code snippet in #PureBasic From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagoras_tree
Pythagoras tree
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 using only vectors (no rotation or ...
#C.2B.2B
C++
#include <windows.h> #include <string> #include <iostream>   const int BMP_SIZE = 720, LINE_LEN = 120, BORDER = 100;   class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( ...
Give a code snippet in #C.2B.2B The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 us...
christopher/rosetta-code
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bit...
#Modula-2
Modula-2
MODULE Entropy; FROM InOut IMPORT WriteString, WriteLn; FROM RealInOut IMPORT WriteReal; FROM Strings IMPORT Length; FROM MathLib IMPORT ln;   PROCEDURE entropy(s: ARRAY OF CHAR): REAL; VAR freq: ARRAY [0..255] OF CARDINAL; i, length: CARDINAL; h, f: REAL; BEGIN (* the entropy of the empt...
Give a code snippet in #Modula-2 Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits ...
#REXX
REXX
/* REXX **************************************************************** * 01.11.2012 Walter Pachl ***********************************************************************/ s='STRING' /* Test input */ Say 's='s ol='' /* initialize target ...
Give a code snippet in #REXX The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the ou...
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 "...
#Wren
Wren
import "/fmt" for Fmt   var environment = Fn.new { class E { construct new(value, count) { _value = value _count = count }   value { _value } count { _count }   hailstone() { Fmt.write("$4d", _value) if (_value == 1) return ...
Give a code snippet in #Wren 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 prog...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#VBScript
VBScript
Dim variable As datatype Dim var1,var2,... As datatype
Give a code snippet in #VBScript Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
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
#PARI.2FGP
PARI/GP
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
Give a code snippet in #PARI.2FGP 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/Jewels_and_stones
Jewels and stones
Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case ...
#BASIC256
BASIC256
  function contar_joyas(piedras, joyas) cont = 0 for i = 1 to length(piedras) bc = instr(joyas, mid(piedras, i, 1), 1) if bc <> 0 then cont += 1 next i return cont end function   print contar_joyas("aAAbbbb", "aA") print contar_joyas("ZZ", "z") print contar_joyas("ABCDEFGHIJKLMNOPQRSTUVWXYZ@abcdefghijklmnopqrst...
Give a code snippet in #BASIC256 Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower c...
christopher/rosetta-code
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#F.23
F#
let cin = [ 0.06m .. 0.05m ..1.01m ] let cout = [0.1m; 0.18m] @ [0.26m .. 0.06m .. 0.44m] @ [0.50m .. 0.04m .. 0.98m] @ [1.m]   let priceadjuster p = let rec bisect lo hi = if lo < hi then let mid = (lo+hi)/2. let left = p < cin.[int mid] bisect (if left then lo else mid...
Give a code snippet in #F.23 A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle
Find if a point is within a triangle
Find if a point is within a triangle. Task   Assume points are on a plane defined by (x, y) real number coordinates.   Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.   You may use any algorithm.   Bonus: explain why the algorithm you chose works. Re...
#D
D
import std.algorithm; //.comparison for min and max import std.stdio;   immutable EPS = 0.001; immutable EPS_SQUARE = EPS * EPS;   double side(double x1, double y1, double x2, double y2, double x, double y) { return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1); }   bool naivePointInTriangle(double x1, double y1, do...
Give a code snippet in #D Find if a point is within a triangle. Task   Assume points are on a plane defined by (x, y) real number coordinates.   Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.   You may use any algorithm.   Bonus: explain why the algo...
christopher/rosetta-code
http://rosettacode.org/wiki/Jacobsthal_numbers
Jacobsthal numbers
Jacobsthal numbers are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1. J0 = 0 J1 = 1 Jn = Jn-1 + 2 ×...
#C
C
#include <stdio.h> #include <gmp.h>   void jacobsthal(mpz_t r, unsigned long n) { mpz_t s; mpz_init(s); mpz_set_ui(r, 1); mpz_mul_2exp(r, r, n); mpz_set_ui(s, 1); if (n % 2) mpz_neg(s, s); mpz_sub(r, r, s); mpz_div_ui(r, r, 3); }   void jacobsthal_lucas(mpz_t r, unsigned long n) { mp...
Give a code snippet in #C Jacobsthal numbers are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1. J0 = 0 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body...
#Java
Java
  for (int i = 10; i >= 0; i--) { System.out.println(i); }  
Give a code snippet in #Java Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increme...
christopher/rosetta-code
http://rosettacode.org/wiki/Brilliant_numbers
Brilliant numbers
Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10. Brilliant numbers are useful in cryptography and when testing prime factoring algorithms. E.G. 3 × 3 (9) is a bri...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[PrimesDecade] PrimesDecade[n_Integer] := Module[{bounds}, bounds = {PrimePi[10^n] + 1, PrimePi[10^(n + 1) - 1]}; Prime[Range @@ bounds] ] ds = Union @@ Table[Union[Times @@@ Tuples[PrimesDecade[d], 2]], {d, 0, 4}];   Multicolumn[Take[ds, 100], {Automatic, 8}, Appearance -> "Horizontal"]   sel = Min /@ Ga...
Give a code snippet in #Mathematica.2FWolfram_Language Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10. Brilliant numbers are useful in cryptography and when testing...
christopher/rosetta-code
http://rosettacode.org/wiki/Damm_algorithm
Damm algorithm
The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
#Pascal
Pascal
program DammAlgorithm; uses sysutils;   TYPE TA = ARRAY[0..9,0..9] OF UInt8; CONST table : TA = ((0,3,1,7,5,9,8,6,4,2), (7,0,9,2,1,5,4,8,6,3), (4,2,0,6,8,7,1,3,5,9), (1,7,5,0,9,8,3,4,2,6), (6,1,2,3,0,4,5,9,7,8), (3,6,...
Give a code snippet in #Pascal The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
christopher/rosetta-code
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of...
#C
C
#include <stdio.h> #include <stdlib.h>   int verbose = 0; #define COND(a, b) int a(int *s) { return (b); } typedef int(*condition)(int *);   /* BEGIN problem specific setup */ #define N_FLOORS 5 #define TOP (N_FLOORS - 1) int solution[N_FLOORS] = { 0 }; int occupied[N_FLOORS] = { 0 };   enum tenants { baker = 0, coop...
Give a code snippet in #C Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allow...
christopher/rosetta-code
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#Racket
Racket
  #lang racket (require slideshow/pict)   (define (yin-yang d) (define base (hc-append (inset/clip (circle d) 0 0 (- (/ d 2)) 0) (inset/clip (disk d) (- (/ d 2)) 0 0 0))) (define with-top (ct-superimpose base (cc-superimpose (colorize (disk (/ d 2)) "white") (d...
Give a code snippet in #Racket One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
christopher/rosetta-code
http://rosettacode.org/wiki/Jacobsthal_numbers
Jacobsthal numbers
Jacobsthal numbers are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1. J0 = 0 J1 = 1 Jn = Jn-1 + 2 ×...
#ALGOL_68
ALGOL 68
BEGIN # find some Jacobsthal and related Numbers # INT max jacobsthal = 29; # highest Jacobsthal number we will find # INT max oblong = 20; # highest Jacobsthal oblong number we will find # INT max j prime = 20; # number of Jacobsthal prinmes we will find # ...
Give a code snippet in #ALGOL_68 Jacobsthal numbers are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1. J...
christopher/rosetta-code
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm
Xiaolin Wu's line algorithm
Task Implement the   Xiaolin Wu's line algorithm   described in Wikipedia. This algorithm draws anti-aliased lines. Related task   See   Bresenham's line algorithm   for aliased lines.
#Racket
Racket
#lang racket (require 2htdp/image)   (define (plot img x y c) (define c*255 (exact-round (* (- 1 c) 255))) (place-image (rectangle 1 1 'solid (make-color c*255 c*255 c*255 255)) x y img))   (define ipart exact-floor) ; assume that a "round-down" is what we want when -ve ;;; `round` is built in -- but we'll us...
Give a code snippet in #Racket Task Implement the   Xiaolin Wu's line algorithm   described in Wikipedia. This algorithm draws anti-aliased lines. Related task   See   Bresenham's line algorithm   for aliased lines.
christopher/rosetta-code
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#Haskell
Haskell
import qualified Data.ByteString as BY (writeFile, pack)   import Data.Bits (xor)   main :: IO () main = BY.writeFile "out.pgm" (BY.pack (fmap (fromIntegral . fromEnum) "P5\n256 256\n256\n" ++ [ x `xor` y | x <- [0 .. 255] , y <- [0 .. 255] ]))
Give a code snippet in #Haskell Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
christopher/rosetta-code