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/Tau_function
Tau function
Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
DivisorSum[#, 1 &] & /@ Range[100]
Give a code snippet in #Mathematica.2FWolfram_Language Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print str...
#Draco
Draco
\util.g   proc nonrec stripchars(*char str, chars, outbuf) *char: channel input text ch_in; channel output text ch_out; [2]char cur = ('\e', '\e');   open(ch_in, str); open(ch_out, outbuf); while read(ch_in; cur[0]) do if CharsIndex(chars, &cur[0]) = -1 then write(ch_out; cur...
Give a code snippet in #Draco Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in t...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f...
#Swift
Swift
import Foundation   let numberFormat = " %7.3f" let k = 0.07 let initialTemp = 100.0 let finalTemp = 20.0 let startTime = 0 let endTime = 100   func ivpEuler(function: (Double, Double) -> Double, initialValue: Double, step: Int) { print(String(format: " Step %2d: ", step), terminator: "") var y = initialValue ...
Give a code snippet in #Swift Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: ...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#Oforth
Oforth
[ [1000,"M"], [900,"CM"], [500,"D"], [400,"CD"], [100,"C"], [90,"XC"], [50,"L"], [40,"XL"], [10,"X"], [9,"IX"], [5,"V"], [4,"IV"], [1,"I"] ] const: Romans   : roman(n) | r | StringBuffer new Romans forEach: r [ while(r first n <=) [ r second << n r first - ->n ] ] ;
Give a code snippet in #Oforth Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a va...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Retro
Retro
 
Give a code snippet in #Retro Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#ALGOL_W
ALGOL W
begin % draw an Archimedian spiral %  % Translation of AWK which was a trnslation of Applesoft Basic program % integer procedure max ( integer x, y ) ; begin if x > y then x else y end; integer procedure min ( integer x, y ) ; begin if x < y then x else y end; integer x_min, y_min, x_max, y_max, a, b, ...
Give a code snippet in #ALGOL_W The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#Gema
Gema
<D> <D>=@add{$1;$2}
Give a code snippet in #Gema A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated...
christopher/rosetta-code
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#VBScript
VBScript
' Population count - VBScript - 10/05/2019 nmax=30 b=3 n=0: list="": bb=1 For i=0 To nmax-1 list=list & " " & popcount(bb) bb=bb*b Next 'i Msgbox list,,"popcounts of the powers of " & b For j=0 to 1 If j=0 Then c="evil numbers": Else c="odious numbers" n=0: list="": i=0 While n<nmax If (popcount(i) ...
Give a code snippet in #VBScript Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop co...
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
#Stata
Stata
!dir   * print a message and wait !echo Ars Longa Vita Brevis & pause   * load Excel from Stata !start excel   * run a Python program (Python must be installed and accessible in the PATH environment variable) !python preprocessing.py   * load Windows Notepad winexec notepad
Give a code snippet in #Stata 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/Sleep
Sleep
Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread for the given amount of time. ...
#AutoIt
AutoIt
#AutoIt Version: 3.2.10.0 $sleep_me=InputBox("Sleep", "Number of seconds to sleep", "10", "", -1, -1, 0, 0) Dim $sleep_millisec=$sleep_me*1000 MsgBox(0,"Sleep","Sleeping for "&$sleep_me&" sec") sleep ($sleep_millisec) MsgBox(0,"Awake","... Awaking")
Give a code snippet in #AutoIt Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main threa...
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 ...
#TypeScript
TypeScript
  function levenshtein(a: string, b: string): number { const m: number = a.length, n: number = b.length; let t: number[] = [...Array(n + 1).keys()], u: number[] = []; for (let i: number = 0; i < m; i++) { u = [i + 1]; for (let j: number = 0; j < n; j++) { u[j + 1] = a[i] ==...
Give a code snippet in #TypeScript 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 an...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth ...
#AWK
AWK
  # syntax: GAWK -f SEQUENCE_SMALLEST_NUMBER_GREATER_THAN_PREVIOUS_TERM_WITH_EXACTLY_N_DIVISORS.AWK # converted from Kotlin BEGIN { limit = 15 printf("first %d terms:",limit) n = 1 while (n <= limit) { if (n == count_divisors(++i)) { printf(" %d",i) n++ } } printf("\n...
Give a code snippet in #AWK Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exact...
christopher/rosetta-code
http://rosettacode.org/wiki/Introspection
Introspection
Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop). Extra credit Repor...
#Ring
Ring
  # Project: Introspection   if version() < 1.8 see "Version is too old" + " (" + version() + ")" + nl else see "Version is uptodate" + " (" + version() + ")" + nl ok bloop = 5 if isglobal("bloop") = 1 see "Variable " + "'bloop'" + " exists" + nl else see "Variable " + "'bloop'" + " doesn't exist" + nl ok i...
Give a code snippet in #Ring Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort
Sorting algorithms/Strand 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 ...
#Euphoria
Euphoria
function merge(sequence left, sequence right) sequence result result = {} while length(left) > 0 and length(right) > 0 do if left[$] <= right[1] then exit elsif right[$] <= left[1] then return result & right & left elsif left[1] < right[1] then res...
Give a code snippet in #Euphoria 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. 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 algebra, polynomial long division is an algorithm for d...
#APL
APL
div←{ { q r d←⍵ (≢d) > n←≢r : q r c ← (⊃⌽r) ÷ ⊃⌽d ∇ (c,q) ((¯1↓r) - c × ¯1↓(-n)↑d) d } ⍬ ⍺ ⍵ }  
Give a code snippet in #APL This page uses content from Wikipedia. The original article was at Polynomial long division. 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 algebra, polynomial long d...
christopher/rosetta-code
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive
Verify distribution uniformity/Naive
This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) producing random integers. The number of times ...
#C.2B.2B
C++
#include <map> #include <iostream> #include <cmath>   template<typename F> bool test_distribution(F f, int calls, double delta) { typedef std::map<int, int> distmap; distmap dist;   for (int i = 0; i < calls; ++i) ++dist[f()];   double mean = 1.0/dist.size();   bool good = true;   for (distmap::iterato...
Give a code snippet in #C.2B.2B This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) producing rando...
christopher/rosetta-code
http://rosettacode.org/wiki/Pinstripe/Display
Pinstripe/Display
Sample image The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display. in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes Quarter of the way down the display, we can switch to a wider 2 pi...
#C.23
C#
  using System.Drawing;   public class Pinstripe { static void Main(string[] args) { var pinstripe = MakePinstripeImage(1366, 768); pinstripe.Save("pinstripe.png"); }   public static Bitmap MakePinstripeImage(int width, int height) { var image = new Bitmap(width, height); ...
Give a code snippet in #C.23 Sample image The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display. in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes Quarter of the way down the display,...
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...
#Snobol
Snobol
&ALPHABET ('a' LEN(25)) . OUTPUT ;* Works in ASCII but not EBCDIC.
Give a code snippet in #Snobol 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...
christopher/rosetta-code
http://rosettacode.org/wiki/2048
2048
Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some move more than others.   Two ...
#Racket
Racket
  ;; LICENSE: See License file LICENSE (MIT license) ;; ;; Repository: https://github.com/danprager/2048 ;; ;; Copyright 2014: Daniel Prager ;; daniel.a.prager@gmail.com ;; ;; This is a largely clean-room, functional implementation in Racket ;; of the game 2048 by Gabriele Cirulli, based on 1024 by Vee...
Give a code snippet in #Racket Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#UNIX_Shell
UNIX Shell
  whiptail --title 'Farewell' --msgbox 'Goodbye, World!' 7 20  
Give a code snippet in #UNIX_Shell Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#REXX
REXX
/*REXX program finds the roots of a specific function: x^3 - 3*x^2 + 2*x via bisection*/ parse arg bot top inc . /*obtain optional arguments from the CL*/ if bot=='' | bot=="," then bot= -5 /*Not specified? Then use the default.*/ if top=='' | top=="," then top= +5 ...
Give a code snippet in #REXX Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
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
#Verilog
Verilog
module main; initial begin $write("Goodbye, World!"); $finish ; end endmodule
Give a code snippet in #Verilog 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/Sta...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Scheme
Scheme
; Commented line below should be uncommented to use read-line with Guile ;(use-modules (ice-9 rdelim))   (define file (open-input-file "input.txt")) (do ((line (read-line file) (read-line file))) ((eof-object? line)) (display line) (newline))
Give a code snippet in #Scheme Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
christopher/rosetta-code
http://rosettacode.org/wiki/Introspection
Introspection
Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop). Extra credit Repor...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
If[$VersionNumber < 8, Quit[]] If[NameQ["bloop"] && NameQ["Abs"], Print[Abs[bloop]]]
Give a code snippet in #Mathematica.2FWolfram_Language Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is availab...
christopher/rosetta-code
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#C
C
  /*Almost every C program has the below line, the #include preprocessor directive is used to instruct the compiler which files to load before compiling the program.   All preprocessor commands begin with # */ #include<stdio.h>   /*The #define preprocessor directive is often used to create abbreviations for code seg...
Give a code snippet in #C Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how...
christopher/rosetta-code
http://rosettacode.org/wiki/String_matching
String matching
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 |...
#VBScript
VBScript
Function StartsWith(s1,s2) StartsWith = False If Left(s1,Len(s2)) = s2 Then StartsWith = True End If End Function   Function Contains(s1,s2) Contains = False If InStr(1,s1,s2) Then Contains = True & " at positions " j = 1 Do Until InStr(j,s1,s2) = False Contains = Contains & InStr(j,s1,s2) & ", " If ...
Give a code snippet in #VBScript 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 Operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f...
#PureBasic
PureBasic
Define.d Prototype.d Func(Time, t)   Procedure.d Euler(*F.Func, y0, a, b, h) Protected y=y0, t=a While t<=b PrintN(RSet(StrF(t,3),7)+" "+RSet(StrF(y,3),7)) y + h * *F(t,y) t + h Wend EndProcedure   Procedure.d newtonCoolingLaw(Time, t) ProcedureReturn -0.07*(t-20) EndProcedure     If OpenConsole() ...
Give a code snippet in #PureBasic Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following fo...
christopher/rosetta-code
http://rosettacode.org/wiki/String_interpolation_(included)
String interpolation (included)
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 |...
#JavaScript
JavaScript
var original = "Mary had a X lamb"; var little = "little"; var replaced = original.replace("X", little); //does not change the original string
Give a code snippet in #JavaScript 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 Operat...
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...
#FreeBASIC
FreeBASIC
' version 16-09-2015 ' compile with: fbc -s console   Function agm(a As Double, g As Double) As Double   Dim As Double t_a   Do t_a = (a + g) / 2 g = Sqr(a * g) Swap a, t_a Loop Until a = t_a   Return a   End Function   ' ------=< MAIN >=------   Print agm(1, 1 / Sqr(2) )   ' em...
Give a code snippet in #FreeBASIC 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 functi...
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.
#C
C
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h>   void hue_to_rgb(double hue, double sat, unsigned char *p) { double x; int c = 255 * sat; hue /= 60; x = (1 - fabs(fmod(hue, 2) - 1)) * 255;   switch((int)hue) { case 0: p[0] = c; p[1] = x; p[2] = 0; return; case 1: p[0] = x; p[1] = c;...
Give a code snippet in #C Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
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...
#Run_BASIC
Run BASIC
' Create string s$ = "Hello, world"   ' String destruction s$ = ""   ' String comparison If s$ = "Hello, world" then print "Equal String"   ' Copying string a$ = s$   ' Check If empty If s$ = "" then print "String is MT"   ' Append a byte s$ = s$ + Chr$(65)   ' Extract a substring a$ = Mid$(s$, 1, 5) '...
Give a code snippet in #Run_BASIC 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 a...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, sho...
#Go
Go
package main   import ( "fmt" "strings" )   func wrap(text string, lineWidth int) (wrapped string) { words := strings.Fields(text) if len(words) == 0 { return } wrapped = words[0] spaceLeft := lineWidth - len(wrapped) for _, word := range words[1:] { if len(word)+1 > spac...
Give a code snippet in #Go Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provide...
christopher/rosetta-code
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#Clojure
Clojure
(let [bounds (set (range 100)) xs [1 0 -1 0] ys [0 -1 0 1]] (loop [dir 0 x 50 y 50 grid {[x y] false}] (if (and (bounds x) (bounds y)) (let [cur (not (grid [x y])) dir (mod (+ dir (if cur -1 1)) 4)] (recur dir (+ x (xs dir)) (+ y (ys dir)) (merge grid {[x y]...
Give a code snippet in #Clojure Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with t...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#EGL
EGL
-- inline comment, continues until new line
Give a code snippet in #EGL Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Dining_philosophers
Dining philosophers
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a rou...
#Julia
Julia
  mutable struct Philosopher name::String hungry::Bool righthanded::Bool rightforkheld::Channel leftforkheld::Channel function Philosopher(name, leftfork, rightfork) this = new() this.name = name this.hungry = rand([false, true]) # not specified so start as either ...
Give a code snippet in #Julia The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eati...
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...
#R
R
checkSentence <- function(sentence){ # Input: character vector # Output: whether the sentence formed by the elements of the vector is valid for (index in 1:(length(sentence)-1)){ first.word <- sentence[index] second.word <- sentence[index+1]   last.letter <- substr(first.word, nchar(first.word), nchar(f...
Give a code snippet in #R 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/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#BBC_BASIC
BBC BASIC
  DIM a(4) a() = 1, 2, 3, 4, 5 PRINT FNreduce(a(), "+") PRINT FNreduce(a(), "-") PRINT FNreduce(a(), "*") END   DEF FNreduce(arr(), op$) REM!Keep tmp, arr() LOCAL I%, tmp tmp = arr(0) FOR I% = 1 TO DIM(arr(), 1) tmp = EVAL("tmp " + op$ + " arr(I%...
Give a code snippet in #BBC_BASIC Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language...
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#AWK
AWK
  # syntax: GAWK -f PYTHAGOREAN_TRIPLES.AWK # converted from Go BEGIN { printf("%5s %11s %11s %11s %s\n","limit","limit","triples","primitives","seconds") for (max_peri=10; max_peri<=1E9; max_peri*=10) { t = systime() prim = 0 total = 0 new_tri(3,4,5) printf("10^%-2d %11d %11d %11d...
Give a code snippet in #AWK A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displa...
christopher/rosetta-code
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#Elixir
Elixir
  def fun(bar: bar, baz: baz), do: IO.puts "#{bar}, #{baz}."   fun(bar: "bar", baz: "baz")  
Give a code snippet in #Elixir Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on ...
christopher/rosetta-code
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyl...
#Go
Go
package main   import "fmt"   func kPrime(n, k int) bool { nf := 0 for i := 2; i <= n; i++ { for n%i == 0 { if nf == k { return false } nf++ n /= i } } return nf == k }   func gen(k, n int) []int { r := make([]int, n) ...
Give a code snippet in #Go A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where...
christopher/rosetta-code
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file...
#PureBasic
PureBasic
#BaseTime =50 #Frequence=1250 #Short = #BaseTime #Long =3* #BaseTime #Intergap = #BaseTime #LetterGap=3* #BaseTime #WordGap =7* #BaseTime   Declare.s TextToMorse(Text$) Declare.i PlayMorse(Text$)   Text$ =InputRequester("Morse coder","Enter text to send","Hello RosettaWorld!") Text$ =TextToMorse(Text$) If N...
Give a code snippet in #PureBasic Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ig...
christopher/rosetta-code
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#Elixir
Elixir
  IO.puts("P - F - S") for p <- [2,4,6], f <- 1..7, s <- 1..7, p != f and p != s and f != s and p + f + s == 12 do "#{p} - #{f} - #{s}" end |> Enum.each(&IO.puts/1)    
Give a code snippet in #Elixir There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (d...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#ALGOL_W
ALGOL W
begin  % find the first few squares via the unoptimised door flipping method  %   integer doorMax; doorMax := 100;   begin  % need to start a new block so the array can have variable bounds  %    % array of doors - door( i ) is true if open, false if closed  % logical array d...
Give a code snippet in #ALGOL_W There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Maple
Maple
> cfloor := define_external( floor, s::float[8], RETURN::float[8], LIB = "libm.so" ): > cfloor( 2.3 ); 2.
Give a code snippet in #Maple Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign languag...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic 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. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle n...
#Delphi
Delphi
defmodule Quadratic do def roots(a, b, c) do IO.puts "Roots of a quadratic function (#{a}, #{b}, #{c})" d = b * b - 4 * a * c a2 = a * 2 cond do d > 0 -> sd = :math.sqrt(d) IO.puts " the real roots are #{(- b + sd) / a2} and #{(- b - sd) / a2}" d == 0 -> IO.puts " ...
Give a code snippet in #Delphi This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Def...
#Julia
Julia
mutable struct DLNode{T} value::T pred::Union{DLNode{T}, Nothing} succ::Union{DLNode{T}, Nothing} DLNode(v) = new{typeof(v)}(v, nothing, nothing) end   function insertpost(prevnode, node) succ = prevnode.succ prevnode.succ = node node.pred = prevnode node.succ = succ if succ != nothi...
Give a code snippet in #Julia Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element R...
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...
#Phix
Phix
function mul_inv(integer a, n) if n<0 then n = -n end if if a<0 then a = n - mod(-a,n) end if integer t = 0, nt = 1, r = n, nr = a; while nr!=0 do integer q = floor(r/nr) {t, nt} = {nt, t-q*nt} {r, nr} = {nr, r-q*nr} end while if r>1 then return "a is not...
Give a code snippet in #Phix 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 {\d...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#Never
Never
func printv(a[d] : float) -> int { prints("[" + a[0] + ", " + a[1] + ", " + a[2] + "]\n"); 0 }   func dot(a[d1] : float, b[d2] : float) -> float { a[0] * b[0] + a[1] * b[1] + a[2] * b[2] }   func cross(a[d1] : float, b[d2] : float) -> [_] : float { [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2]...
Give a code snippet in #Never A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#Python
Python
def digital_root (n): ap = 0 n = abs(int(n)) while n >= 10: n = sum(int(digit) for digit in str(n)) ap += 1 return ap, n   if __name__ == '__main__': for n in [627615, 39390, 588225, 393900588225, 55]: persistance, root = digital_root(n) print("%12i has additive persi...
Give a code snippet in #Python The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} ,...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 ...
#Perl
Perl
  sub quick_sort { return @_ if @_ < 2; my $p = splice @_, int rand @_, 1; quick_sort(grep $_ < $p, @_), $p, quick_sort(grep $_ >= $p, @_); }   my @a = (4, 65, 2, -31, 0, 99, 83, 782, 1); @a = quick_sort @a; print "@a\n";  
Give a code snippet in #Perl 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/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\di...
#Swift
Swift
import Foundation   func mapRanges(_ r1: ClosedRange<Double>, _ r2: ClosedRange<Double>, to: Double) -> Double { let num = (to - r1.lowerBound) * (r2.upperBound - r2.lowerBound) let denom = r1.upperBound - r1.lowerBound   return r2.lowerBound + num / denom }   for i in 0...10 { print(String(format: "%2d maps to...
Give a code snippet in #Swift Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly m...
christopher/rosetta-code
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identif...
#11l
11l
V Δx = 1 Δx++ print(Δx)
Give a code snippet in #11l Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task ...
christopher/rosetta-code
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#C.2B.2B
C++
// Much shorter than the version below; // uses C++11 threads to parallelize the computation; also uses backtracking // Outputs all solutions for any table size #include <vector> #include <iostream> #include <iomanip> #include <thread> #include <future>   // Print table. 'pos' is a vector of positions – the index in po...
Give a code snippet in #C.2B.2B Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element inse...
#Tcl
Tcl
oo::define List { method insertBefore {elem} { $elem next [self] $elem previous $prev if {$prev ne ""} { $prev next $elem } set prev $elem } method insertAfter {elem} { $elem previous [self] $elem next $next if {$next ne ""} { ...
Give a code snippet in #Tcl Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Ele...
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Mathematica.2F.2FWolfram_Language
Mathematica//Wolfram Language
(#*#)& /@ {1, 2, 3, 4} Map[Function[#*#], {1, 2, 3, 4}] Map[((#*#)&,{1,2,3,4}] Map[Function[w,w*w],{1,2,3,4}]
Give a code snippet in #Mathematica.2F.2FWolfram_Language Task Take a combined set of elements and apply a function to each element.
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...
#Perl
Perl
use strict; use warnings; use DateTime;   use constant PI => 2 * atan2(1, 0);   my %cycles = ( 'Physical' => 23, 'Emotional' => 28, 'Mental' => 33 ); my @Q = ( ['up and rising', 'peak'], ['up but falling', 'transition'], ['down and falling', 'valley'], ['down but rising', 'transition...
Give a code snippet in #Perl 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, b...
christopher/rosetta-code
http://rosettacode.org/wiki/Pig_the_dice_game/Player
Pig the dice game/Player
Pig the dice game/Player You are encouraged to solve this task according to the task description, using any language you may know. Task Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy. State here the play strategies involved. Show play dur...
#REXX
REXX
/*REXX program plays "pig the dice game" (any number of CBLFs and/or silicons or HALs).*/ sw= linesize() - 1 /*get the width of the terminal screen,*/ parse arg hp cp win die _ . '(' names ")" /*obtain optional arguments from the CL*/ ...
Give a code snippet in #REXX Pig the dice game/Player You are encouraged to solve this task according to the task description, using any language you may know. Task Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy. State here the play strat...
christopher/rosetta-code
http://rosettacode.org/wiki/Visualize_a_tree
Visualize a tree
A tree structure   (i.e. a rooted, connected acyclic graph)   is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as:   indented text   (à la unix tree command)   nested HTML tables   hierarchical GUI widgets   2D   or ...
#Wren
Wren
import "/dynamic" for Struct import "random" for Random   var Stem = Struct.create("Stem", ["str", "next"])   var SDOWN = " |" var SLAST = " `" var SNONE = " "   var rand = Random.new()   var tree // recursive tree = Fn.new { |root, head| var col = Stem.new(null, null) var tail = head while (tail) { ...
Give a code snippet in #Wren A tree structure   (i.e. a rooted, connected acyclic graph)   is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as:   indented text   (à la unix tree command)   nested HTML tables   hierar...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#Aime
Aime
text s; s = ""; if (length(s) == 0) { ... } if (length(s) != 0) { .... }
Give a code snippet in #Aime Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Othe...
christopher/rosetta-code
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#ERRE
ERRE
  PROGRAM IDENTITY   !$DYNAMIC DIM A[0,0]   BEGIN PRINT(CHR$(12);) ! CLS INPUT("Matrix size",N%)  !$DIM A[N%,N%] FOR I%=1 TO N% DO A[I%,I%]=1 END FOR ! print matrix FOR I%=1 TO N% DO FOR J%=1 TO N% DO WRITE("###";A[I%,J%];) END FOR PRINT END FOR END PROGRAM  
Give a code snippet in #ERRE Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#UNIX_Shell
UNIX Shell
function luhn { typeset n p s t=('0123456789' '0516273849') while ((-n<${#1})); do p="${t[n--%2]%${1:n:1}*}" ((s+=${#p})) done ((s%10)) }   for c in 49927398716 49927398717 1234567812345678 1234567812345670; do if luhn $c; then echo $c is invalid else echo $c is valid fi don...
Give a code snippet in #UNIX_Shell The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the ord...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
If[problem, Abort[]];
Give a code snippet in #Mathematica.2FWolfram_Language Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open...
christopher/rosetta-code
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#Ruby
Ruby
x.abs #absolute value x.magnitude #absolute value x.floor #floor x.ceil #ceiling x ** y #power include Math E #e PI #pi sqrt(x) #square root log(x) #natural logarithm log(x, y) #logarithm base y log10(x) #base 10 logarithm exp(x) #exponential  
Give a code snippet in #Ruby Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "ma...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#C.23
C#
static string ReverseString(string input) { char[] inputChars = input.ToCharArray(); Array.Reverse(inputChars); return new string(inputChars); }
Give a code snippet in #C.23 Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty ...
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...
#Maple
Maple
ChowlaFunction := n -> NumberTheory:-SumOfDivisors(n) - n - 1;   PrintChowla := proc(n::posint) local i; printf("Integer : Chowla Number\n"); for i to n do printf("%d  :  %d\n", i, ChowlaFunction(i)); end do; end proc:   countPrimes := n -> nops([ListTools[SearchAll](0, map(ChowlaFunction, [seq(1 .. n)]))]);   fin...
Give a code snippet in #Maple 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/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#Oberon-2
Oberon-2
  MODULE LoopFor; IMPORT Out; VAR i, j: INTEGER;   BEGIN FOR i := 1 TO 5 DO FOR j := 1 TO i DO Out.Char('*'); END; Out.Ln END END LoopFor.  
Give a code snippet in #Oberon-2 “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract stru...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaysty...
#Swift
Swift
precedencegroup ExponentiationGroup { higherThan: MultiplicationPrecedence }   infix operator ** : ExponentiationGroup   protocol Ring { associatedtype RingType: Numeric   var one: Self { get }   static func +(_ lhs: Self, _ rhs: Self) -> Self static func *(_ lhs: Self, _ rhs: Self) -> Self static func **(_...
Give a code snippet in #Swift Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, t...
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Bracmat
Bracmat
( leap-year = . mod$(!arg.100):0 & `(mod$(!arg.400):0) { The backtick skips the remainder of the OR operation, even if the tested condition fails. } | mod$(!arg.4):0 ) & 1600 1700 1899 1900 2000 2006 2012:?tests & whl ' ( !tests:%?test ?tests & ( le...
Give a code snippet in #Bracmat Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#Ruby
Ruby
size = 4 scores = [] guesses = [] puts "Playing Bulls & Cows with #{size} unique digits." possible_guesses = [*'1'..'9'].permutation(size).to_a.shuffle   loop do guesses << current_guess = possible_guesses.pop print "Guess #{guesses.size} is #{current_guess.join}. Answer (bulls,cows)? " scores << score = gets.spl...
Give a code snippet in #Ruby Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those ...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT year=2012 LOOP month=1,12 LOOP day=31,22,-1 dayofweek=DATE (number,day,month,year,nummer) IF (dayofweek==5) THEN PRINT year,"-",month,"-",day EXIT ENDIF ENDLOOP ENDLOOP  
Give a code snippet in #TUSCRIPT Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2...
christopher/rosetta-code
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#R
R
years <- 2008:2121 xmas <- as.POSIXlt(paste0(years, '/12/25')) years[xmas$wday==0] # 2011 2016 2022 2033 2039 2044 2050 2061 2067 2072 2078 2089 2095 2101 2107 2112 2118   # Also: xmas=seq(as.Date("2008/12/25"), as.Date("2121/12/25"), by="year") as.numeric(format(xmas[weekdays(xmas)== 'Sunday'], "%Y"))   # Still anothe...
Give a code snippet in #R A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008...
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.
#PicoLisp
PicoLisp
(filter '((N) (not (bit? 1 N))) (1 2 3 4 5 6 7 8 9) )
Give a code snippet in #PicoLisp 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/Image_noise
Image noise
Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
#REXX
REXX
/*REXX program times (elapsed) the generation of 100 frames of random black&white image.*/ parse arg sw sd im . /*obtain optional args from the C.L. */ if sw=='' | sw=="," then sw=320 /*SW specified? No, then use default.*/ if sd=='' | sd=="," then sd=240 ...
Give a code snippet in #REXX Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
christopher/rosetta-code
http://rosettacode.org/wiki/Minesweeper_game
Minesweeper game
There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid...
#Tcl
Tcl
package require Tcl 8.5 fconfigure stdout -buffering none   # Set up the grid and fill it with some mines proc makeGrid {n m} { global grid mine unset -nocomplain grid mine set grid(size) [list $n $m] set grid(shown) 0 set grid(marked) 0 for {set j 1} {$j <= $m} {incr j} { for {set i 1} {$i <= ...
Give a code snippet in #Tcl There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordin...
christopher/rosetta-code
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Vedit_macro_language
Vedit macro language
if (Match(".* string$", REGEXP)==0) { Statline_Message("This line ends with 'string'") }
Give a code snippet in #Vedit_macro_language Task   match a string against a regular expression   substitute part of a string using a regular expression
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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 before E except after C Bioinformatics/base count Count occurren...
#Ring
Ring
  # Project : Magic 8-Ball   answers = ["It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Signs point to yes", "Yes", "Reply hazy, try again", "Ask again later", ...
Give a code snippet in #Ring Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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 before E except after C Bioinformat...
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 ...
#Brainf.2A.2A.2A
Brainf***
[.]
Give a code snippet in #Brainf.2A.2A.2A 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#FBSL
FBSL
#DEFINE WM_LBUTTONDOWN 513 #DEFINE WM_CLOSE 16   FBSLSETTEXT(ME, "Bezier Quadratic") FBSLSETFORMCOLOR(ME, RGB(0, 255, 255)) ' Cyan: persistent background color DRAWWIDTH(5) ' Adjust point size FBSL.GETDC(ME) ' Use volatile FBSL.GETDC below to avoid extra assignments   RESIZE(ME, 0, 0, 235, 235) CENTER(ME) SHOW(ME)   DI...
Give a code snippet in #FBSL Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
christopher/rosetta-code
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1
Minimum positive multiple in base 10 using only 0 and 1
Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property. This is simple to do, but can be challenging to do efficiently. To avoid repeating long, unwieldy phrases, the operation "minimum pos...
#Java
Java
  import java.math.BigInteger; import java.util.ArrayList; import java.util.List;   // Title: Minimum positive multiple in base 10 using only 0 and 1   public class MinimumNumberOnlyZeroAndOne {   public static void main(String[] args) { for ( int n : getTestCases() ) { BigInteger result = get...
Give a code snippet in #Java Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property. This is simple to do, but can be challenging to do efficiently. To avoid repeating long, unwieldy phras...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#OCaml
OCaml
open Printf   let csv_data = "\ Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; \ he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mot...
Give a code snippet in #OCaml Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Cr...
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...
#OCaml
OCaml
# 'a';; - : char = 'a'
Give a code snippet in #OCaml 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/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Pike
Pike
string content=Stdio.File("foo.txt")->read();
Give a code snippet in #Pike Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished increm...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_SNUSP
Execute SNUSP
Execute SNUSP is an implementation of SNUSP. Other implementations of SNUSP. RCSNUSP SNUSP An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not...
#Kotlin
Kotlin
// version 1.1.2   // requires 5 chars (10 bytes) of data store const val hw = """ /++++!/===========?\>++.>+.+++++++..+++\ \+++\ | /+>+++++++>/ /++++++++++<<.++>./ $+++/ | \+++++++++>\ \+++++.>.+++.-----\ \==-<<<<+>+++/ /=.>.+>.--------.-/"""   // input is a multi-line string. fun snusp(dlen: Int, raw: String) {...
Give a code snippet in #Kotlin Execute SNUSP is an implementation of SNUSP. Other implementations of SNUSP. RCSNUSP SNUSP An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', an...
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 ...
#Aime
Aime
integer dist(data s, t, integer i, j, list d) { integer x;   x = d[i * (~t + 1) + j]; if (x == -1) { if (i == ~s) { x = ~t - j; } elif (j == ~t) { x = ~s - i; } elif (s[i] == t[j]) { x = dist(s, t, i + 1, j + 1, d); } else { x =...
Give a code snippet in #Aime 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 comp...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Scilab
Scilab
nmax=12, xx=3 s= blanks(xx)+" |" for j=1:nmax s=s+part(blanks(xx)+string(j),$-xx:$) end printf("%s\n",s) s=strncpy("-----",xx)+" +" for j=1:nmax s=s+" "+strncpy("-----",xx) end printf("%s\n",s) for i=1:nmax s=part(blanks(xx)+string(i),$-xx+1:$)+" |" ...
Give a code snippet in #Scilab Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
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.
#Z80_Assembly
Z80 Assembly
MyByte: byte 0 ;most assemblers will also accept DB or DFB MyWord: word 0 ;most assemblers will also accept DW or DFW MyDouble: dd 0
Give a code snippet in #Z80_Assembly Task Demonstrate how to specify the minimum size of a variable or a data type.
christopher/rosetta-code
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Tcl
Tcl
proc nthroot {n A} { expr {pow($A, 1.0/$n)} }
Give a code snippet in #Tcl Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
christopher/rosetta-code
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#6502_Assembly
6502 Assembly
;swap X with Y pha  ;push accumulator txa pha  ;push x tya pha ;push y pla tax ;pop y into x pla tay  ;pop x into y pla  ;pop accumulator
Give a code snippet in #6502_Assembly Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides g...
christopher/rosetta-code
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#Groovy
Groovy
final CELL_VALUES = ('1'..'9')   class GridException extends Exception { GridException(String message) { super(message) } }   def string2grid = { string -> assert string.size() == 81 (0..8).collect { i -> (0..8).collect { j -> string[9*i+j] } } }   def gridRow = { grid, slot -> grid[slot.i] as Set }   def g...
Give a code snippet in #Groovy Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
christopher/rosetta-code
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#BASIC256
BASIC256
onerror TratoError infinity = 1e300*1e300 end   TratoError: if lasterror = 29 then print lasterrormessage return
Give a code snippet in #BASIC256 Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwi...
christopher/rosetta-code
http://rosettacode.org/wiki/Zumkeller_numbers
Zumkeller numbers
Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ...
#11l
11l
F getDivisors(n) V divs = [1, n] V i = 2 L i * i <= n I n % i == 0 divs [+]= i   V j = n I/ i I i != j divs [+]= j i++ R divs   F isPartSum(divs, sum) I sum == 0 R 1B   V le = divs.len I le == 0 R 0B   V last = divs.last [Int] new...
Give a code snippet in #11l Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisor...
christopher/rosetta-code
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and...
#Swift
Swift
import Foundation   let strData = "The quick brown fox jumps over the lazy dog".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) let crc = crc32(uLong(0), UnsafePointer<Bytef>(strData!.bytes), uInt(strData!.length))   println(NSString(format:"%2X", crc))
Give a code snippet in #Swift Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * ...
#Euphoria
Euphoria
procedure triangle(integer x, integer y, integer len, integer n) if n = 0 then position(y,x) puts(1,'*') else triangle (x, y+len, floor(len/2), n-1) triangle (x+len, y, floor(len/2), n-1) triangle (x+len*2, y+len, floor(len/2), n-1) end if end procedure   clear_sc...
Give a code snippet in #Euphoria Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * ...
christopher/rosetta-code
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#Nemerle
Nemerle
using System; using System.Console;   module Hofstadter { F(n : int) : int { |0 => 1 |_ => n - M(F(n - 1)) }   M(n : int) : int { |0 => 0 |_ => n - F(M(n - 1)) }   Main() : void { foreach (n in [0 .. 20]) Write("{0} ", F(n)); WriteLine(); ...
Give a code snippet in #Nemerle Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( ...
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...
#Phixmonti
Phixmonti
def romanDec /# s -- n #/ 0 >ps 0 >ps ( ( "M" 1000 ) ( "D" 500 ) ( "C" 100 ) ( "L" 50 ) ( "X" 10 ) ( "V" 5 ) ( "I" 1 ) )   swap upper reverse len while pop rot rot tochar getd if dup ps> < if 0 swap - endif dup ps> + >ps >ps swap ...
Give a code snippet in #Phixmonti 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,...
christopher/rosetta-code
http://rosettacode.org/wiki/Hilbert_curve
Hilbert curve
Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
#Ada
Ada
with PDF_Out; use PDF_Out;   procedure Hilbert_Curve_PDF is   Length  : constant := 500.0; Corner  : constant Point := (50.0, 300.0);   type Rule_Type is (A, B, C, D);   PDF  : PDF_Out.Pdf_Out_File; First : Boolean;   procedure Hilbert (Order  : in Natural; Rule  : in Rule_Typ...
Give a code snippet in #Ada Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
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...
#M2000_Interpreter
M2000 Interpreter
  Module AmbFunction { Function Amb (failure) { // get an array of s items, return an array of 1 item // we do this so we forget the type of element getitem=lambda (n, c) -> { dim z(1) :link c to c() stock c(n) keep 1, z(0) // copy from c(n)...
Give a code snippet in #M2000_Interpreter 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 fini...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#Inform_7
Inform 7
Hallway is a room.   A toggle door is a kind of thing. A toggle door can be open or closed. It is usually closed. A toggle door has a number called the door number. Understand the door number property as referring to a toggle door. Rule for printing the name of a toggle door: say "door #[door number]".   There are 100 ...
Give a code snippet in #Inform_7 There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6,...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#AutoHotkey
AutoHotkey
NauticalBell(hh, mm){ Hr := 0, min := 30, Bells := [], pattern := [] Loop 8 ; genrate 8 patterns { num := A_Index , code := "" while (num/2 >=1) code .= "** ", num := num-2 code .= mod(A_Index, 2) ? "*" : "" pattern[A_Index] := code } loop, 48 ; 24 hours * 2 for every half an hour {...
Give a code snippet in #AutoHotkey 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's eval...
#Frink
Frink
println["5^3^2 = " + 5^3^2] println["(5^3)^2 = " + (5^3)^2] println["5^(3^2) = " + 5^(3^2)]  
Give a code snippet in #Frink This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show ...
christopher/rosetta-code