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/Kosaraju
Kosaraju
This page uses content from Wikipedia. The original article was at Graph. 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) Kosaraju's algorithm (also known as the Kosaraju–Sharir algorithm) is a lin...
#11l
11l
F kosaraju(g) V size = g.len V vis = [0B] * size V l = [0] * size V x = size V t = [[Int]()] * size   F visit(Int u) -> N I !@vis[u] @vis[u] = 1B L(v) @g[u] @visit(v) @t[v] [+]= u @x-- @l[@x] = u   L(u) 0 .< g.len visit(u) V...
Give a code snippet in #11l This page uses content from Wikipedia. The original article was at Graph. 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) Kosaraju's algorithm (also known as the Kosara...
christopher/rosetta-code
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes
Partition an integer x into n primes
Task Partition a positive integer   X   into   N   distinct primes. Or, to put it in another way: Find   N   unique primes such that they add up to   X. Show in the output section the sum   X   and the   N   primes in ascending order separated by plus (+) signs: •   partition 99809 with 1 prime. ...
#Phix
Phix
with javascript_semantics requires("1.0.2") -- (join(fmt)) function partition(integer v, n, idx=0) if n=1 then return iff(is_prime(v)?{v}:0) end if while true do idx += 1 integer np = get_prime(idx) if np>=floor(v/2) then exit end if object res = partition(v-np, n-1, ...
Give a code snippet in #Phix Task Partition a positive integer   X   into   N   distinct primes. Or, to put it in another way: Find   N   unique primes such that they add up to   X. Show in the output section the sum   X   and the   N   primes in ascending order separated by plus (+) signs: •   partitio...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#Scheme
Scheme
(define (guess) (define number (random 11)) (display "Pick a number from 1 through 10.\n> ") (do ((guess (read) (read))) ((= guess number) (display "Well guessed!\n")) (display "Guess again.\n")))
Give a code snippet in #Scheme Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a ...
christopher/rosetta-code
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Lua
Lua
require "lfs" local attributes = lfs.attributes("input.txt") if attributes then print(path .. " was last modified " .. os.date("%c", attributes.modification) .. ".")   -- set access and modification time to now ... lfs.touch("input.txt")   -- ... or set modification time to now, keep original access tim...
Give a code snippet in #Lua Task Get and set the modification time of a file.
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...
#REBOL
REBOL
rebol [ Title: "Trigonometric Functions" URL: http://rosettacode.org/wiki/Trigonometric_Functions ]   radians: pi / 4 degrees: 45.0   ; Unlike most languages, REBOL's trig functions work in degrees unless ; you specify differently.   print [sine/radians radians sine degrees] print [cosine/radians radians cosin...
Give a code snippet in #REBOL 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 evalu...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. 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 l...
#M4
M4
define(`spam',`SPAM spam') spam
Give a code snippet in #M4 Task Print out       SPAM       followed by a   newline   in an infinite loop. 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/I...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Prolog
Prolog
% SWI-Prolog version 8.0.0 for i686-linux. % This will find itself, and return the knowledge base it is in. file_name(F) :- true , M = user % M is the module . , P = file_name(_) % P is the predicate . , source_file(M:P, F) % F is the file . , \+ predicate_property(M:P, imported_from(_...
Give a code snippet in #Prolog The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script...
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.
#Zig
Zig
pub fn main() !void { var array = [_]i32{1, 2, 3}; apply(@TypeOf(array[0]), array[0..], func); }   fn apply(comptime T: type, a: []T, f: fn(T) void) void { for (a) |item| { f(item); } }   fn func(a: i32) void { const std = @import("std"); std.debug.print("{d}\n", .{a-1}); }
Give a code snippet in #Zig Task Take a combined set of elements and apply a function to each element.
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 ...
#Smalltalk
Smalltalk
isPalindrome := [:aString | str := (aString select: [:chr| chr isAlphaNumeric]) collect: [:chr | chr asLowercase]. str = str reversed. ].  
Give a code snippet in #Smalltalk 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/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...
#J
J
row0=: u: 9812+2}.5|i.10 king=: u:9812 rook=: u:9814 bish=: u:9815 pos=: I.@e. bishok=: 1=2+/ .| pos&bish rookok=: pos&rook -: (<./,>./)@pos&(rook,king) ok=: bishok*rookok perm=: A.&i.~ ! valid=: (#~ ok"1) ~.row0{"1~perm 8 gen=: valid {~ ? bind 960
Give a code snippet in #J 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 pl...
christopher/rosetta-code
http://rosettacode.org/wiki/Plasma_effect
Plasma effect
The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid. Task Create a plasma effect. See also Computer Graphics Tutorial (lod...
#Phix
Phix
-- demo\rosetta\plasma.exw include pGUI.e   Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas   sequence plasma integer pw = 0, ph = 0   procedure createPlasma(integer w, h) plasma = repeat(repeat(0,w),h) for y=1 to h do for x=1 to w do atom v = sin(x/16) v += sin(y/8) ...
Give a code snippet in #Phix The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid. Task Create a plasma effect. See also C...
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 ...
#Vlang
Vlang
if boolean_expression { statements }
Give a code snippet in #Vlang 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/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
socket = SocketConnect["localhost:256", "TCP"]; WriteString[socket, "hello socket world"]; Close[socket];
Give a code snippet in #Mathematica.2FWolfram_Language For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
christopher/rosetta-code
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Arturo
Arturo
found: 0 i: 1 maxDiv: 0   while [found<20][ fac: size factors i if fac > maxDiv [ print i maxDiv: fac found: found + 1 ] i: i + 1 ]
Give a code snippet in #Arturo The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
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...
#Phix
Phix
with javascript_semantics constant N = 6, limit = power(10,N) -- standard sieve: enum L,R -- (with primes[i] as mini bit-field) sequence primes = repeat(L+R, limit) primes[1] = 0 for i=2 to floor(sqrt(limit)) do if primes[i] then for k=i*i to limit by i do primes[k] = 0 end for end ...
Give a code snippet in #Phix 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-truncatabl...
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...
#CLU
CLU
alph = proc () returns (string) a: int := char$c2i('a') letters: array[char] := array[char]$predict(1,26) for i: int in int$from_to(0, 25) do array[char]$addh(letters, char$i2c(a + i)) end return(string$ac2s(letters)) end alph   % test start_up = proc () stream$putl(stream$primary_output...
Give a code snippet in #CLU 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 re...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions:...
#PHP
PHP
<?php function brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) { do { switch($s[$_s]) { case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break; case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break; case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break; case '<': $_d--; break; ...
Give a code snippet in #PHP Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implemen...
christopher/rosetta-code
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also ...
#AWK
AWK
  # syntax: GAWK -f SMARANDACHE_PRIME-DIGITAL_SEQUENCE.AWK BEGIN { limit = 25 printf("1-%d:",limit) while (1) { if (is_prime(++n)) { if (all_digits_prime(n) == 1) { if (++count <= limit) { printf(" %d",n) } if (count == 100) { printf("\n%d:...
Give a code snippet in #AWK The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundre...
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...
#JavaScript
JavaScript
Julia Operators in Order of Preference -------------------------------------------- Syntax . followed by :: Exponentiation ^ Fractions // Multiplication * / % & \ Bitshifts << >> >>> Addition + - | ⊻ Syntax : .. followed by |> Comparisons > < >= <= == === != !== <: Control flow && followed by || fo...
Give a code snippet in #JavaScript 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 o...
christopher/rosetta-code
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#Fortran
Fortran
Program Compass implicit none   integer :: i, ind real :: heading   do i = 0, 32 heading = i * 11.25 if (mod(i, 3) == 1) then heading = heading + 5.62 else if (mod(i, 3) == 2) then heading = heading - 5.62 end if ind = mod(i, 32) + 1 write(*, "(i2, a20, f8.2)") ind, com...
Give a code snippet in #Fortran There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#Nyquist
Nyquist
(defun factorial (n) (do ((x n (* x n))) ((= n 1) x) (setq n (1- n))))
Give a code snippet in #Nyquist Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
Sorting algorithms/Pancake 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 ...
#Ada
Ada
with Ada.Text_IO; procedure Pancake_Sort is generic type Element_Type is private; type Index_Type is range <>; type Array_Type is array (Index_Type range <>) of Element_Type; with function ">" (Left, Right : Element_Type) return Boolean is <>; procedure Pancake_Sort (Data: in out Array_Typ...
Give a code snippet in #Ada 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Make_directory_path
Make directory path
Task Create a directory and any missing parents. This task is named after the posix mkdir -p command, and several libraries which implement the same behavior. Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect. If the directory already exists, return succe...
#FreeBASIC
FreeBASIC
#ifdef __FB_WIN32__ Dim pathname As String = "Ring\docs" #else Dim pathname As String = "Ring/docs" #endif   Dim As String mkpathname = "mkdir " & pathname Dim result As Long = Shell (mkpathname)   If result = 0 Then Print "Created the directory..." Chdir(pathname) Print Curdir Else Print "error...
Give a code snippet in #FreeBASIC Task Create a directory and any missing parents. This task is named after the posix mkdir -p command, and several libraries which implement the same behavior. Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect. If the dir...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. 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 l...
#SNUSP
SNUSP
@\>@\>@\>@\>++++++++++===!/ < < < < \ | | | \M=@@@@+@+++++# \.>.>.>.>./ | | \A=@@+@@@@+++# | \P=@@+@@+@@+++# \S=@@+@+@@@+++#
Give a code snippet in #SNUSP Task Print out       SPAM       followed by a   newline   in an infinite loop. 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   Loop...
christopher/rosetta-code
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#ColdFusion
ColdFusion
  <!--- Create sample JSON structure ---> <cfset json = { string: "Hello", number: 42, arrayOfNumbers: [1, 2, 3, 4], arrayOfStrings: ["One", "Two", "Three", "Four"], arrayOfAnything: [1, "One", [1, "One"], { one: 1 }], object: { key: "value" } } />   <!--- Convert to JSON string ---> <cfset jsonSerial...
Give a code snippet in #ColdFusion Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
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...
#XBS
XBS
#> Vector3 Class <# class Vector3 { construct=func(self,x,y,z){ self:x=x; self:y=y; self:z=z; }; ToString=func(self){ send self.x+", "+self.y+", "+self.z; }; Magnitude=func(self){ send math.sqrt((self.x^2)+(self.y^2)+(self.z^2)); }; Normalize=func(self){ set Mag = self::Magnitude(); send new Vector...
Give a code snippet in #XBS 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 numb...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#Raku
Raku
sub prime (Int $i --> Bool) { $i > 1 and so $i %% none 2..$i.sqrt; }
Give a code snippet in #Raku Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops ...
christopher/rosetta-code
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#F.23
F#
open System.Windows.Forms open System.Runtime.InteropServices   #nowarn "9" [<Struct; StructLayout(LayoutKind.Sequential)>] type POINT = new (x, y) = { X = x; Y = y } val X : int val Y : int   [<DllImport("user32.dll")>] extern nativeint GetForegroundWindow(); [<DllImport("user32.dll", CharSet=CharSet.Auto,...
Give a code snippet in #F.23 Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Groovy
Groovy
println ([2,4,0,3,1,2,-12].max())
Give a code snippet in #Groovy Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Jsish
Jsish
/* Arrays in Jsi */ // Create a new array with length 0 var myArray = new Array(); ;myArray;   // In Jsi, typeof [] is "array". In ECMAScript, typeof [] is "object" ;typeof [];   // Create a new array with length 5 var myArray1 = new Array(5); ;myArray1;   // Create an array with 2 members (length is 2) var myArray2 ...
Give a code snippet in #Jsish This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retri...
christopher/rosetta-code
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#Fantom
Fantom
class MyClass { // an instance variable Int x   // a constructor, providing default value for instance variable new make (Int x := 1) { this.x = x }   // a method, return double the number x public Int double () { return 2 * x } }   class Main { public static Void main () { a := MyCl...
Give a code snippet in #Fantom In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the cl...
christopher/rosetta-code
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#Nim
Nim
const C = block useless: 3
Give a code snippet in #Nim Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use
Text processing/Max licenses in use
A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a checkout event when a copy of the ...
#Perl
Perl
#!/usr/bin/perl -w use strict;   my $out = 0; my $max_out = -1; my @max_times;   open FH, '<mlijobs.txt' or die "Can't open file: $!"; while (<FH>) { chomp; if (/OUT/) { $out++; } else { $out--; } if ($out > $max_out) { $max_out = $out; @max_times = (); } if (...
Give a code snippet in #Perl A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a chec...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#Euphoria
Euphoria
function gcd_iter(integer u, integer v) integer t while v do t = u u = v v = remainder(t, v) end while if u < 0 then return -u else return u end if end function
Give a code snippet in #Euphoria Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   great...
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...
#Red
Red
  primes: function [n [integer!]][ poke prim: make bitset! n 1 true r: 2 while [r * r <= n][ repeat q n / r - 1 [poke prim q + 1 * r true] until [not pick prim r: r + 1] ] collect [repeat i n [if not prim/:i [keep i]]] ]   primes 100 == [2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 7...
Give a code snippet in #Red 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   alg...
christopher/rosetta-code
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function shou...
#PHP
PHP
$fh = tmpfile(); // do stuff with $fh fclose($fh); // file removed when closed   // or: $filename = tempnam('/tmp', 'prefix'); echo "$filename\n"; // open $filename and do stuff with it
Give a code snippet in #PHP Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" ...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_syntax
Inverted syntax
Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the statement or code block: needumb...
#Sidef
Sidef
# Inverted syntax with assignment var raining = true; [false]»(\var needumbrella);   # Inverted syntax with conditional expressions if (raining==true) {needumbrella=true}; {needumbrella=true} -> if (raining==true); (needumbrella=true) if (raining==true);
Give a code snippet in #Sidef Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the sta...
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...
#Phix
Phix
with javascript_semantics function randN(integer N) return rand(N) = 1 end function function unbiased(integer N) while true do integer a = randN(N) if a!=randN(N) then return a end if end while end function constant n = 100000 for b=3 to 6 do integer cb = 0, ...
Give a code snippet in #Phix 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 t...
christopher/rosetta-code
http://rosettacode.org/wiki/Faulhaber%27s_formula
Faulhaber's formula
In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expressions, starting with p = 0. R...
#J
J
Bsecond=:verb define"0 +/,(<:*(_1^[)*!*(y^~1+[)%1+])"0/~i.1x+y )   Bfirst=: Bsecond - 1&=   Faul=:adverb define (0,|.(%m+1x) * (_1x&^ * !&(m+1) * Bfirst) i.1+m)&p. )
Give a code snippet in #J In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expressions...
christopher/rosetta-code
http://rosettacode.org/wiki/Optional_parameters
Optional parameters
Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicographic by default. column ...
#Unix_Shell
Unix Shell
#!/usr/bin/env bash # sort-args.sh   data() { cat <<EOF 123 456 0789 456 0789 123 0789 123 456 EOF }   # sort_table [column NUM | KIND | reverse] ... <INPUT >OUTPUT # KIND = lexicographical | numeric | human   sort_table() { local opts='-b' local column=1 while (( $# > 0 )) ; do case "$1" in ...
Give a code snippet in #Unix_Shell Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#elastiC
elastiC
package hello;   // Import the `basic' package import basic;   // Define a simple function function hello() { // Print hello world basic.print( "Hello world!\n" ); }   /* * Here we start to execute package code */   // Invoke the `hello' function hello();
Give a code snippet in #elastiC Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error...
christopher/rosetta-code
http://rosettacode.org/wiki/Play_recorded_sounds
Play recorded sounds
Load at least two prerecorded sounds, and demonstrate as many of these features as you can: playing them individually and simultaneously stopping before the end of the sound looping (preferably glitch-free) setting the volume of each sound stereo or 3D positional mixing performing other actions when marked times...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
a = Import["sound1.flac","FLAC"]; b = Import["sound2.flac","FLAC"];   ListPlay[a, {t, 0, 10}]; ListPlay[b, {t, 0, 10}];   ListPlay[{a,b}, {t, 0, 10}];   Stopping before the end can be done using the GUI or by reducing the parameter range of the ListPlay function.   While[True,ListPlay[{a,b}, {t, 0, 10}];]   ListPlay[{...
Give a code snippet in #Mathematica.2FWolfram_Language Load at least two prerecorded sounds, and demonstrate as many of these features as you can: playing them individually and simultaneously stopping before the end of the sound looping (preferably glitch-free) setting the volume of each sound stereo or 3D posit...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#ERRE
ERRE
  PROGRAM 24SOLVE   LABEL 98,99,2540,2550,2560   ! possible brackets CONST NBRACKETS=11,ST_CONST$="+-*/^("   DIM D[4],PERM[24,4] DIM BRAKETS$[NBRACKETS] DIM OP$[3] DIM STACK$[50]   PROCEDURE COMPATTA_STACK IF NS>1 THEN R=1 WHILE R<NS DO IF INSTR(ST_CONST$,STACK$[R])=0 AND INSTR(ST_CONST$,STACK$[...
Give a code snippet in #ERRE task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/PPM_conversion_through_a_pipe
Bitmap/PPM conversion through a pipe
Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page. There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpeg (package "netpbm" on Linux)...
#Tcl
Tcl
package require Tk   proc output_jpeg {image filename {quality 75}} { set f [open |[list convert ppm:- -quality $quality jpg:- > $filename] w] fconfigure $f -translation binary puts -nonewline $f [$image data -format ppm] close $f }
Give a code snippet in #Tcl Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page. There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpe...
christopher/rosetta-code
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that...
#ALGOL_68
ALGOL 68
BEGIN # compute some Egytian fractions # PR precision 2000 PR # set the number of digits for LONG LONG INT # PROC gcd = ( LONG LONG INT a, b )LONG LONG INT: IF b = 0 THEN IF a < 0 THEN - a ELSE a FI ELSE gcd( b, a MO...
Give a code snippet in #ALGOL_68 An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task...
#C.2B.2B
C++
#include <algorithm> #include <chrono> #include <iostream> #include <random> #include <vector>   template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend();   os << '['; if (it != end) { os << *it; it = std::next(...
Give a code snippet in #C.2B.2B A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2...
christopher/rosetta-code
http://rosettacode.org/wiki/One_of_n_lines_in_a_file
One of n lines in a file
A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of the file if possible and m...
#Liberty_BASIC
Liberty BASIC
  DIM chosen(10)   FOR i = 1 TO 10000'00 c = oneofN(10) chosen(c) = chosen(c) + 1 NEXT   FOR i = 1 TO 10 PRINT i, chosen(i) NEXT   end   FUNCTION oneofN(n) FOR i = 1 TO n IF RND(1) < 1/i THEN oneofN = i NEXT END FUNCTION  
Give a code snippet in #Liberty_BASIC A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the se...
christopher/rosetta-code
http://rosettacode.org/wiki/Barnsley_fern
Barnsley fern
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ƒ2   (chosen 85% of the time) ...
#Sidef
Sidef
require('Imager')   var w = 640 var h = 640   var img = %O<Imager>.new(xsize => w, ysize => h, channels => 3) var green = %O<Imager::Color>.new('#00FF00')   var (x, y) = (0.float, 0.float)   1e5.times { var r = 100.rand (x, y) = ( if (r <= 1) { ( 0.00*x - 0.00*y, 0.00*x + 0.16*y + 0.00) } elsif (r <=...
Give a code snippet in #Sidef A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; procedure Main is begin Put_Line ("Hello world!"); end Main;
Give a code snippet in #Ada Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#Ruby
Ruby
require 'file'
Give a code snippet in #Ruby Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/Concurrent_computing
Concurrent computing
Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
#C.23
C#
  static Random tRand = new Random();   static void Main(string[] args) { Thread t = new Thread(new ParameterizedThreadStart(WriteText)); t.Start("Enjoy");   t = new Thread(new ParameterizedThreadStart(WriteText)); t.Start("Rosetta");   t = new Thread(new ParameterizedThreadStart(WriteText)); t.Start("Code");   ...
Give a code snippet in #C.23 Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your la...
christopher/rosetta-code
http://rosettacode.org/wiki/Percolation/Bond_percolation
Percolation/Bond percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N...
#Swift
Swift
let randMax = 32767.0 let filled = 1 let rightWall = 2 let bottomWall = 4   final class Percolate { let height: Int let width: Int   private var grid: [Int] private var end: Int   init(height: Int, width: Int) { self.height = height self.width = width self.end = width self.grid = [Int](repeat...
Give a code snippet in #Swift Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean clus...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#CMake
CMake
set(string "1599") math(EXPR string "${string} + 1") message(STATUS "${string}")
Give a code snippet in #CMake Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro...
#PARI.2FGP
PARI/GP
shortestPath(G, startAt=1)={ my(n=#G[,1],dist=vector(n,i,9e99),prev=dist,Q=2^n-1); dist[startAt]=0; while(Q, my(t=vecmin(vecextract(dist,Q)),u); if(t==9e99, break); for(i=1,#v,if(dist[i]==t && bittest(Q,i-1), u=i; break)); Q-=1<<(u-1); for(i=1,n, if(!G[u,i],next); my(alt=dist[u]+G[u,i]); if (alt <...
Give a code snippet in #PARI.2FGP This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves ...
christopher/rosetta-code
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#TXR
TXR
@(next :args) @(collect) @arg @(end) @(output) My args are: {@(rep)@arg, @(last)@arg@(end)} @(end)
Give a code snippet in #TXR Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
christopher/rosetta-code
http://rosettacode.org/wiki/Holidays_related_to_Easter
Holidays related to Easter
Task Calculate the dates of:   Easter   Ascension Thursday   Pentecost   Trinity Sunday   Corpus Christi feast (for Catholic)   All Saints' Sunday (for Orthodox) As an example, calculate for the first year of each century from;   years     400   to   2100 CE   and for   years   2010   to   2020 CE. Note ...
#Tcl
Tcl
package require Tcl 8.5; # Advanced date handling engine   # Easter computation code from http://www.assa.org.au/edm.html proc EasterDate year { set FirstDig [expr {$year / 100}] set Remain19 [expr {$year % 19}]   # calculate Paschal Full Moon date set temp [expr {($FirstDig - 15)/2 + 202 - 11*$Remain19...
Give a code snippet in #Tcl Task Calculate the dates of:   Easter   Ascension Thursday   Pentecost   Trinity Sunday   Corpus Christi feast (for Catholic)   All Saints' Sunday (for Orthodox) As an example, calculate for the first year of each century from;   years     400   to   2100 CE   and for   years ...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Ring
Ring
  fp = fopen("C:\Ring\ReadMe.txt","r") n = 0   r = "" while isstring(r) while n < 8 r = fgetc(fp) if r = char(10) n++ see nl else see r ok end end fclose(fp)  
Give a code snippet in #Ring Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitcoin/address_validation
Bitcoin/address validation
Bitcoin/address validation You are encouraged to solve this task according to the task description, using any language you may know. Task Write a program that takes a bitcoin address as argument, and checks whether or not this address is valid. A bitcoin address uses a base58 encoding, which uses an alphabet of th...
#Rust
Rust
  extern crate crypto;   use crypto::digest::Digest; use crypto::sha2::Sha256;   const DIGITS58: [char; 58] = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',...
Give a code snippet in #Rust Bitcoin/address validation You are encouraged to solve this task according to the task description, using any language you may know. Task Write a program that takes a bitcoin address as argument, and checks whether or not this address is valid. A bitcoin address uses a base58 encoding...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#EGL
EGL
s string = "12345"; s = 1 + s; // Note: s + 1 is a string concatenation.
Give a code snippet in #EGL Task Increment a numerical string.
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...
#J
J
amean=: +/ % # gmean=: # %: */ hmean=: amean&.:%
Give a code snippet in #J 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 ,...
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 ...
#F.23
F#
let Spiral n = let sq = Array2D.create n n 0 // Set up an output array let nCur = ref -1 // Current value being inserted let NextN() = nCur := (!nCur+1) ; !nCur // Inc current value and return new value ...
Give a code snippet in #F.23 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#Go
Go
  package main   import "fmt"   func printTriangle(n int) { // degenerate cases if n <= 0 { return } fmt.Println(1) if n == 1 { return } // iterate over rows, zero based a := make([]int, (n+1)/2) a[0] = 1 for row, middle := 1, 0; row < n; row++ { // genera...
Give a code snippet in #Go Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 ...
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...
#Perl
Perl
sub sieve { my $n = shift; my @composite; for my $i (2 .. int(sqrt($n))) { if (!$composite[$i]) { for (my $j = $i*$i; $j <= $n; $j += $i) { $composite[$j] = 1; } } } my @primes; for my $i (2 .. $n) { $composite[$i] || push @primes, $i; } @primes; }
Give a code snippet in #Perl This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   al...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#Monicelli
Monicelli
  stuzzica ... # loop body e brematura anche, se <expr> # exit if <expr> is false  
Give a code snippet in #Monicelli 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   Loo...
christopher/rosetta-code
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#ALGOL_68
ALGOL 68
BEGIN # DISCORDIAN DATE CALCULATION - TRANSLATION OF MAD VIA ALGOL W # INT greg, gmonth, gday, gyear; []STRING holys = []STRING( "MUNG", "MOJO", "SYA", "ZARA", "MALA" )[ AT 0 ]; []STRING holys0 = []STRING( "CHAO", "DISCO", "CONFU", "BURE", "AF" )[ AT 0 ]; []STRING disday = []STRING( "SWE...
Give a code snippet in #ALGOL_68 Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_macros
Keyboard macros
Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { \\ Scan statement exist from version 1 \\ We can make targets and use function keys, in console \\ Scan track mouse click on targets and functions keys state \\ when any of these selected then a call to a global module happen \\ show$(hide$("&8%", "master",3), "code1", 1...
Give a code snippet in #M2000_Interpreter Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
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
#Haskell
Haskell
foobar = 15   f x = x + foobar where foobar = 15   f x = let foobar = 15 in x + foobar   f x = do let foobar = 15 return $ x + foobar
Give a code snippet in #Haskell 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/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decompositi...
#MATLAB_.2F_Octave
MATLAB / Octave
A = [12 -51 4 6 167 -68 -4 24 -41]; [Q,R]=qr(A)
Give a code snippet in #MATLAB_.2F_Octave Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mat...
christopher/rosetta-code
http://rosettacode.org/wiki/The_Name_Game
The Name Game
Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game". The regular verse Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules. The verse for the name 'Gary' would be like this: Gary, Gary, bo-bary...
#ALGOL_68
ALGOL 68
  main:( PROC print lyrics = (STRING name) VOID: BEGIN PROC change name = (STRING name, CHAR initial) STRING: BEGIN CHAR lower first = to lower(name[1]); IF char in string(lower first, NIL, "aeiou") THEN lower first + name[2:] ELIF lower first = initial THEN...
Give a code snippet in #ALGOL_68 Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game". The regular verse Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules. The verse for the name 'Gary' would be ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#SPL
SPL
t = #.str(5^(4^(3^2))) n = #.size(t) #.output(n," digits") #.output(#.mid(t,1,20),"...",#.mid(t,n-19,20))
Give a code snippet in #SPL Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#Raku
Raku
use MONKEY-SEE-NO-EVAL;   say "Here are your digits: ", constant @digits = (1..9).roll(4)».Str;   grammar Exp24 { token TOP { ^ <exp> $ { fail unless EVAL($/) == 24 } } rule exp { <term>+ % <op> } rule term { '(' <exp> ')' | <@digits> } token op { < + - * / > } }   while my $exp = prompt "\n24? " { ...
Give a code snippet in #Raku The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four dig...
christopher/rosetta-code
http://rosettacode.org/wiki/Hostname
Hostname
Task Find the name of the host on which the routine is running.
#K
K
  _h  
Give a code snippet in #K Task Find the name of the host on which the routine is running.
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
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 |...
#Ol
Ol
  (define a 8) (define b 12)   (print "(+ " a " " b ") => " (+ a b)) (print "(- " a " " b ") => " (- a b)) (print "(* " a " " b ") => " (* a b)) (print "(/ " a " " b ") => " (/ a b))   (print "(quotient " a " " b ") => " (quot a b)) ; same as (quotient a b) (print "(remainder " a " " b ") => " (rem a b)) ...
Give a code snippet in #Ol 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 Con...
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'...
#Phix
Phix
with javascript_semantics constant nMax = iff(platform()=JS?8:12) -- Aside: on desktop/Phix, strings can be modified in situ, whereas -- JavaScript strings are immutable, and the equivalent code -- in p2js.js ends up doing excessive splitting and splicing -- hence nMax has to be significantly smal...
Give a code snippet in #Phix 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/Long_year
Long year
Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
#Go
Go
package main   import ( "fmt" "time" )   func main() { centuries := []string{"20th", "21st", "22nd"} starts := []int{1900, 2000, 2100} for i := 0; i < len(centuries); i++ { var longYears []int fmt.Printf("\nLong years in the %s century:\n", centuries[i]) for j := starts[i]; ...
Give a code snippet in #Go Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
christopher/rosetta-code
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number...
#Go
Go
package main   import "fmt"   func mcnugget(limit int) { sv := make([]bool, limit+1) // all false by default for s := 0; s <= limit; s += 6 { for n := s; n <= limit; n += 9 { for t := n; t <= limit; t += 20 { sv[t] = true } } } for i := limit; i >=...
Give a code snippet in #Go Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugge...
christopher/rosetta-code
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#Scala
Scala
object BitmapOps { def luminosity(c:Color)=(0.2126*c.getRed + 0.7152*c.getGreen + 0.0722*c.getBlue+0.5).toInt   def grayscale(bm:RgbBitmap)={ val image=new RgbBitmap(bm.width, bm.height) for(x <- 0 until bm.width; y <- 0 until bm.height; l=luminosity(bm.getPixel(x,y))) image.setPixel(x, y, ne...
Give a code snippet in #Scala Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion....
christopher/rosetta-code
http://rosettacode.org/wiki/JortSort
JortSort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#AppleScript
AppleScript
use AppleScript version "2.4" use framework "Foundation" use scripting additions     ------------------------- JORTSORT -------------------------     -- jortSort :: Ord a => [a] -> Bool on jortSort(xs) xs = sort(xs) end jortSort     --------------------------- TEST --------------------------- on run map(jortSor...
Give a code snippet in #AppleScript 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 | Qu...
christopher/rosetta-code
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#Oz
Oz
P = point(x:1 y:2)
Give a code snippet in #Oz Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Rela...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle Sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Quackery
Quackery
[ dup size 2 < iff [ drop true ] done true swap dup [] != if [ behead swap witheach [ tuck > if [ dip not conclude ] ] ] drop ] is sorted ( [ --> b )   [ behead swap witheach [ 2dup < iff nip else drop ] ] is largest ...
Give a code snippet in #Quackery 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/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Genyris
Genyris
defvar (intern 'This is not a pipe.') 42 define |<weird>| 2009
Give a code snippet in #Genyris Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
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...
#Metafont
Metafont
a := 0; forever: show a; a := a + 1; exitif a mod 6 = 0; endfor end
Give a code snippet in #Metafont 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   Loop...
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...
#Axe
Axe
Returnʳ
Give a code snippet in #Axe 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/d...
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 ...
#Oforth
Oforth
Object Class new: Delegate1   Object Class new: Delegate2 Delegate2 method: thing "Delegate implementation" println ;   Object Class new: Delegator(delegate) Delegator method: initialize  := delegate ;   Delegator method: operation @delegate respondTo(#thing) ifTrue: [ @delegate thing return ] "Default implement...
Give a code snippet in #Oforth 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-256_Merkle_tree
SHA-256 Merkle tree
As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256. Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are pai...
#Delphi
Delphi
  program SHA256_Merkle_tree;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Classes, DCPsha256;   function SHA256(const Input: TArray<Byte>; Len: Integer = -1): TArray<Byte>; var Hasher: TDCP_sha256; l: Integer; begin if Len < 0 then l := length(Input) else l := Len;   Hasher := TDCP_sha25...
Give a code snippet in #Delphi As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256. Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hash...
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 .
#TI-83_BASIC
TI-83 BASIC
PROGRAM:MANDELBR :Input "ITER. ",D :For(A,Xmin,Xmax,ΔX) :For(B,Ymin,Ymax,ΔY) :0→X :0→Y :0→I :D→M :While X^2+Y^2≤4 and I<M :X^2-Y^2+A→R :2XY+B→Y :R→X :I+1→I :End :If I≠M :Then :I→C :Else :0→C :End :If C<1 :Pt-On(A,B) :End :End :End  
Give a code snippet in #TI-83_BASIC 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/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#Erlang
Erlang
-module(anagrams). -compile(export_all).   play() -> {ok, P} = file:read_file('unixdict.txt'), D = dict:new(), E=fetch(string:tokens(binary_to_list(P), "\n"), D), get_value(dict:fetch_keys(E), E).   fetch([H|T], D) -> fetch(T, dict:append(lists:sort(H), H, D)); fetch([], D) -> D.   get_value(L, ...
Give a code snippet in #Erlang When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in ...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Sidef
Sidef
say 1.rand # random float in the interval [0,1) say 100.irand # random integer in the interval [0,100)
Give a code snippet in #Sidef The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorith...
christopher/rosetta-code
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a function to find the closest two p...
#Perl
Perl
use strict; use warnings; use POSIX qw(ceil);   sub dist { my ($a, $b) = @_; return sqrt(($a->[0] - $b->[0])**2 + ($a->[1] - $b->[1])**2) }   sub closest_pair_simple { my @points = @{ shift @_ }; my ($a, $b, $d) = ( $points[0], $points[1], dist($points[0], $points[1]) ); while( @points ...
Give a code snippet in #Perl This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a func...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#Order
Order
#include <order/interpreter.h>   #define ORDER_PP_DEF_8fac \ ORDER_PP_FN(8fn(8N, \ 8if(8less_eq(8N, 0), \ 1, \ 8mul(8N, 8fac(8dec(8N))))))   ORDER_PP(8to_lit(8fac(8))) // 40320
Give a code snippet in #Order Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a n...
christopher/rosetta-code
http://rosettacode.org/wiki/Halt_and_catch_fire
Halt and catch fire
Task Create a program that crashes as soon as possible, with as few lines of code as possible. Be smart and don't damage your computer, ok? The code should be syntactically valid. It should be possible to insert [a subset of] your submission into another program, presumably to help debug it, or perhaps for use when an...
#REXX
REXX
_=1;_+=
Give a code snippet in #REXX Task Create a program that crashes as soon as possible, with as few lines of code as possible. Be smart and don't damage your computer, ok? The code should be syntactically valid. It should be possible to insert [a subset of] your submission into another program, presumably to help debug ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. 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 l...
#Batch_File
Batch File
@echo off :loop echo SPAM goto loop
Give a code snippet in #Batch_File Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#ALGOL_68
ALGOL 68
# returns original phrase with the order of the words reversed # # a word is a sequence of non-blank characters # PROC reverse word order = ( STRING original phrase )STRING: BEGIN STRING words reversed := ""; STRING separator := ""; INT start pos := LWB original...
Give a code snippet in #ALGOL_68 Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by s...
christopher/rosetta-code
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call
Respond to an unknown method call
Task Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions. Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin...
#Elena
Elena
import extensions;   class Example { generic() { // __received is an built-in variable containing the incoming message name console.printLine(__received," was invoked") }   generic(x) { console.printLine(__received,"(",x,") was invoked") }   generic(x,y) { ...
Give a code snippet in #Elena Task Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions. Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point ...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#68000_Assembly
68000 Assembly
isPrime: ; REG USAGE: ; D0 = input (unsigned 32-bit integer) ; D1 = temp storage for D0 ; D2 = candidates for possible factors ; D3 = temp storage for quotient/remainder ; D4 = total count of proper divisors.   MOVEM.L D1-D4,-(SP) ;push data regs except D0 MOVE.L #0,D1 MOVEM.L D1,D2-D4 ;clear regs D1 thru ...
Give a code snippet in #68000_Assembly Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but ot...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#Ada
Ada
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;   procedure Test_Literals is begin Put (16#2D7#); Put (10#727#); Put (8#1_327#); Put (2#10_1101_0111#); end Test_Literals;
Give a code snippet in #Ada Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be i...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an ov...
#Lambdatalk
Lambdatalk
  {def ^ {def *^ {lambda {:base :exponent :acc} {if {= :exponent 0} then :acc else {*^ :base {- :exponent 1} {* :acc :base}}}}} {lambda {:base :exponent} {*^ :base :exponent 1}}} -> ^   {^ 2 3} -> 8 {^ {/ 1 2} 3} -> 0.125 // No rational type as primitives {^ 0.5 3} -> 0.125  
Give a code snippet in #Lambdatalk Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (o...
christopher/rosetta-code
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#Raku
Raku
sub is_munchausen ( Int $n ) { constant @powers = 0, |map { $_ ** $_ }, 1..9; $n == @powers[$n.comb].sum; } .say if .&is_munchausen for 1..5000;
Give a code snippet in #Raku A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see ...
christopher/rosetta-code
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149....
#OCaml
OCaml
#load "graphics.cma" open Graphics   let round x = int_of_float (floor(x +. 0.5))   let x = [0; 1; 2; 3; 4; 5; 6; 7; 8; 9] and y = [2.7; 2.8; 31.4; 38.1; 58.0; 76.2; 100.5; 130.0; 149.3; 180.0]   let () = open_graph ""; List.iter2 (fun x y -> (* scale to fit in the window *) let _x = x * 30 an...
Give a code snippet in #OCaml Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1,...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#Octave
Octave
% built in factorial printf("%d\n", factorial(50));   % let's define our recursive... function fact = my_fact(n) if ( n <= 1 ) fact = 1; else fact = n * my_fact(n-1); endif endfunction   printf("%d\n", my_fact(50));   % let's define our iterative function fact = iter_fact(n) fact = 1; for i = 2:n ...
Give a code snippet in #Octave Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a ...
christopher/rosetta-code