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/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#Java
Java
public static int[][] Zig_Zag(final int size) { int[][] data = new int[size][size]; int i = 1; int j = 1; for (int element = 0; element < size * size; element++) { data[i - 1][j - 1] = element; if ((i + j) % 2 == 0) { // Even stripes if (j < size) j++; else i+= 2; if (i > 1) i--; } ...
Give a code snippet in #Java Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to enco...
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. ...
#8080_Assembly
8080 Assembly
exit: equ 0 ; CP/M syscall to exit puts: equ 9 ; CP/M syscall to print a string sfirst: equ 17 ; 'Find First' CP/M syscall snext: equ 18 ; 'Find Next' CP/M syscall FCB: equ 5Ch ; Location of FCB for file given on command line org 100h lxi d,FCB ; CP/M parses the command line for us automatically mvi c,sfirst; and p...
Give a code snippet in #8080_Assembly 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 dir...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#FreeBASIC
FreeBASIC
  Open Cons For Output As #1 ' Open Cons abre los flujos de entrada (stdin) o salida (stdout) estándar ' de la consola para leer o escribir.   If Err > 0 Then Print #1, "stdout is not a tty." Else Print #1, "stdout is a tty." End If Close #1 Sleep  
Give a code snippet in #FreeBASIC Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
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...
#ALGOL_68
ALGOL 68
BOOL prime = TRUE, non prime = FALSE; PROC eratosthenes = (INT n)[]BOOL: ( [n]BOOL sieve; FOR i TO UPB sieve DO sieve[i] := prime OD; INT m = ENTIER sqrt(n); sieve[1] := non prime; FOR i FROM 2 TO m DO IF sieve[i] = prime THEN FOR j FROM i*i BY i TO n DO sieve[j] := non prime OD FI...
Give a code snippet in #ALGOL_68 This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes ...
christopher/rosetta-code
http://rosettacode.org/wiki/Dining_philosophers
Dining philosophers
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a rou...
#Phix
Phix
without js -- threads integer fork1 = init_cs(), fork2 = init_cs(), fork3 = init_cs(), fork4 = init_cs(), fork5 = init_cs() integer terminate = 0 -- control flag procedure person(sequence name, atom left_fork, atom right_fork) -- (except Russell, who gets left and rig...
Give a code snippet in #Phix The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eatin...
christopher/rosetta-code
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#AWK
AWK
cat mutual_recursion.awk: #!/usr/local/bin/gawk -f   # User defined functions function F(n) { return n == 0 ? 1 : n - M(F(n-1)) }   function M(n) { return n == 0 ? 0 : n - F(M(n-1)) }   BEGIN { for(i=0; i <= 20; i++) { printf "%3d ", F(i) } print "" for(i=0; i <= 20; i++) { printf "%3d ", M(i) } pri...
Give a code snippet in #AWK Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Julia
Julia
run(`ls`)
Give a code snippet in #Julia Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#Maple
Maple
  F := unapply( sum(3*i,i=1..floor((n-1)/3)) + sum(5*i,i=1..floor((n-1)/5)) - sum(15*i,i=1..floor((n-1)/15)), n);   F(1000);   F(10^20);  
Give a code snippet in #Maple Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
christopher/rosetta-code
http://rosettacode.org/wiki/HTTPS
HTTPS
Task Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console. Checking the host certificate for validity is recommended. Do not authenticate. That is the subject of other tasks. Readers may wish to contrast with the HTTP Request task, and also the task on HTT...
#Sidef
Sidef
var lwp = require('LWP::UserAgent'); # LWP::Protocol::https is needed var url = 'https://rosettacode.org';   var ua = lwp.new( agent => 'Mozilla/5.0', ssl_opts => Hash.new(verify_hostname => 1), );   var resp = ua.get(url); resp.is_success || die "Failed to GET #{url.dump}: #{resp.status_line}"; print res...
Give a code snippet in #Sidef Task Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console. Checking the host certificate for validity is recommended. Do not authenticate. That is the subject of other tasks. Readers may wish to contrast with the HTTP Request...
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...
#Dylan
Dylan
define method a (k :: <integer>, x1 :: <function>, x2 :: <function>, x3 :: <function>, x4 :: <function>, x5 :: <function>) => (i :: <integer>)   local b() => (i :: <integer>) k := k - 1; a(k, b, x1, x2, x3, x4) end;   if (k <= 0) x4() + x5() else b() end if   end method a;   defi...
Give a code snippet in #Dylan 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 ai...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
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 Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#Perl
Perl
@queue = (); # we will simulate a queue in a array   push @queue, (1..5); # enqueue numbers from 1 to 5   print shift @queue,"\n"; # dequeue   print "array is empty\n" unless @queue; # is empty ?   print $n while($n = shift @queue); # dequeue all print "\n"; print "array is empty\n" unless @queue; # is empty ?
Give a code snippet in #Perl 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 Create a queue data structure and demonstrate its operations. (For implementations of queu...
christopher/rosetta-code
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th...
#Scala
Scala
object Sailors extends App { var x = 0   private def valid(n: Int, _nuts: Int): Boolean = { var nuts = _nuts for (k <- n until 0 by -1) { if (nuts % n != 1) return false nuts -= 1 + nuts / n } nuts != 0 && (nuts % n == 0) }   for (nSailors <- 2 until 10) { while (!valid(nSailors,...
Give a code snippet in #Scala Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
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 ...
#Common_Lisp
Common Lisp
CL-USER> (defparameter *test-scores* '(("texas" 68.9) ("ohio" 87.8) ("california" 76.2) ("new york" 88.2)) ) *TEST-SCORES*
Give a code snippet in #Common_Lisp 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/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#Factor
Factor
USING: kernel math prettyprint ;   : sum-multiples ( m n upto -- sum ) >integer 1 - [ 2dup * ] dip [ 2dup swap [ mod - + ] [ /i * 2/ ] 2bi ] curry tri@ [ + ] [ - ] bi* ;   3 5 1000 sum-multiples . 3 5 1e20 sum-multiples .
Give a code snippet in #Factor Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#Nim
Nim
import strutils, sugar   proc facmod(n, m: int): int = ## Compute (n - 1)! mod m. result = 1 for k in 2..n: result = (result * k) mod m   func isPrime(n: int): bool = (facmod(n - 1, n) + 1) mod n == 0   let primes = collect(newSeq): for n in 2..100: if n.isPrime: n   echo "Prim...
Give a code snippet in #Nim Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wi...
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 ...
#Slate
Slate
define: #multiply -> [| :a :b | a * b].
Give a code snippet in #Slate 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/CUSIP
CUSIP
This page uses content from Wikipedia. The original article was at CUSIP. 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) A   CUSIP   is a nine-character alphanumeric code that identifies a North A...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function IsCUSIP(s As String) As Boolean If s.Length <> 9 Then Return False End If   Dim sum = 0 For i = 0 To 7 Dim c = s(i)   Dim v As Integer If "0" <= c AndAlso c <= "9" Then v = Asc(c) - 48 ...
Give a code snippet in #Visual_Basic_.NET This page uses content from Wikipedia. The original article was at CUSIP. 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) A   CUSIP   is a nine-character ...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections ...
#Axe
Axe
Lbl LINK r₂→{r₁}ʳ 0→{r₁+2}ʳ 0→{r₁+4}ʳ r₁ Return   Lbl NEXT {r₁+2}ʳ Return   Lbl PREV {r₁+4}ʳ Return   Lbl VALUE {r₁}ʳ Return
Give a code snippet in #Axe Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Crea...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#C
C
#include <string.h>   int main(void) { const char *string = "Hello, world!"; size_t length = strlen(string);   return 0; }
Give a code snippet in #C Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containi...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Yabasic
Yabasic
  error "Goodbye World!"  
Give a code snippet in #Yabasic Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard ou...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#Octave
Octave
M = [ 3, 2; 2, 1 ]; M^0 M^1 M^2 M^(-1) M^0.5
Give a code snippet in #Octave Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Clojure
Clojure
(let [[a b] (repeatedly read)] (doseq [[op string] [[< "less than"] [> "greater than"] [= "equal to"]]] (when (op a b) (println (str a " is " string " " b)))))
Give a code snippet in #Clojure 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 Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Vi...
#Go
Go
package main   import ( "bufio" "encoding/binary" "fmt" "log" "os" "strconv" "strings" )   type NodeType int   const ( ndIdent NodeType = iota ndString ndInteger ndSequence ndIf ndPrtc ndPrts ndPrti ndWhile ndAssign ndNegate ndNot ndMul ...
Give a code snippet in #Go A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine cod...
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...
#AutoHotkey
AutoHotkey
Cset(C,1,1) MsgBox % Cstr(C) ; 1 + i*1 Cneg(C,C) MsgBox % Cstr(C) ; -1 - i*1 Cadd(C,C,C) MsgBox % Cstr(C) ; -2 - i*2 Cinv(D,C) MsgBox % Cstr(D) ; -0.25 + 0.25*i Cmul(C,C,D) MsgBox % Cstr(C) ; 1 + i*0   Cset(ByRef C, re, im) { VarSetCapacity(C,16) NumPut(re,C,0,"double") NumPut(im,C,8,"double") } Cre(ByRef...
Give a code snippet in #AutoHotkey 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 {\disp...
christopher/rosetta-code
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper...
#M2000_Interpreter
M2000 Interpreter
  Class Alfa$ { Private: myValue$ Public: Set { Read .myValue$ } Value { =.myValue$ } Module Doit { Function TwoChars$(A$) { =Left$(Left$(a$,1)+Right$(a$,1)+"??",2) ...
Give a code snippet in #M2000_Interpreter Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regardi...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Count_examples
Rosetta Code/Count examples
task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'll need to use the Media Wiki AP...
#PureBasic
PureBasic
Procedure handleError(value, msg.s) If value = 0 MessageRequester("Error", msg) End EndIf EndProcedure   handleError(InitNetwork(), "Unable to initialize network functions.") If OpenConsole() Define url$, x1$, y1$, title$, unescapedTitle$, encodedURL$ Define x2, i, j, totalExamples, totalTasks url$ = ...
Give a code snippet in #PureBasic task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. Y...
christopher/rosetta-code
http://rosettacode.org/wiki/Heronian_triangles
Heronian triangles
Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b + c 2 . {\displaystyle s...
#ALGOL_W
ALGOL W
begin  % record to hold details of a Heronian triangle % record Heronian ( integer a, b, c, area, perimeter );  % returns the details of the Heronian Triangle with sides a, b, c or nil if it isn't one % reference(Heronian) procedure tryHt( integer value a, b, c ) ; begin real s,...
Give a code snippet in #ALGOL_W Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance/Alignment
Levenshtein distance/Alignment
The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order. An alignment is a notation used to describe the operations used t...
#Raku
Raku
sub align ( Str $σ, Str $t ) { my @s = flat *, $σ.comb; my @t = flat *, $t.comb;   my @A; @A[$_][ 0]<d s t> = $_, @s[1..$_].join, '-' x $_ for ^@s; @A[ 0][$_]<d s t> = $_, '-' x $_, @t[1..$_].join for ^@t;   for 1 ..^ @s X 1..^ @t -> (\i, \j) { if @s[i] ne @t[j] { @A[i][j]<d> = 1 + my $min...
Give a code snippet in #Raku The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order. An alignment is a notation used to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Conjugate_transpose
Conjugate transpose
Suppose that a matrix M {\displaystyle M} contains complex numbers. Then the conjugate transpose of M {\displaystyle M} is a matrix M H {\displaystyle M^{H}} containing the complex conjugates of the matrix transposition of M {\displaystyle M} . ( M H ) j i = M i j ...
#Maple
Maple
M:=<<3|2+I>,<2-I|1>>:   with(LinearAlgebra): IsNormal:=A->EqualEntries(A^%H.A,A.A^%H):   M^%H; HermitianTranspose(M); type(M,'Matrix'(hermitian)); IsNormal(M); IsUnitary(M);
Give a code snippet in #Maple Suppose that a matrix M {\displaystyle M} contains complex numbers. Then the conjugate transpose of M {\displaystyle M} is a matrix M H {\displaystyle M^{H}} containing the complex conjugates of the matrix transposition of M {\displaystyle M} . ( ...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack
Stack
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. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#UNIX_Shell
UNIX Shell
init() { if [[ -n $KSH_VERSION ]]; then set -A stack else stack=(); # this sets stack to '()' in ksh fi }   push() { stack=("$1" "${stack[@]}") }   stack_top() { # this approach sidesteps zsh indexing difference set -- "${stack[@]}" printf '%s\n' "$1" }   pop() { stack_top stack=("${stack[@]:...
Give a code snippet in #UNIX_Shell 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. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack ...
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...
#Clojure
Clojure
(let [temp-file (java.io.File/createTempFile "pre" ".suff")] ; insert logic here that would use temp-file (.delete temp-file))
Give a code snippet in #Clojure 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 conditio...
christopher/rosetta-code
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#JavaScript
JavaScript
e = {} // generic object e.foo = 1 e["bar"] = 2 // name specified at runtime
Give a code snippet in #JavaScript Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in M...
christopher/rosetta-code
http://rosettacode.org/wiki/Horizontal_sundial_calculations
Horizontal sundial calculations
Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit...
#ALGOL_68
ALGOL 68
BEGIN REAL lat, slat, lng, ref; print ( "Enter latitude => " ); read (lat); print ( "Enter longitude => " ); read (lng); print ( "Enter legal meridian => " ); read (ref); new line(stand out);   slat := sin(lat*2*pi/360) ; print ( (" sine of latitude: ", float(slat,8,2,1), new line ) ); p...
Give a code snippet in #ALGOL_68 Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Isl...
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
#Maple
Maple
antiprimes := proc(n) local ap, i, max_divisors, num_divisors; max_divisors := 0; ap := [];   for i from 1 while numelems(ap) < n do num_divisors := numelems(NumberTheory:-Divisors(i)); if num_divisors > max_divisors then ap := [op(ap), i]; max_divisors := num_divisors; end if; end do;   retur...
Give a code snippet in #Maple 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/Equal_prime_and_composite_sums
Equal prime and composite sums
Suppose we have a sequence of prime sums, where each term Pn is the sum of the first n primes. P = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ... P = 2, 5, 10, 17, 28, etc. Further; suppose we have a sequence of composite sums, where each term Cm is the sum of the first m composites. C = (4...
#Julia
Julia
using Primes   function getsequencematches(N, masksize = 1_000_000_000) pmask = primesmask(masksize) found, psum, csum, pindex, cindex, pcount, ccount = 0, 2, 4, 2, 4, 1, 1 incrementpsum() = (pindex += 1; if pmask[pindex] psum += pindex; pcount += 1 end) incrementcsum() = (cindex += 1; if !pmask[cindex]...
Give a code snippet in #Julia Suppose we have a sequence of prime sums, where each term Pn is the sum of the first n primes. P = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ... P = 2, 5, 10, 17, 28, etc. Further; suppose we have a sequence of composite sums, where each term Cm is the sum of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ...
#EchoLisp
EchoLisp
  (define-syntax-rule (deg->radian deg) (* deg 1/180 PI)) (define-syntax-rule (radian->deg rad) (* 180 (/ PI) rad))   (define (mean-angles angles) (radian->deg (angle (for/sum ((a angles)) (make-polar 1 (deg->radian a))))))   (mean-angles '( 350 10)) → -0 (mean-angles '[90 180 270 360]) → -9...
Give a code snippet in #EchoLisp When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first r...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutation_test
Permutation test
Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n {\displaystyle n} treatment...
#Python
Python
from itertools import combinations as comb   def statistic(ab, a): sumab, suma = sum(ab), sum(a) return ( suma / len(a) - (sumab -suma) / (len(ab) - len(a)) )   def permutationTest(a, b): ab = a + b Tobs = statistic(ab, a) under = 0 for count, perm in enumerate(comb(ab, len(a)), 1):...
Give a code snippet in #Python Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n...
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 ...
#Dart
Dart
  bool isPalindrome(String s){ for(int i = 0; i < s.length/2;i++){ if(s[i] != s[(s.length-1) -i]) return false; } return true; }  
Give a code snippet in #Dart 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#Whenever
Whenever
  1 2#read()-N(2); 2 2; 3 defer(1 || N(2) > 90 || N(2) < 65) 5#65-N(5); 4 defer(1 || N(2) > 122 || N(2) < 97) 5#97-N(5); 5 5; 6 defer(3 && 4) put(U(((N(2) - N(5) + 13) % 26) + N(5))); 7 defer(1 || N(2) > 64 || N(2) == 0) put(U(N(2))); 8 again(8) defer(6 && 7) 1,-6#N(6)-1,-7#N(7)-1,-3#N(3)-1,-4#N(4)-1; 9 defer(1 || N(2)...
Give a code snippet in #Whenever Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot...
christopher/rosetta-code
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#Swift
Swift
var cache = [[1]] func namesOfGod(n:Int) -> [Int] { for l in cache.count...n { var r = [0] for x in 1...l { r.append(r[r.count - 1] + cache[l - x][min(x, l-x)]) } cache.append(r) } return cache[n] }   func row(n:Int) -> [Int] { let r = namesOfGod(n) var re...
Give a code snippet in #Swift This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_Computer/Zero
Execute Computer/Zero
Execute Computer/Zero is an implementation of Computer/zero Assembly. Other implementations of Computer/zero Assembly. Task Create a Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs "2+2" and "7*8" found there.   The virtual machi...
#Phix
Phix
with javascript_semantics constant NOP = 0b000_00000, -- no operation LDA = 0b001_00000, -- load accumulator, a := memory [xxxxx] STA = 0b010_00000, -- store accumulator, memory [xxxxx] := a ADD = 0b011_00000, -- add, a := a + memory [xxxxx] SUB = 0b100_00000, -- subtract, a := a – m...
Give a code snippet in #Phix Execute Computer/Zero is an implementation of Computer/zero Assembly. Other implementations of Computer/zero Assembly. Task Create a Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs "2+2" and "7*8" foun...
christopher/rosetta-code
http://rosettacode.org/wiki/Stable_marriage_problem
Stable marriage problem
Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of engagements for marriage is o...
#Julia
Julia
  # This is not optimized, but tries to follow the pseudocode given the Wikipedia entry below. # Reference: https://en.wikipedia.org/wiki/Stable_marriage_problem#Algorithm   const males = ["abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"] const females = ["abi", "bea", "cath", "dee", "eve", "fay", "...
Give a code snippet in #Julia Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set o...
christopher/rosetta-code
http://rosettacode.org/wiki/Lah_numbers
Lah numbers
Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets. Lah numbers a...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "math/big" )   func main() { limit := 100 last := 12 unsigned := true l := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { l[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { l[n][k] = new(big.Int) } ...
Give a code snippet in #F.C5.8Drmul.C3.A6 Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-emp...
christopher/rosetta-code
http://rosettacode.org/wiki/Fivenum
Fivenum
Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the   R   programming language i...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Runtime.CompilerServices Imports System.Text   Module Module1   <Extension()> Function AsString(Of T)(c As ICollection(Of T), Optional format As String = "{0}") As String Dim sb As New StringBuilder("[") Dim it = c.GetEnumerator() If it.MoveNext() Then sb.Appen...
Give a code snippet in #Visual_Basic_.NET Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. Fo...
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"
#Genie
Genie
[indent=4] /* Command line arguments, in Genie   valac commandLine.gs ./commandLine sample arguments 'four in total here, including args 0' */   init   // Output the number of arguments print "%d command line argument(s):", args.length   // Enumerate all command line arguments for s in args ...
Give a code snippet in #Genie 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/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain sync...
#Wren
Wren
import "scheduler" for Scheduler import "timer" for Timer   var Interval = 0   class Integrator { construct new() { _sum = 0 }   input(k) { _k = k _v0 = k.call(0) _t = 0 _running = true integrate_() }   output { _sum }   stop() { _running =...
Give a code snippet in #Wren In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such me...
christopher/rosetta-code
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules: ...
#Rust
Rust
extern crate rand; #[macro_use] extern crate rand_derive;   use std::io; use rand::Rng; use Choice::*;   #[derive(PartialEq, Clone, Copy, Rand, Debug)] enum Choice { Rock, Paper, Scissors, }   fn beats(c1: Choice, c2: Choice) -> bool { (c1 == Rock && c2 == Scissors) || (c1 == Scissors && c2 == Paper) ||...
Give a code snippet in #Rust Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner ...
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#Seed7
Seed7
odd(aNumber)
Give a code snippet in #Seed7 Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divi...
christopher/rosetta-code
http://rosettacode.org/wiki/Short-circuit_evaluation
Short-circuit evaluation
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resources without side effects, an...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function A(v As Boolean) As Boolean Console.WriteLine("a") Return v End Function   Function B(v As Boolean) As Boolean Console.WriteLine("b") Return v End Function   Sub Test(i As Boolean, j As Boolean) Console.WriteLine("{0} and {1} = {2} (ea...
Give a code snippet in #Visual_Basic_.NET Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes cons...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#R
R
hanoimove <- function(ndisks, from, to, via) { if (ndisks == 1) { cat("move disk from", from, "to", to, "\n") } else { hanoimove(ndisks - 1, from, via, to) hanoimove(1, from, to, via) hanoimove(ndisks - 1, via, to, from) } }   hanoimove(4, 1, 2, 3)
Give a code snippet in #R Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#Ring
Ring
  i = 1 while true see i + nl if i = 10 see "Break!" exit ok i = i + 1 end  
Give a code snippet in #Ring Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#PowerShell
PowerShell
#Declaring variables $intIterations = 10000 $intKept = 0 $intSwitched = 0   #Creating a function Function Play-MontyHall() { #Using a .NET object for randomization $objRandom = New-Object -TypeName System.Random   #Generating the winning door number $intWin = $objRandom.Next(1,4)   #Generating t...
Give a code snippet in #PowerShell Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed fo...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#Gambas
Gambas
'Altered to prevent lines starting with ']' or ending with '[' being generated as they can't work   siNumberOfBrackets As Short = 20 'Maximum amount of brackets in a line siNumberOfLines As Short = 20 'Amount of lines to test   '----   Public Sub Main() Dim sBrks As String[] = GenerateBrack...
Give a code snippet in #Gambas Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Smalltalk
Smalltalk
#(3 1 4 1 5 9) inject: 0 into: [:sum :aNumber | sum + aNumber squared]
Give a code snippet in #Smalltalk Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
christopher/rosetta-code
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua...
#Scala
Scala
scala> def if2[A](x: => Boolean)(y: => Boolean)(xyt: => A) = new { | def else1(xt: => A) = new { | def else2(yt: => A) = new { | def orElse(nt: => A) = { | if(x) { | if(y) xyt else xt | } else if(y) { | yt | } else { | ...
Give a code snippet in #Scala Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g....
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
varname = InputString["Enter a variable name"]; varvalue = InputString["Enter a value"]; ReleaseHold[ Hold[Set["nameholder", "value"]] /. {"nameholder" -> Symbol[varname], "value" -> varvalue}]; Print[varname, " is now set to ", Symbol[varname]]
Give a code snippet in #Mathematica_.2F_Wolfram_Language 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/Singleton
Singleton
A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
#JavaScript
JavaScript
function Singleton() { if(Singleton._instance) return Singleton._instance; this.set(""); Singleton._instance = this; }   Singleton.prototype.set = function(msg) { this.msg = msg; } Singleton.prototype.append = function(msg) { this.msg += msg; } Singleton.prototype.get = function() { return this.msg; }     var a = ne...
Give a code snippet in #JavaScript A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#AWK
AWK
BEGIN { a = "a string" b = a sub(/a/, "X", a) # modify a print b # b is a copy, not a reference to... }
Give a code snippet in #AWK This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty str...
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...
#11l
11l
fs:create_dirs(path)
Give a code snippet in #11l 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Set_of_real_numbers
Set of real numbers
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary: [a, b]: {x | a ≤ x and x ≤ b } (a, b): {x | ...
#C
C
#include <math.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h>   struct RealSet { bool(*contains)(struct RealSet*, struct RealSet*, double); struct RealSet *left; struct RealSet *right; double low, high; };   typedef enum { CLOSED, LEFT_OPEN, RIGHT_OPEN, BOTH_OPEN, } Range...
Give a code snippet in #C All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary: [a, b]: {x | a ≤ x...
christopher/rosetta-code
http://rosettacode.org/wiki/Pierpont_primes
Pierpont primes
A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the first definition, but will be c...
#Go
Go
package main   import ( "fmt" big "github.com/ncw/gmp" "sort" )   var ( one = new(big.Int).SetUint64(1) two = new(big.Int).SetUint64(2) three = new(big.Int).SetUint64(3) )   func pierpont(ulim, vlim int, first bool) []*big.Int { p := new(big.Int) p2 := new(big.Int).Set(one) p3 :=...
Give a code snippet in #Go A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the fir...
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. ...
#LiveCode
LiveCode
set the defaultFolder to the documents folder -- the documents folder is a "specialFolderPath" put the files into docfiles filter docfiles with "*.txt" put docfiles
Give a code snippet in #LiveCode 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 director...
christopher/rosetta-code
http://rosettacode.org/wiki/Top_rank_per_group
Top rank per group
Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
InitialList ={{"Tyler Bennett","E10297",32000,"D101"}, {"John Rappl","E21437",47000,"D050"},{"George Woltman","E00127",53500,"D101"}, {"Adam Smith","E63535",18000,"D202"},{"Claire Buckman","E39876",27800,"D202"}, {"David McClellan","E04242",41500,"D101"},{"Rich Holcomb","E01234",49500,"D202"}, {"Nathan Adams","E41298",...
Give a code snippet in #Mathematica.2FWolfram_Language Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: E...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the...
#REXX
REXX
/*REXX program verifies that all characters in a string are all the same (character). */ @chr= ' [character' /* define a literal used for SAY.*/ @all= 'all the same character for string (length' /* " " " " " " */ @.= ...
Give a code snippet in #REXX Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each s...
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...
#Tcl
Tcl
set ary [subst [lrepeat 10 [lrepeat 5 {[expr int(rand()*20+1)]}]]]   try { foreach row $ary { foreach col $row { puts -nonewline [format %3s $col] if {$col == 20} { throw MULTIBREAK "we're done" } } puts , } } trap MULTIBREAK {} {} puts...
Give a code snippet in #Tcl 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/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#GAP
GAP
Catalan1 := n -> Binomial(2*n, n) - Binomial(2*n, n - 1);   Catalan2 := n -> Binomial(2*n, n)/(n + 1);   Catalan3 := function(n) local k, c; c := 1; k := 0; while k < n do k := k + 1; c := 2*(2*k - 1)*c/(k + 1); od; return c; end;   Catalan4_memo := [1]; Catalan4 := function(n) ...
Give a code snippet in #GAP Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  fo...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at uni...
#Perl
Perl
sub deranged { # only anagrams ever get here my @a = split('', shift); # split word into letters my @b = split('', shift); for (0 .. $#a) { $a[$_] eq $b[$_] and return; } return 1 }   sub find_deranged { for my $i ( 0 .....
Give a code snippet in #Perl Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Logtalk
Logtalk
:- object(bottles).   :- initialization(sing(99)).   sing(0) :- write('No more bottles of beer on the wall, no more bottles of beer.'), nl, write('Go to the store and buy some more, 99 bottles of beer on the wall.'), nl, nl. sing(N) :- N > 0, N2 is N -1, beers(N), wri...
Give a code snippet in #Logtalk Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall ...
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...
#JAMES_II.2FRule-based_Cellular_Automata
JAMES II/Rule-based Cellular Automata
@caversion 1;   dimensions 2;   //using Moore neighborhood neighborhood moore;   //available states state DEAD, ALIVE;   /* if current state is ALIVE and the neighborhood does not contain 2 or 3 ALIVE states the cell changes to DEAD */ rule{ALIVE}:!ALIVE{2,3}->DEAD;   /* if current state is DEAD and there are...
Give a code snippet in #JAMES_II.2FRule-based_Cellular_Automata 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   w...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_ternary
Balanced ternary
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0" ...
#OCaml
OCaml
type btdigit = Pos | Zero | Neg type btern = btdigit list   let to_string n = String.concat "" (List.rev_map (function Pos -> "+" | Zero -> "0" | Neg -> "-") n)   let from_string s = let sl = ref [] in let digit = function '+' -> Pos | '-' -> Neg | '0' -> Zero | _ -> failwith "invalid digit" in ...
Give a code snippet in #OCaml Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, t...
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#Ring
Ring
  load "guilib.ring"   new qapp { win1 = new qwidget() { setwindowtitle("drawing using qpainter") setwinicon(self,"C:\Ring\bin\image\browser.png") setgeometry(100,100,500,600) label1 = new qlabel(win1) { setgeometry(10,...
Give a code snippet in #Ring Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#Hoon
Hoon
|= [arr=(list @ud) x=@ud] =/ lo=@ud 0 =/ hi=@ud (dec (lent arr)) |- ?> (lte lo hi) =/ mid (div (add lo hi) 2) =/ val (snag mid arr) ?: (lth x val) $(hi (dec mid)) ?: (gth x val) $(lo +(mid)) mid
Give a code snippet in #Hoon A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Bin_given_limits
Bin given limits
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] ...
#REXX
REXX
/*REXX program counts how many numbers of a set that fall in the range of each bin. */ lims= 23 37 43 53 67 83 /* ◄■■■■■■1st set of bin limits & data.*/ data= 95 21 94 12 99 4 70 75 83 93 52 80 57 5 53 86 65 17 92 83 71 61 54 58 47 , 16 8 9 32 84 7 87 46 19 30 37 96 6 98 40 79 97 45 ...
Give a code snippet in #REXX You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs ar...
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Luhn is   function Luhn_Test (Number: String) return Boolean is Sum  : Natural := 0; Odd  : Boolean := True; Digit: Natural range 0 .. 9; begin for p in reverse Number'Range loop Digit := Integer'Value (Number (p..p)); if Odd then S...
Give a code snippet in #Ada The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of t...
christopher/rosetta-code
http://rosettacode.org/wiki/Ternary_logic
Ternary logic
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In logic, a three-valued logic (also trivalent, ternary, or trinary...
#Icon_and_Unicon
Icon and Unicon
$define TRUE 1 $define FALSE -1 $define UNKNOWN 0   invocable all link printf   procedure main() # demonstrate ternary logic   ufunc := ["not3"] bfunc := ["and3", "or3", "xor3", "eq3", "ifthen3"]   every f := !ufunc do { # display unary functions printf("\nunary function=%s:\n",f) every t1 := (TRUE | FAL...
Give a code snippet in #Icon_and_Unicon This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In logic, a three-valued l...
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 ...
#Oforth
Oforth
aBoolean ifTrue: [ ...] aBoolean ifFalse: [ ... ] aObject ifNull: [ ... ] aObject ifNotNull: [ ... ] aObject ifZero: [ ... ]
Give a code snippet in #Oforth 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/DNS_query
DNS query
DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
#REXX
REXX
/*REXX program displays IPV4 and IPV6 addresses for a supplied domain name.*/ parse arg tar . /*obtain optional domain name from C.L.*/ if tar=='' then tar= 'www.kame.net' /*Not specified? Then use the default.*/ tFID = '\TEMP\DNSQUERY.$$$' /*define temp file to store IPV4 outpu...
Give a code snippet in #REXX DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
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...
#LiveCode
LiveCode
repeat for each line txtln in fld "Fieldtxt" repeat with i = the number of words of txtln down to 1 put word i of txtln & space after txtrev end repeat put cr after txtrev -- preserve line end repeat put txtrev
Give a code snippet in #LiveCode 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/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#REALbasic
REALbasic
  Sub PrintArgs(ParamArray Args() As String) For i As Integer = 0 To Ubound(Args) Print(Args(i)) Next End Sub  
Give a code snippet in #REALbasic Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and computer science, the Levenshtein ...
#Io
Io
Io 20110905 Io> Range ; "kitten" levenshtein("sitting") ==> 3 Io> "rosettacode" levenshtein("raisethysword") ==> 8 Io>
Give a code snippet in #Io This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and comput...
christopher/rosetta-code
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120....
#JavaScript
JavaScript
(() => { 'use strict';   // attractiveNumbers :: () -> Gen [Int] const attractiveNumbers = () => // An infinite series of attractive numbers. filter( compose(isPrime, length, primeFactors) )(enumFrom(1));     // ----------------------- TEST ----------------------- ...
Give a code snippet in #JavaScript A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Ta...
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 |...
#Scala
Scala
object StringInterpolation extends App {   import util.matching.Regex._ val size = "little"   { // Method I (preferred) // Scala 2.10.0 supports direct string interpolation // by putting "s" at the beginning of the string. println("V2.10+  : " + s"Mary had a $size lamb,") }   { // Method II //...
Give a code snippet in #Scala 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/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#Erlang
Erlang
  1> [1, 2, 3] ++ [4, 5, 6]. [1,2,3,4,5,6] 2> lists:append([1, 2, 3], [4, 5, 6]). [1,2,3,4,5,6] 3>  
Give a code snippet in #Erlang Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program quickSort64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeConstantesAR...
Give a code snippet in #AArch64_Assembly 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_factors
Count in factors
Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would be shown as   2 × 3 {\di...
#Julia
Julia
using Primes, Printf function strfactor(n::Integer) n > -2 || return "-1 × " * strfactor(-n) isprime(n) || n < 2 && return dec(n) f = factor(Vector{typeof(n)}, n) return join(f, " × ") end   lo, hi = -4, 40 println("Factor print $lo to $hi:") for n in lo:hi @printf("%5d = %s\n", n, strfactor(n)) end
Give a code snippet in #Julia Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would...
christopher/rosetta-code
http://rosettacode.org/wiki/List_comprehensions
List comprehensions
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the use of map and filter functio...
#Raku
Raku
my $n = 20; gather for 1..$n -> $x { for $x..$n -> $y { for $y..$n -> $z { take $x,$y,$z if $x*$x + $y*$y == $z*$z; } } }
Give a code snippet in #Raku A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the...
christopher/rosetta-code
http://rosettacode.org/wiki/Intersecting_number_wheels
Intersecting number wheels
A number wheel has: A name which is an uppercase letter. A set of ordered values which are either numbers or names. A number is generated/yielded from a named wheel by: 1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel"...
#C.2B.2B
C++
#include <initializer_list> #include <iostream> #include <map> #include <vector>   struct Wheel { private: std::vector<char> values; size_t index;   public: Wheel() : index(0) { // empty }   Wheel(std::initializer_list<char> data) : values(data), index(0) { //values.assign(data); ...
Give a code snippet in #C.2B.2B A number wheel has: A name which is an uppercase letter. A set of ordered values which are either numbers or names. A number is generated/yielded from a named wheel by: 1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func begin writeln(fileType("input.txt") = FILE_REGULAR); writeln(fileType("/input.txt") = FILE_REGULAR); writeln(fileType("docs") = FILE_DIR); writeln(fileType("/docs") = FILE_DIR); end func;
Give a code snippet in #Seed7 Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works wit...
christopher/rosetta-code
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#Haskell
Haskell
matI n = [ [fromEnum $ i == j | i <- [1..n]] | j <- [1..n]]
Give a code snippet in #Haskell Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap ...
#D
D
void main() { import std.stdio, std.file, std.string, std.algorithm;   bool[string] seenWords; size_t pairCount = 0;   foreach (const word; "unixdict.txt".readText.toLower.splitter) { //const drow = word.dup.reverse(); auto drow = word.dup; drow.reverse(); if (drow in see...
Give a code snippet in #D A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#F.23
F#
[<EntryPoint>] let main argv = let fs = List.init 10 (fun i -> fun () -> i*i) do List.iter (fun f -> printfn "%d" <| f()) fs 0
Give a code snippet in #F.23 Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2....
christopher/rosetta-code
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Fantom
Fantom
  // create an enumeration with named constants enum class Fruits { apple, banana, orange }  
Give a code snippet in #Fantom Task Create an enumeration of constants with and without explicit values.
christopher/rosetta-code
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#CoffeeScript
CoffeeScript
  last_friday_of_month = (year, month) -> # month is 1-based, JS API is 0-based, then we use # non-positive indexes to work backward relative to the # first day of the next month i = 0 while true last_day = new Date(year, month, i) if last_day.getDay() == 5 return last_day.toDateString() i ...
Give a code snippet in #CoffeeScript Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-...
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#Sather
Sather
class MAIN is look_and_say!: STR is current ::= "1"; loop yield current; buf ::= #FSTR; last ::= current[0]; count ::= 0; loop ch ::= current.elt!; if ch /= last then buf := buf + count + last; last := ch; ...
Give a code snippet in #Sather The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequenc...
christopher/rosetta-code
http://rosettacode.org/wiki/String_comparison
String comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Apex
Apex
public class Compare { /** * Test in the developer console: * Compare.compare('Hello', 'Hello'); * Compare.compare('5', '5.0'); * Compare.compare('java', 'Java'); * Compare.compare('ĴÃVÁ', 'ĴÃVÁ'); */   public static void compare (String A, String B) { if (A.equals(B)) System.deb...
Give a code snippet in #Apex 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/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).
#Python
Python
>>> import json >>> data = json.loads('{ "foo": 1, "bar": [10, "apples"] }') >>> sample = { "blue": [1,2], "ocean": "water" } >>> json_string = json.dumps(sample) >>> json_string '{"blue": [1, 2], "ocean": "water"}' >>> sample {'blue': [1, 2], 'ocean': 'water'} >>> data {'foo': 1, 'bar': [10, 'apples']}
Give a code snippet in #Python 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/Averages/Simple_moving_average
Averages/Simple moving average
Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an avera...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) sma := buildSMA(3) # Use better name than "I". every write(sma(!A)) end   procedure buildSMA(P) local stream c := create { stream := [] while n := (avg@&source)[1] do { put(stream, n) if *stream > P then pop(stream) every (avg := 0.0) +...
Give a code snippet in #Icon_and_Unicon Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving a...
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)...
#Julia
Julia
using Images, FileIO   ppmimg = load("data/bitmapInputTest.ppm") save("data/bitmapOutputTest.jpg", ppmimg)
Give a code snippet in #Julia 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), ppmtoj...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
Find largest left truncatable prime in a given base
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2. Let's consider what happens in...
#Fortran
Fortran
USE PRIMEBAG !Gain access to NEXTPRIME and ISPRIME. Calculates the largest "left-truncatable" digit sequence that is a prime number, in various bases. INTEGER LBASE,MANY,ENUFF !Some sizes. PARAMETER (LBASE = 13, MANY = 66666, ENUFF = 66) INTEGER NS,START(LBASE) !A list of single-digit prime numb...
Give a code snippet in #Fortran A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2...
christopher/rosetta-code
http://rosettacode.org/wiki/World_Cup_group_stage
World Cup group stage
It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other internat...
#C
C
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h>   // to supply to qsort int compare(const void *a, const void *b) { int int_a = *((int *)a); int int_b = *((int *)b); return (int_a > int_b) - (int_a < int_b); }   char results[7]; bool next_result() { char *ptr = results + ...
Give a code snippet in #C It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their pe...
christopher/rosetta-code