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/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 ...
#Pointless
Pointless
output = readFileLines("unixdict.txt") |> reduce(logWord, {}) |> vals |> getMax |> printLines   logWord(dict, word) = (dict with $[chars] = [word] ++ getDefault(dict, [], chars)) where chars = sort(word)   getMax(groups) = groups |> filter(g => length(g) == maxLength) where maxLength = groups |> map(l...
Give a code snippet in #Pointless 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#C.23
C#
using System; using System.IO;   namespace RosettaCode { class Program { static void Main() { try { File.Delete("input.txt"); Directory.Delete("docs"); File.Delete(@"\input.txt"); Directory.Delete(@"\docs"); } catch (Exc...
Give a code snippet in #C.23 Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Oforth
Oforth
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
Give a code snippet in #Oforth Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Modula-3
Modula-3
IF Foo = TRUE THEN Bar(); ELSE Baz(); END;
Give a code snippet in #Modula-3 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. Comm...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Modula-2
Modula-2
MODULE Main;   BEGIN END Main.
Give a code snippet in #Modula-2 Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail 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 ...
#C.23
C#
public static void cocktailSort(int[] A) { bool swapped; do { swapped = false; for (int i = 0; i <= A.Length - 2; i++) { if (A[i] > A[i + 1]) { //test whether the two elements are in the wrong order ...
Give a code snippet in #C.23 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/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.
#Quackery
Quackery
[ $ "turtleduck.qky" loadfile ] now! turtle 0 n->v 900 times [ 2dup walk 1 20 v+ 1 36 turn ] 2drop
Give a code snippet in #Quackery 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/Ramer-Douglas-Peucker_line_simplification
Ramer-Douglas-Peucker line simplification
Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Task Using the   Ramer–Douglas–P...
#PHP
PHP
function perpendicular_distance(array $pt, array $line) { // Calculate the normalized delta x and y of the line. $dx = $line[1][0] - $line[0][0]; $dy = $line[1][1] - $line[0][1]; $mag = sqrt($dx * $dx + $dy * $dy); if ($mag > 0) { $dx /= $mag; $dy /= $mag; }   // Calculate dot product, projecting ...
Give a code snippet in #PHP Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Task...
christopher/rosetta-code
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation langu...
#BBC_BASIC
BBC BASIC
MAXITEMS = 100 FOR i% = 1 TO 8 READ n PRINT "Value = "; n ", running SD = " FNrunningsd(n) NEXT END   DATA 2,4,4,4,5,5,7,9   DEF FNrunningsd(n) PRIVATE list(), i% DIM list(MAXITEMS) i% += 1 list(i%) = n = SQR(MOD(list())^2/i% - (SUM(list(...
Give a code snippet in #BBC_BASIC Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the f...
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 ...
#Vlang
Vlang
fn get_divisors(n int) []int { mut divs := [1, n] for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i divs << i if i != j { divs << j } } } return divs }   fn sum(divs []int) int { mut sum := 0 for div in divs { ...
Give a code snippet in #Vlang 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 divis...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#AutoIt
AutoIt
Local $var = drawBresenhamLine(2, 3, 2, 6)   Func drawBresenhamLine($iX0, $iY0, $iX1, $iY1) Local $iDx = Abs($iX1 - $iX0) Local $iSx = $iX0 < $iX1 ? 1 : -1 Local $iDy = Abs($iY1 - $iY0) Local $iSy = $iY0 < $iY1 ? 1 : -1 Local $iErr = ($iDx > $iDy ? $iDx : -$iDy) / 2, $e2   While $iX0 <= $iX1 ConsoleWrite("plot(...
Give a code snippet in #AutoIt Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
christopher/rosetta-code
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#Logo
Logo
collection = {0, '1'} print(collection[1]) -- prints 0   collection = {["foo"] = 0, ["bar"] = '1'} -- a collection of key/value pairs print(collection["foo"]) -- prints 0 print(collection.foo) -- syntactic sugar, also prints 0   collection = {0, '1', ["foo"] = 0, ["bar"] = '1'}
Give a code snippet in #Logo This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Cre...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body...
#E
E
for i in (0..10).descending() { println(i) }
Give a code snippet in #E Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#HolyC
HolyC
U16 i = 1024; while (i > 0) { Print("%d\n", i); i /= 2; }
Give a code snippet in #HolyC Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downwar...
christopher/rosetta-code
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. Par...
#Perl
Perl
sub co9 { # Follows the simple procedure asked for in Part 1 my $n = shift; return $n if $n < 10; my $sum = 0; $sum += $_ for split(//,$n); co9($sum); }   sub showadd { my($n,$m) = @_; print "( $n [",co9($n),"] + $m [",co9($m),"] ) [",co9(co9($n)+co9($m)),"]", " = ", $n+$m," [",co9($n+$m),"]\n...
Give a code snippet in #Perl Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or other...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap
Determine if two triangles overlap
Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)     and   (-10,0),(-5,0),(-1,6)...
#Racket
Racket
#lang racket   ;; A triangle is a list of three pairs of points: '((x . y) (x . y) (x . y)) (define (to-tri x1 y1 x2 y2 x3 y3) `((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)))   (define det-2D (match-lambda [`((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)) (+ (* x1 (- y2 y3)) (* x2 (- y3 y1)) (* x3 (- y1 y2)))]))   (define (assert-...
Give a code snippet in #Racket Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#Quackery
Quackery
[ over 3 mod 1 = ] is 1? ( n1 n2 --> n1 n2 f )   [ 3 / swap ] is 3/ ( n1 n2 --> n2/3 n1 )   [ true unrot [ 2dup or while 1? 1? and iff [ rot not unrot ] done 3/ 3/ again ] 2drop ] is incarpet ( n --> )   [...
Give a code snippet in #Quackery Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # #...
christopher/rosetta-code
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#UNIX_Shell
UNIX Shell
# choose 'choice 1' 'choice 2' ... # Prints menu to standard error. Prompts with PS3. # Reads REPLY from standard input. Sets CHOICE. choose() { CHOICE= # Default CHOICE is empty string. [[ $# -gt 0 ]] || return # Return if "$@" is empty. select CHOICE; do # Select from ...
Give a code snippet in #UNIX_Shell Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#Scala
Scala
import java.io.IOException import java.net.{InetAddress, ServerSocket}   object SingletonApp extends App { private val port = 65000   try { val s = new ServerSocket(port, 10, InetAddress.getLocalHost) } catch { case _: IOException => // port taken, so app is already running println("Applicat...
Give a code snippet in #Scala This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 ...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   import java.util.List import java.util.ArrayList   numeric digits 20   class RSortingPermutationsort public   properties private static iterations maxIterations   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~...
Give a code snippet in #NetRexx 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/Modified_random_distribution
Modified random distribution
Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x) taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[Modifier, CreateRandomNumber] Modifier[x_] := If[x < 0.5, 2 (0.5 - x), 2 (x - 0.5)] CreateRandomNumber[] := Module[{r1, r2, done = True}, While[done, r1 = RandomReal[]; r2 = RandomReal[]; If[r2 < Modifier[r1], Return[r1]; done = False ] ] ] numbers = Table[CreateRandomNumber[], 1000...
Give a code snippet in #Mathematica.2FWolfram_Language Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x) taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; th...
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 |...
#SenseTalk
SenseTalk
ask "Enter the first number:" put it into number1   ask "Enter the second number:" put it into number2   put "Sum: " & number1 plus number2 put "Difference: " & number1 minus number2 put "Product: " & number1 multiplied by number2 put "Integer quotient: " & number1 div number2 -- Rounding towards 0 put "Remainder: " & ...
Give a code snippet in #SenseTalk 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 Operati...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#8th
8th
"ha" 5 s:* . cr
Give a code snippet in #8th Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) =>...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#FutureBasic
FutureBasic
window 1   print date(@"yyyy-MM-dd") print date(@"EEEE, MMMM dd, yyyy")   HandleEvents
Give a code snippet in #FutureBasic This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/Logical_operations
Logical operations
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 |...
#Rust
Rust
  fn boolean_ops(a: bool, b: bool) { println!("{} and {} -> {}", a, b, a && b); println!("{} or {} -> {}", a, b, a || b); println!("{} xor {} -> {}", a, b, a ^ b); println!("not {} -> {}\n", a, !a); }   fn main() { boolean_ops(true, true); boolean_ops(true, false); boolean_ops(false, true); ...
Give a code snippet in #Rust 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 C...
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"
#Fortran
Fortran
program command_line_arguments   implicit none integer, parameter :: len_max = 256 integer :: i , nargs character (len_max) :: arg   nargs = command_argument_count() !nargs = iargc() do i = 0, nargs call get_command_argument (i, arg) !call getarg (i, arg) write (*, '(a)') trim (arg) end do  ...
Give a code snippet in #Fortran 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/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#Free_Pascal
Free Pascal
program queue; {$IFDEF FPC}{$MODE DELPHI}{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF}{$ENDIF} {$ASSERTIONS ON} uses Generics.Collections;   var lQueue: TQueue<Integer>; begin lQueue := TQueue<Integer>.Create; try lQueue.EnQueue(1); lQueue.EnQueue(2); lQueue.EnQueue(3); Write(lQueue.DeQueue:2); ...
Give a code snippet in #Free_Pascal Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in...
christopher/rosetta-code
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#Objeck
Objeck
  class Caesar { function : native : Encode(enc : String, offset : Int) ~ String { offset := offset % 26 + 26; encoded := ""; enc := enc->ToLower(); each(i : enc) { c := enc->Get(i); if(c->IsChar()) { j := (c - 'a' + offset) % 26; encoded->Append(j + 'a'); } els...
Give a code snippet in #Objeck Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z t...
christopher/rosetta-code
http://rosettacode.org/wiki/Variable_declaration_reset
Variable declaration reset
A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may ...
#jq
jq
[1,2,2,3,4,4,5] | . as $array | range(1;length) | select( $array[.] == $array[.-1])  
Give a code snippet in #jq A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. ...
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
#REXX
REXX
/*REXX program demonstrates the use of labels and also a CALL statement. */ blarney = -0 /*just a blarney & balderdash statement*/ signal do_add /*transfer program control to a label.*/ ttt = sinD(30) ...
Give a code snippet in #REXX 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/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="heal...
#XProc
XProc
<p:pipeline xmlns:p="http://www.w3.org/ns/xproc" name="one-two-three" version="1.0"> <p:identity> <p:input port="source"> <p:inline> <root> <first/> <prices/> <names/> </root> </p:inline> </p:input> </p:identity> <p:insert match="/root/first" p...
Give a code snippet in #XProc Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #...
christopher/rosetta-code
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#Action.21
Action!
DEFINE COUNT="20" BYTE ARRAY levels=[6 11 16 21 26 31 36 41 46 51 56 61 66 71 76 81 86 91 96 101] BYTE ARRAY values=[10 18 26 32 38 44 50 54 58 62 66 70 74 78 82 86 90 94 98 100]   PROC PrintValue(BYTE v) PrintB(v/100) Put('.) v=v MOD 100 PrintB(v/10) v=v MOD 10 PrintB(v) RETURN   BYTE FUNC Map(BYTE v) BYTE...
Give a code snippet in #Action.21 A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#AppleScript
AppleScript
on pickNumber() set theNumber to "" repeat 4 times set theDigit to (random number from 1 to 9) as string repeat while (offset of theDigit in theNumber) > 0 set theDigit to (random number from 1 to 9) as string end repeat set theNumber to theNumber & theDigit end repeat end pickNumber   to bulls of theGues...
Give a code snippet in #AppleScript Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins i...
christopher/rosetta-code
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguis...
#Ruby
Ruby
def a(k, x1, x2, x3, x4, x5) b = lambda { k -= 1; a(k, b, x1, x2, x3, x4) } k <= 0 ? x4[] + x5[] : b[] end   puts a(10, lambda {1}, lambda {-1}, lambda {-1}, lambda {1}, lambda {0})
Give a code snippet in #Ruby Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim...
christopher/rosetta-code
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Racket
Racket
#lang racket (define p 0.5001) (define (step) (> p (random)))   (define (step-up n) (cond ((zero? n) 'done) ((step) (step-up (sub1 n))) (else (step-up (add1 n)))))   (step-up 1)
Give a code snippet in #Racket From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function de...
christopher/rosetta-code
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#FreeBASIC
FreeBASIC
#define UPPER 1000000 #include"isprime.bas"   dim as uinteger champ = 0, record = 0, streak, i, j, n   'first generate all the primes below UPPER redim as uinteger prime(1 to 2) prime(1) = 2 : prime(2) = 3 for i = 5 to UPPER step 2 if isprime(i) then redim preserve prime(1 to ubound(prime) + 1) prim...
Give a code snippet in #FreeBASIC Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for ...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /...
#PicoLisp
PicoLisp
(load "@lib/xm.l")   (mapcar '((L) (attr L 'Name)) (body (in "file.xml" (xml))) )
Give a code snippet in #PicoLisp Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gend...
christopher/rosetta-code
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:...
#Racket
Racket
  #lang racket (require file/md5)   (md5 "") (md5 "a") (md5 "abc") (md5 "message digest") (md5 "abcdefghijklmnopqrstuvwxyz") (md5 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") (md5 "12345678901234567890123456789012345678901234567890123456789012345678901234567890")  
Give a code snippet in #Racket Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 ...
#Perl
Perl
1 while ($_ = shift and @ARGV and !fork); sleep $_; print "$_\n"; wait;
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/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#PicoLisp
PicoLisp
  (load "pluser/sieve.l") # See the task "Sieve of Eratosthanes"   (setq NthPrime '( ( 10 . 29) ( 100 . 541) ( 1000 . 7919) ( 10000 . 104729) ( 100000 . 1299709) (1000000 . 15485863)))   (de conspiracy (Power) (let (Upto (cdr (assoc (...
Give a code snippet in #PicoLisp A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided prefe...
christopher/rosetta-code
http://rosettacode.org/wiki/Median_filter
Median filter
The median filter takes in the neighbourhood the median color (see Median filter) (to test the function below, you can use these input and output solutions)
#Tcl
Tcl
package require Tk   # Set the color of a pixel proc applyMedian {srcImage x y -> dstImage} { set x0 [expr {$x==0 ? 0 : $x-1}] set y0 [expr {$y==0 ? 0 : $y-1}] set x1 $x set y1 $y set x2 [expr {$x+1==[image width $srcImage] ? $x : $x+1}] set y2 [expr {$y+1==[image height $srcImage] ? $y : $y+1}...
Give a code snippet in #Tcl The median filter takes in the neighbourhood the median color (see Median filter) (to test the function below, you can use these input and output solutions)
christopher/rosetta-code
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives ...
#Perl
Perl
#!/usr/bin/perl   use utf8; use strict; binmode STDOUT, ":utf8";   my (@tgt, %names); sub setprops { my %h = @_; my @p = keys %h; for my $p (@p) { my @v = @{ $h{$p} }; @tgt = map(+{idx=>$_-1, map{ ($_, undef) } @p}, 1 .. @v) unless @tgt; $names{$_} = $p for @v; } }   my $solve = sub { for my $i (@tgt) { ...
Give a code snippet in #Perl Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five hou...
christopher/rosetta-code
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   static class Program { static List<int> l = new List<int>() { 1, 1 };   static int gcd(int a, int b) { return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }   static void Main(string[] args) { int max = 1000; int take...
Give a code snippet in #C.23 For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.41421356...
#Lua
Lua
filename = "file.txt"   x = { 1, 2, 3, 1e11 } y = { 1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791 }; xprecision = 3; yprecision = 5;   fstr = "%."..tostring(xprecision).."f ".."%."..tostring(yprecision).."f\n"   fp = io.open( filename, "w+" )   for i = 1, #x do fp:write( string.format( fstr, x[i], y...
Give a code snippet in #Lua Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3,...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly...
#Ruby
Ruby
require 'prime'   def num_divisors(n) n.prime_division.inject(1){|prod, (_p,n)| prod *= (n + 1) } end   def first_with_num_divs(n) (1..).detect{|i| num_divisors(i) == n } end   p (1..15).map{|n| first_with_num_divs(n) }  
Give a code snippet in #Ruby Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Seq...
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...
#Nim
Nim
type Solution = tuple[p, s, f: int]   iterator solutions(max, total: Positive): Solution = for p in countup(2, max, 2): for s in 1..max: if s == p: continue let f = total - p - s if f notin [p, s] and f in 1..max: yield (p, s, f)   echo "P S F" for sol in solutions(7, 12): echo sol.p, ...
Give a code snippet in #Nim 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 (diff...
christopher/rosetta-code
http://rosettacode.org/wiki/Topological_sort
Topological 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 ...
#PicoLisp
PicoLisp
(de sortDependencies (Lst) (setq Lst # Build a flat list (uniq (mapcan '((L) (put (car L) 'dep (cdr L)) # Store dependencies in 'dep' properties (copy L) ) (mapcar uniq Lst) ) ) ) # without self-dependencies (m...
Give a code snippet in #PicoLisp 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/Numbers_with_equal_rises_and_falls
Numbers with equal rises and falls
When a number is written in base 10,   adjacent digits may "rise" or "fall" as the number is read   (usually from left to right). Definition Given the decimal digits of the number are written as a series   d:   A   rise   is an index   i   such that   d(i)  <  d(i+1)   A   fall    is an index   i   such that   ...
#MAD
MAD
NORMAL MODE IS INTEGER VECTOR VALUES FMT = $I8,1H:,I9*$   INTERNAL FUNCTION(NUM) ENTRY TO RISFAL. N=NUM DEPTH = 0 DIGA = N-(N/10)*10 N = N/10 LOOP WHENEVER N.E.0, FUNCTION RETURN DEPTH.E.0 DIGB = DIGA ...
Give a code snippet in #MAD When a number is written in base 10,   adjacent digits may "rise" or "fall" as the number is read   (usually from left to right). Definition Given the decimal digits of the number are written as a series   d:   A   rise   is an index   i   such that   d(i)  <  d(i+1)   A   fall    i...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Phix
Phix
atom t1 = time()+1 integer depth = 0 procedure recurse() if time()>t1 then ?depth t1 = time()+1 end if depth += 1 -- only 1 of these will ever get called, of course... recurse() recurse() recurse() end procedure recurse()
Give a code snippet in #Phix Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#AWK
AWK
cat power_set.awk #!/usr/local/bin/gawk -f   # User defined function function tochar(l,n, r) { while (l) { n--; if (l%2 != 0) r = r sprintf(" %c ",49+n); l = int(l/2) }; return r }   # For each input { for (i=0;i<=2^NF-1;i++) if (i == 0) printf("empty\n"); else printf("(%s)\n",tochar(i,NF)) }  
Give a code snippet in #AWK A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a...
christopher/rosetta-code
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#Purity
Purity
data Iter = f => FoldNat <const $f One, $f> data Ackermann = FoldNat <const Succ, Iter>
Give a code snippet in #Purity The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { ...
christopher/rosetta-code
http://rosettacode.org/wiki/Logical_operations
Logical operations
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 |...
#Nim
Nim
proc logic(a, b: bool) = echo "a and b: ", a and b echo "a or b: ", a or b echo "not a: ", not a echo "a xor b: ", a xor b
Give a code snippet in #Nim Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#Ring
Ring
oGenerator = new Generator   Func main oGenerator { accumulator = generator(1) see call accumulator(5) see nl generator(3) see call accumulator(2.3) }   Class Generator aN = []   func generator i aN + i return eval(substr("return func d { ...
Give a code snippet in #Ring A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values pass...
christopher/rosetta-code
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi
Almkvist-Giullera formula for pi
The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 This formula can be used to calcul...
#J
J
  numerator =: monad define "0 (3 * (! x: y)^6) %~ 32 * (!6x*y) * (y*(126 + 532*y)) + 9x )   term =: numerator % 10x ^ 3 + 6&*   echo 'The first 10 numerators are:' echo ,. numerator i.10   echo '' echo 'The sum of the first 10 terms (pi^-2) is ', 0j15 ": +/ term i.10   heron =: [: -: ] + %   sqrt =: dyad define NB...
Give a code snippet in #J The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 This fo...
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#ReScript
ReScript
let s1 = "hello" let s2 = s1 ++ " literal"   Js.log(s1) Js.log(s2)  
Give a code snippet in #ReScript String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string ...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET nd=1: LET np=0: LET na=0 20 FOR i=2 TO 20000 30 LET sum=1 40 LET max=i/2 50 LET n=2: LET l=max-1 60 IF n>l THEN GO TO 90 70 IF i/n=INT (i/n) THEN LET sum=sum+n: LET max=i/n: IF max<>n THEN LET sum=sum+max: LET l=max-1 80 LET n=n+1: GO TO 60 90 IF sum<i THEN LET nd=nd+1: GO TO 120 100 IF sum=i ...
Give a code snippet in #ZX_Spectrum_Basic These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed a...
christopher/rosetta-code
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the objec...
#Lingo
Lingo
squares = script("generator.power").new(2) cubes = script("generator.power").new(3) filter = script("generator.filter").new(squares, cubes) filter.skip(20) res = [] i = 0 repeat while filter.exec(res) i = i + 1 if i>10 then exit repeat put res[1] end repeat
Give a code snippet in #Lingo A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Break
Loops/Break
Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If the number 10 is never gener...
#PHP
PHP
while (true) { $a = rand(0,19); echo "$a\n"; if ($a == 10) break; $b = rand(0,19); echo "$b\n"; }
Give a code snippet in #PHP Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#ACL2
ACL2
(defun fast-fib-r (n a b) (if (or (zp n) (zp (1- n))) b (fast-fib-r (1- n) b (+ a b))))   (defun fast-fib (n) (fast-fib-r n 1 1))   (defun first-fibs-r (n i) (declare (xargs :measure (nfix (- n i)))) (if (zp (- n i)) nil (cons (fast-fib i) (first-fibs-r n (1+ i))))) ...
Give a code snippet in #ACL2 The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are ...
christopher/rosetta-code
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded c...
#jq
jq
# This filter may be applied to integers or integer-valued strings def luhntest: def digits: tostring | explode | map([.]|implode|tonumber); (digits | reverse) | ( [.[range(0;length;2)]] | add ) as $sum1 | [.[range(1;length;2)]] | (map( (2 * .) | if . > 9 then (digits|add) else . end) | add) as $sum2 | ($s...
Give a code snippet in #jq An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct fo...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#Nial
Nial
multiply is operation a b {a * b}
Give a code snippet in #Nial A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract f...
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 |...
#Elixir
Elixir
  x = "little" IO.puts "Mary had a #{x} lamb"  
Give a code snippet in #Elixir Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#PureBasic
PureBasic
#ToFind=8 #MaxTests=100 #True = 1: #False = 0 Declare is_happy(n)   If OpenConsole() Define i=1,Happy Repeat If is_happy(i) Happy+1 PrintN("#"+Str(Happy)+RSet(Str(i),3)) EndIf i+1 Until Happy>=#ToFind ; Print(#CRLF$+#CRLF$+"Press ENTER to exit"): Input() CloseConsole() EndIf   Proced...
Give a code snippet in #PureBasic From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endles...
christopher/rosetta-code
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactl...
#Common_Lisp
Common Lisp
(defun trailing-zerop (number) "Is the lowest digit of `number' a 0" (zerop (rem number 10)))   (defun integer-digits (integer) "Return the number of digits of the `integer'" (assert (integerp integer)) (length (write-to-string integer)))   (defun paired-factors (number) "Return a list of pairs that are fac...
Give a code snippet in #Common_Lisp A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original numb...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_simple
Abbreviations, simple
The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. For this task, the following   command table   will be used: add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 ...
#M2000_Interpreter
M2000 Interpreter
  Module Abbreviations_Simple { Function Lex { a$={add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 ...
Give a code snippet in #M2000_Interpreter The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. For this task, the following   command table   will be used: add 1 alter 3...
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...
#11l
11l
V nuggets = Set(0..100) L(s, n, t) cart_product(0 .. 100 I/ 6, 0 .. 100 I/ 9, 0 .. 100 I/ 20) nuggets.discard(6*s + 9*n + 20*t)   print(max(nuggets))
Give a code snippet in #11l 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 McNugg...
christopher/rosetta-code
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The follow...
#Pascal
Pascal
sub bin2gray { return $_[0] ^ ($_[0] >> 1); }   sub gray2bin { my ($num)= @_; my $bin= $num; while( $num >>= 1 ) { # a bit ends up flipped iff an odd number of bits to its left is set. $bin ^= $num; # different from the suggested algorithm; } # avoids using bit ma...
Give a code snippet in #Pascal Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many...
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. ...
#Dao
Dao
for( i = 1 : 5 ){ for( j = 1 : i ) io.write( '*' ) io.writeln() }
Give a code snippet in #Dao “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 structure...
christopher/rosetta-code
http://rosettacode.org/wiki/Ramanujan_primes/twins
Ramanujan primes/twins
In a manner similar to twin primes, twin Ramanujan primes may be explored. The task is to determine how many of the first million Ramanujan primes are twins. Related Task Twin primes
#Nim
Nim
import math, sequtils, strutils, sugar, times   let t0 = now()   type PrimeCounter = seq[int32]   proc initPrimeCounter(limit: Positive): PrimeCounter {.noInit.} = doAssert limit > 1 result = repeat(1i32, limit) result[0] = 0 result[1] = 0 for i in countup(4, limit - 1, 2): result[i] = 0 var p = 3 var p2 ...
Give a code snippet in #Nim In a manner similar to twin primes, twin Ramanujan primes may be explored. The task is to determine how many of the first million Ramanujan primes are twins. Related Task Twin primes
christopher/rosetta-code
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#IDL
IDL
result = 1.0 + 0.5*randomn(seed,1000)
Give a code snippet in #IDL Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related t...
christopher/rosetta-code
http://rosettacode.org/wiki/Nonogram_solver
Nonogram solver
A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs of occupied cells. Using only...
#Julia
Julia
using Base.Iterators   struct NonogramPuzzle nrows::Int ncols::Int xhints::Vector{Vector{Int}} yhints::Vector{Vector{Int}} solutions:: Vector{Any} NonogramPuzzle(xh, yh) = new(length(xh), length(yh), xh, yh, Vector{NTuple{4,Array{Int64,1}}}()) end   ycols2xrows(ycols) = [[ycols[i][j] for i in ea...
Give a code snippet in #Julia A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct run...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_square_curve
Sierpinski square curve
Task Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
#Factor
Factor
USING: accessors kernel L-system sequences ui ;   : square-curve ( L-system -- L-system ) L-parser-dialect >>commands [ 90 >>angle ] >>turtle-values "F+XF+F+XF" >>axiom { { "X" "XF-F+F-XF+F+XF-F+F-X" } } >>rules ;   [ <L-system> square-curve "Sierpinski square curve" open-window ] wi...
Give a code snippet in #Factor Task Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
christopher/rosetta-code
http://rosettacode.org/wiki/Statistics/Normal_distribution
Statistics/Normal distribution
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random number generator and create a ...
#C.2B.2B
C++
#include <random> #include <map> #include <string> #include <iostream> #include <cmath> #include <iomanip>   int main( ) { std::random_device myseed ; std::mt19937 engine ( myseed( ) ) ; std::normal_distribution<> normDistri ( 2 , 3 ) ; std::map<int , int> normalFreq ; int sum = 0 ; //holds the sum of th...
Give a code snippet in #C.2B.2B The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform rand...
christopher/rosetta-code
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an...
#COBOL
COBOL
>>SOURCE FORMAT FREE *> This code is dedicated to the public domain identification division. program-id. dragon. environment division. configuration section. repository. function all intrinsic. data division. working-storage section. 01 segment-length pic 9 value 2. 01 mark pic x value '.'. 01 segment-count...
Give a code snippet in #COBOL Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by...
christopher/rosetta-code
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ...
#ObjectIcon
ObjectIcon
# # Floyd-Warshall algorithm. # # See https://en.wikipedia.org/w/index.php?title=Floyd%E2%80%93Warshall_algorithm&oldid=1082310013 #   import io import ipl.array import ipl.printf   record fw_results (n, distance, next_vertex)   procedure main () local example_graph local fw local u, v   example_graph := [[1, -...
Give a code snippet in #ObjectIcon The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has alrea...
christopher/rosetta-code
http://rosettacode.org/wiki/Problem_of_Apollonius
Problem of Apollonius
Task Implement a solution to the Problem of Apollonius   (description on Wikipedia)   which is the problem of finding the circle that is tangent to three specified circles   (colored black in the diagram below to the right). There is an   algebraic solution   which is pretty straightforward. The solutions to the ...
#Sidef
Sidef
class Circle(x,y,r) { method to_s { "Circle(#{x}, #{y}, #{r})" } }   func solve_apollonius(c, s) {   var(c1, c2, c3) = c...; var(s1, s2, s3) = s...;   var 𝑣11 = (2*c2.x - 2*c1.x); var 𝑣12 = (2*c2.y - 2*c1.y); var 𝑣13 = (c1.x**2 - c2.x**2 + c1.y**2 - c2.y**2 - c1.r**2 + c2.r**2); var 𝑣14 ...
Give a code snippet in #Sidef Task Implement a solution to the Problem of Apollonius   (description on Wikipedia)   which is the problem of finding the circle that is tangent to three specified circles   (colored black in the diagram below to the right). There is an   algebraic solution   which is pretty straightfo...
christopher/rosetta-code
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#Icon_and_Unicon
Icon and Unicon
procedure main() S := [] writes("Enter 11 numbers: ") read() ? every !11 do (tab(many(' \t'))|0,put(S, tab(upto(' \t')|0))) every item := !reverse(S) do write(item, " -> ", (400 >= f(item)) | "overflows") end   procedure f(x) return abs(x)^0.5 + 5*x^3 end
Give a code snippet in #Icon_and_Unicon The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#MOO
MOO
a = make(10, make(10)); for i in [1..10] for j in [1..10] a[i][j] = random(20); endfor endfor for i in [1..10] s = ""; for j in [1..10] s += tostr(" ", a[i][j]); if (a[i][j] == 20) break i; endif endfor player:tell(s); s = ""; endfor player:tell(s);
Give a code snippet in #MOO Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met....
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#PicoLisp
PicoLisp
(scl 49) (de fsqrt2 (N A) (default A 1) (cond ((> A (inc N)) 2) (T (+ (if (=1 A) 1.0 2.0) (*/ `(* 1.0 1.0) (fsqrt2 N (inc A))) ) ) ) ) (de pi (N A) (default A 1) (cond ((> A (inc N)) 6.0) (T (+ (if (=1 A) 3.0 6.0) (*/ ...
Give a code snippet in #PicoLisp continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to ...
christopher/rosetta-code
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the i...
#JavaScript
JavaScript
  var mac = "88:53:2E:67:07:BE"; function findmac(){ window.open("http://api.macvendors.com/" + mac); }   findmac();  
Give a code snippet in #JavaScript Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (o...
christopher/rosetta-code
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation
Bioinformatics/Sequence mutation
Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance o...
#C.2B.2B
C++
#include <array> #include <iomanip> #include <iostream> #include <random> #include <string>   class sequence_generator { public: sequence_generator(); std::string generate_sequence(size_t length); void mutate_sequence(std::string&); static void print_sequence(std::ostream&, const std::string&); enum...
Give a code snippet in #C.2B.2B Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, ...
christopher/rosetta-code
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Racket
Racket
  #lang racket (file-or-directory-modify-seconds "foo.rkt")  
Give a code snippet in #Racket Task Get and set the modification time of a file.
christopher/rosetta-code
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Batch_File
Batch File
del input.txt rd /s /q docs   del \input.txt rd /s /q \docs
Give a code snippet in #Batch_File Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
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...
#Pop11
Pop11
gcd_n(15, 12, 2) =>
Give a code snippet in #Pop11 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Object_serialization
Object serialization
Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o...
#zkl
zkl
class [static] ARootClass{ // A top level class, no instances class A{ self.println(" constructor"); } // a regular class class B(A){ // ditto var x; fcn init(x=123){ self.x=x } fcn toString{ "x is "+x } } }   ARootClass.B(456).println(); // create an instance // prints: Class(A) constr...
Give a code snippet in #zkl Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#C.2B.2B
C++
#include <algorithm> #include <string> #include <cctype>   // compare character case-insensitive struct icompare_char { bool operator()(char c1, char c2) { return std::toupper(c1) < std::toupper(c2); } };   // return true if s1 comes before s2 struct compare { bool operator()(std::string const& s1, std::strin...
Give a code snippet in #C.2B.2B 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/Create_a_file
Create a file
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Delphi
Delphi
  program createFile;   {$APPTYPE CONSOLE}   uses Classes, SysUtils;   const filename = 'output.txt';   var cwdPath, fsPath: string;     // Create empty file in current working directory function CreateEmptyFile1: Boolean; var f: textfile; begin // Make path to the file to be created cwdPath := ExtractF...
Give a code snippet in #Delphi In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/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.)
#Arendelle
Arendelle
  /* ARM assembly Raspberry PI comment one line */ /* comment line 1 comment line 2 */   mov r0,#0 @ this comment on end of line mov r1,#0 // authorized comment    
Give a code snippet in #Arendelle 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/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...
#F.C5.8Drmul.C3.A6
Fōrmulæ
RandNGen := function(n) local v, rand; v := [1 .. n - 1]*0; Add(v, 1); rand := function() return Random(v); end; return rand; end;   UnbiasedGen := function(rand) local unbiased; unbiased := function() local a, b; while true do a := rand(); b := rand(); if a <> b then break; fi; od; re...
Give a code snippet in #F.C5.8Drmul.C3.A6 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 numbe...
christopher/rosetta-code
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#Common_Lisp
Common Lisp
  (defun hello-goodbye (files) (labels ((replace-from-file (file) (with-open-file (in file) (loop for line = (read-line in nil) while line do (loop for index = (search "Goodbye London!" line) while index do ...
Give a code snippet in #Common_Lisp Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8
Read a file character by character/UTF8
Task Read a file one character at a time, as opposed to reading the entire file at once. The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached). The procedure should support the reading of files contain...
#PicoLisp
PicoLisp
  (in "wordlist" (while (char) (process @))  
Give a code snippet in #PicoLisp Task Read a file one character at a time, as opposed to reading the entire file at once. The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached). The procedure should su...
christopher/rosetta-code
http://rosettacode.org/wiki/Password_generator
Password generator
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above ch...
#Scala
Scala
object makepwd extends App {   def newPassword( salt:String = "", length:Int = 13, strong:Boolean = true ) = {   val saltHash = salt.hashCode & ~(1 << 31)   import java.util.Calendar._   val cal = java.util.Calendar.getInstance() val rand = new scala.util.Random((cal.getTimeInMillis+saltHash).toLong) ...
Give a code snippet in #Scala Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typica...
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   DEFINE R_="+0" DEFINE I_="+6" TYPE Complex=[CARD cr1,cr2,cr3,ci1,ci2,ci3]   BYTE FUNC Positive(REAL POINTER x) BYTE ARRAY tmp   tmp=x IF (tmp(0)&$80)=$00 THEN RETURN (1) FI RETURN (0)   PROC PrintComplex(Complex POINTER x) PrintR(x R_) IF Positive(x I_)...
Give a code snippet in #Action.21 A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displ...
christopher/rosetta-code
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#PL.2FI
PL/I
(subscriptrange): Conway: procedure options (main); /* 20 November 2013 */ /* A grid of (1:100, 1:100) is desired; the array GRID is defined as (0:101, 0:101), */ /* to satisfy the requirement that elements off-grid are zero. */ declare n fixed binary; /* grid size) */   put ('W...
Give a code snippet in #PL.2FI The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. ...
#F.23
F#
System.IO.Directory.GetFiles("c:\\temp", "*.xml") |> Array.iter (printfn "%s")
Give a code snippet in #F.23 Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, n...
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...
#PL.2FI
PL/I
  test: procedure options (main); /* 20 Nov. 2012 */   randN: procedure(N) returns (bit (1)); declare N fixed (1); declare random builtin; declare r fixed (2) external initial (-1); if r >= 0 then do; r = r-1; return ('0'b); end; r = random()*2*N; return ('1'b); end randN;   random: procedure returns ...
Give a code snippet in #PL.2FI P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator...
christopher/rosetta-code
http://rosettacode.org/wiki/Linear_congruential_generator
Linear congruential generator
The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaystyle r_{0}} is a seed. r 1 ...
#SequenceL
SequenceL
  import <Utilities/Random.sl>;   main(args(2)) := let bsdRandomGenerator := newRandomGenerator(0, 0, 2147483647, bsdNext); msRandomGenerator := newRandomGenerator(0, 0, 32767, msNext);   // Create a random sequence with each one of the generators numbers := getRandomSequence([bsdRandomGenerator, msRandomGener...
Give a code snippet in #SequenceL The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaysty...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#dc
dc
{}
Give a code snippet in #dc Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance m...
#Objeck
Objeck
  ClassName->some_function(); # call class function instance->some_method(); # call instance method
Give a code snippet in #Objeck In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge 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 ...
#Sidef
Sidef
func stooge(x, i, j) { if (x[j] < x[i]) { x.swap(i, j) }   if (j-i > 1) { var t = ((j - i + 1) / 3) stooge(x, i, j - t) stooge(x, i + t, j ) stooge(x, i, j - t) } }   var a = 10.of { 100.irand }   say "Before #{a}" stooge(a, 0, a.end) say "After #{a}"
Give a code snippet in #Sidef Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick so...
christopher/rosetta-code