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/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "image" "image/color" "image/png" "log" "os" "sync" )   func main() { const ( width, height = 800.0, 600.0 maxIter = 255 cX, cY = -0.7, 0.27015 fileName = "julia.png" ) img := image.NewNRGBA(image.Rect(0, 0, width, height))   var wg sync.WaitGroup wg.Add(widt...
Give a code snippet in #F.C5.8Drmul.C3.A6 Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
christopher/rosetta-code
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string
Selectively replace multiple instances of a character within a string
Task This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it. Given the string: "abracadabra", replace programatically: the first 'a' with 'A' the second 'a' with 'B' the fourth 'a' with 'C' the fifth 'a' with 'D' the first 'b...
#Phix
Phix
with javascript_semantics function replace_nth(string s, r) string res = s for i=1 to length(r) by 3 do res[find_all(r[i],s)[r[i+1]-'0']] = r[i+2] end for return res end function ?replace_nth("abracadabra","a1Aa2Ba4Ca5Db1Er2F") -- Alternative version function replace_nths(string s, sequence r) ...
Give a code snippet in #Phix Task This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it. Given the string: "abracadabra", replace programatically: the first 'a' with 'A' the second 'a' with 'B' the fourth 'a' with 'C' the fi...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Icon_and_Unicon
Icon and Unicon
procedure main() # a null file will compile but generate a run-time error for missing main end
Give a code snippet in #Icon_and_Unicon Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume t...
#D
D
import std.stdio, std.typecons, std.typetuple;   template integrate(alias method) { double integrate(F, Float)(in F f, in Float a, in Float b, in int steps) { double s = 0.0; immutable double h = (b - a) / steps; foreach (i; 0 .. steps) s += method(...
Give a code snippet in #D Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make i...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Raku
Raku
class Pixel { has UInt ($.R, $.G, $.B) } class Bitmap { has UInt ($.width, $.height); has Pixel @.data; }   role PGM { has @.GS; method P5 returns Blob { "P5\n{self.width} {self.height}\n255\n".encode('ascii') ~ Blob.new: self.GS } }   sub load-ppm ( $ppm ) { my $fh = $ppm.IO.open( :enc('IS...
Give a code snippet in #Raku Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to graysca...
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.
#Nemerle
Nemerle
using System.Console; using Nemerle.Collections;   module ArrayCat { Main() : void { def arr1 = array[1, 2, 3]; def arr2 = array[4, 5, 6]; def arr12 = arr1.Append(arr2); // <---- foreach (i in arr12) Write($"$i "); } }
Give a code snippet in #Nemerle 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/Eertree
Eertree
An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the string "eertree", then outp...
#REXX
REXX
/*REXX program creates a list of (unique) sub─palindromes that exist in an input string.*/ parse arg x . /*obtain optional input string from CL.*/ if x=='' | x=="," then x= 'eertree' /*Not specified? Then use the default.*/ L= length(x) ...
Give a code snippet in #REXX An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for t...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion
Singly-linked list/Element insertion
Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Trav...
#REXX
REXX
/*REXX program demonstrates how to create and show a single-linked list.*/ @.=0 /*define a null linked list. */ call set@ 3 /*linked list: 12 Proth primes. */ call set@ 5 call set@ 13 call set@ 17 call set@ 41 call set@ 97 call set@ 113 call set@ 193 cal...
Give a code snippet in #REXX Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition...
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
#Logtalk
Logtalk
os::shell('ls -a').
Give a code snippet in #Logtalk 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/Solve_the_no_connection_puzzle
Solve the no connection puzzle
You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/ G H You ar...
#JavaScript
JavaScript
(() => { 'use strict';   // -------------- NO CONNECTION PUZZLE ---------------   // solvedPuzzle :: () -> [Int] const solvedPuzzle = () => {   // universe :: [[Int]] const universe = permutations(enumFromTo(1)(8));   // isSolution :: [Int] -> Bool const isSolution = ([a,...
Give a code snippet in #JavaScript You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / ...
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...
#11l
11l
V guyprefers = [‘abe’ = [‘abi’, ‘eve’, ‘cath’, ‘ivy’, ‘jan’, ‘dee’, ‘fay’, ‘bea’, ‘hope’, ‘gay’], ‘bob’ = [‘cath’, ‘hope’, ‘abi’, ‘dee’, ‘eve’, ‘fay’, ‘bea’, ‘jan’, ‘ivy’, ‘gay’], ‘col’ = [‘hope’, ‘eve’, ‘abi’, ‘dee’, ‘bea’, ‘fay’, ‘ivy’, ‘gay’, ‘cath’, ‘jan’], ‘dan’ = [‘...
Give a code snippet in #11l 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Visual_Basic
Visual Basic
  Public Function IsLeapYear1(ByVal theYear As Integer) As Boolean 'this function utilizes documented behaviour of the built-in DateSerial function IsLeapYear1 = (VBA.Day(VBA.DateSerial(theYear, 2, 29)) = 29) End Function   Public Function IsLeapYear2(ByVal theYear As Integer) As Boolean 'this function uses the well-kn...
Give a code snippet in #Visual_Basic Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Dimensions
Terminal control/Dimensions
Determine the height and width of the terminal, and store this information into variables for subsequent use.
#Python
Python
import os   def get_windows_terminal(): from ctypes import windll, create_string_buffer h = windll.kernel32.GetStdHandle(-12) csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)   #return default size if actual size can't be determined if not res: return 80,...
Give a code snippet in #Python Determine the height and width of the terminal, and store this information into variables for subsequent use.
christopher/rosetta-code
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the...
#Visual_Basic_.NET
Visual Basic .NET
Imports System Imports System.Numerics Imports System.Text   Module Module1 Sub Main() Dim n As BigInteger = BigInteger.Parse("9516311845790656153499716760847001433441357") Dim e As BigInteger = 65537 Dim d As BigInteger = BigInteger.Parse("5617843187844953170308463622230283376298685") ...
Give a code snippet in #Visual_Basic_.NET Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type o...
christopher/rosetta-code
http://rosettacode.org/wiki/ISBN13_check_digit
ISBN13 check digit
Task Validate the check digit of an ISBN-13 code:   Multiply every other digit by  3.   Add these numbers and the other digits.   Take the remainder of this number after division by  10.   If it is  0,   the ISBN-13 check digit is correct. Use the following codes for testing:   978-1734314502       (good)   ...
#Pascal
Pascal
program ISBNChecksum(output);   const codeIndexMaximum = 17; ISBNIndexMinimum = 1; ISBNIndexMaximum = 13; ISBNIndexRange = ISBNIndexMaximum - ISBNIndexMinimum + 1;   type code = string(codeIndexMaximum); codeIndex = 1..codeIndexMaximum value 1; decimalDigit = '0'..'9'; decimalValue = 0..9; ISBNIndex = ISBNInde...
Give a code snippet in #Pascal Task Validate the check digit of an ISBN-13 code:   Multiply every other digit by  3.   Add these numbers and the other digits.   Take the remainder of this number after division by  10.   If it is  0,   the ISBN-13 check digit is correct. Use the following codes for testing:  ...
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...
#Tcl
Tcl
set Q [list] empty Q ;# ==> 1 (true) push Q foo empty Q ;# ==> 0 (false) push Q bar peek Q ;# ==> foo pop Q ;# ==> foo peek Q ;# ==> bar
Give a code snippet in #Tcl 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 queue...
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see...
#Clojure
Clojure
(def ^:dynamic x nil)   (defn eval-with-x [program a b] (- (binding [x b] (eval program)) (binding [x a] (eval program))))
Give a code snippet in #Clojure x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples a...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Forth
Forth
defer less? ' < is less?   : least ( start end -- least ) over cell+ do i @ over @ less? if drop i then cell +loop ; : selection ( array len -- ) cells over + tuck ( end start end ) cell- swap do ( end ) i over least ( end least ) i @ over @ i ! swap ! cell +loop drop ;   create array 8 , 1 , ...
Give a code snippet in #Forth Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick so...
christopher/rosetta-code
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
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 |...
#Lua
Lua
local table1 = {1,2,3} local table2 = table1 table2[3] = 4 print(unpack(table1))
Give a code snippet in #Lua Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#jq
jq
def subarray_sum: . as $arr | reduce range(0; length) as $i ( {"first": length, "last": 0, "curr": 0, "curr_first": 0, "max": 0}; $arr[$i] as $e | (.curr + $e) as $curr | . + (if $e > $curr then {"curr": $e, "curr_first": $i} else {"curr": $curr} end) | if .curr > .max then . +...
Give a code snippet in #jq Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are neg...
christopher/rosetta-code
http://rosettacode.org/wiki/Polyspiral
Polyspiral
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the b...
#C.23
C#
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Windows.Threading;   namespace Polyspiral { public partial class Form1 : Form { private double inc;   public Form1() { Width = Height = 640; StartPosition ...
Give a code snippet in #C.23 A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the an...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#VBScript
VBScript
  'permutation ,recursive a=array("Hello",1,True,3.141592) cnt=0 perm a,0 wscript.echo vbcrlf &"Count " & cnt   sub print(a) s="" for i=0 to ubound(a): s=s &" " & a(i): next: wscript.echo s : cnt=cnt+1 : end sub sub swap(a,b) t=a: a=b :b=t: end sub   sub perm(byval a,i) if i=ubound(a) then print a: ...
Give a code snippet in #VBScript Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   g...
christopher/rosetta-code
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#ACL2
ACL2
(defun increment-alist (tbl key) (cond ((endp tbl) (list (cons key 1))) ((eql (car (first tbl)) key) (cons (cons key (1+ (cdr (first tbl)))) (rest tbl))) (t (cons (first tbl) (increment-alist (rest tbl) key)))))   (defun freq-table (xs) (if (endp xs) ...
Give a code snippet in #ACL2 Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assi...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is s...
#C.23
C#
  using System.Text.RegularExpressions;   string RemoveComments(string str, string delimiter) { //regular expression to find a character (delimiter) and // replace it and everything following it with an empty string. //.Trim() will remove all beginning and ending white ...
Give a code snippet in #C.23 Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Wh...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Common_Lisp
Common Lisp
(defun cocktail-sort-vector (vector predicate &aux (len (length vector))) (labels ((scan (start step &aux swapped) (loop for i = start then (+ i step) while (< 0 i len) do (when (funcall predicate (aref vector i) (aref vector (1- i))) ...
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/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Pascal
Pascal
clrscr;
Give a code snippet in #Pascal Task Clear the terminal window.
christopher/rosetta-code
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#Objeck
Objeck
class Fasta { function : Main(args : String[]) ~ Nil { if(args->Size() = 1) { is_line := false; tokens := System.Utility.Parser->Tokenize(System.IO.File.FileReader->ReadFile(args[0]))<String>; each(i : tokens) { token := tokens->Get(i); if(token->Get(0) = '>') { i...
Give a code snippet in #Objeck In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rose...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#MIPS_Assembly
MIPS Assembly
  .text main: li $v0, 5 # read integer from input. The read integer will be stroed in $v0 syscall   beq $v0, 0, is1 beq $v0, 1, is1   li $s4, 1 # the counter which has to equal to $v0   li $s0, 1 li $s1, 1   loop: add $s2, $s0, $s1 addi $s4, $s4, 1 beq $v0, $s4, iss2   add $s0, $s1, $s2 addi $s4, $s4, 1 ...
Give a code snippet in #MIPS_Assembly The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solut...
christopher/rosetta-code
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the defin...
#Scala
Scala
object StrongWeakPrimes { def main(args: Array[String]): Unit = { val bnd = 1000000 println( f"""|First 36 Strong Primes: ${strongPrimes.take(36).map(n => f"$n%,d").mkString(", ")} |Strong Primes < 1,000,000: ${strongPrimes.takeWhile(_ < bnd).size}%,d |Strong Primes < 10,000,000: ${s...
Give a code snippet in #Scala Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#Arturo
Arturo
define :point [x,y][] define :line [a, b][ init: [ this\slope: div this\b\y-this\a\y this\b\x-this\a\x this\yInt: this\a\y - this\slope*this\a\x ] ]   evalX: function [line, x][ line\yInt + line\slope * x ]   intersect: function [line1, line2][ x: div line2\yInt-line1\yInt line1\slope-li...
Give a code snippet in #Arturo [1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
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 ) ) , ...
#Aime
Aime
integer F(integer n); integer M(integer n);   integer F(integer n) { integer r; if (n) { r = n - M(F(n - 1)); } else { r = 1; } return r; }   integer M(integer n) { integer r; if (n) { r = n - F(M(n - 1)); } else { r = 0; } return r; }   integer main(void) { integer i; ...
Give a code snippet in #Aime 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/Parallel_calculations
Parallel calculations
Many programming languages allow you to specify computations to be run in parallel. While Concurrent computing is focused on concurrency, the purpose of this task is to distribute time-consuming calculations on as many CPUs as possible. Assume we have a collection of numbers, and want to find the one with the largest ...
#Swift
Swift
import BigInt import Foundation   extension BinaryInteger { @inlinable public func primeDecomposition() -> [Self] { guard self > 1 else { return [] }   func step(_ x: Self) -> Self { return 1 + (x << 2) - ((x >> 1) << 1) }   let maxQ = Self(Double(self).squareRoot()) var d: Self = 1 va...
Give a code snippet in #Swift Many programming languages allow you to specify computations to be run in parallel. While Concurrent computing is focused on concurrency, the purpose of this task is to distribute time-consuming calculations on as many CPUs as possible. Assume we have a collection of numbers, and want to...
christopher/rosetta-code
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#Joy
Joy
fib == [small] [] [pred dup pred] [+] binrec;
Give a code snippet in #Joy While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Clojure
Clojure
(ns anthony.random.hq9plus (:require [clojure.string :as str]))   (defn bottles [] (loop [bottle 99] (if (== bottle 0) () (do (println (str bottle " bottles of beer on the wall")) (println (str bottle " bottles of beer")) (println "Take one down, pass it around") (pri...
Give a code snippet in #Clojure Task Implement a   HQ9+   interpreter or compiler.
christopher/rosetta-code
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#C.23
C#
public int[,] Spiral(int n) { int[,] result = new int[n, n];   int pos = 0; int count = n; int value = -n; int sum = -1;   do { value = -1 * value / n; for (int i = 0; i < count; i++) { sum += value; result[sum / n, sum % n] = pos++; } valu...
Give a code snippet in #C.23 Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Julia
Julia
s = "I am a string" if ismatch(r"string$", s) println("'$s' ends with 'string'") end
Give a code snippet in #Julia Task   match a string against a regular expression   substitute part of a string using a regular expression
christopher/rosetta-code
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
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 |...
#Julia
Julia
s = "niño" println("Position Char Bytes\n==============================") for (i, c) in enumerate(s) println("$i $c $(sizeof(c))") end  
Give a code snippet in #Julia 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/Tau_function
Tau function
Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
#Verilog
Verilog
module main; integer N, T, A;   initial begin $display("The tau functions for the first 100 positive integers are:\n"); for (N = 1; N <= 100; N=N+1) begin if (N < 3) T = N; else begin T = 2; for (A = 2; A <= (N+1)/2; A=A+1) begin if (N % A == 0) T = T ...
Give a code snippet in #Verilog Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#GAP
GAP
gap>List(SymmetricGroup(4), p -> Permuted([1 .. 4], p)); perms(4); [ [ 1, 2, 3, 4 ], [ 4, 2, 3, 1 ], [ 2, 4, 3, 1 ], [ 3, 2, 4, 1 ], [ 1, 4, 3, 2 ], [ 4, 1, 3, 2 ], [ 2, 1, 3, 4 ], [ 3, 1, 4, 2 ], [ 1, 3, 4, 2 ], [ 4, 3, 1, 2 ], [ 2, 3, 1, 4 ], [ 3, 4, 1, 2 ], [ 1, 2, 4, 3 ], [ 4, 2, 1, 3 ], [ 2, 4, 1, 3 ], [ 3, 2,...
Give a code snippet in #GAP Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   genera...
christopher/rosetta-code
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#D
D
import std.stdio, std.math, std.mathspecial;   real taylorGamma(in real x) pure nothrow @safe @nogc { static immutable real[30] table = [ 0x1p+0, 0x1.2788cfc6fb618f4cp-1, -0x1.4fcf4026afa2dcecp-1, -0x1.5815e8fa27047c8cp-5, 0x1.5512320b43fbe5dep-3, -0x1.59af103c340927bep-5, -0x...
Give a code snippet in #D Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The ...
#Delphi
Delphi
type Expr = Bin(op, Expr left, Expr right) or Literal(Float val) with Lookup   type Token(val, Char kind) with Lookup func Token.ToString() => this.val.ToString()   func tokenize(str) { func isSep(c) => c is '+' or '-' or '*' or '/' or ' ' or '\t' or '\n' or '\r' or '(' or ')' or '\0'   var idx = -1...
Give a code snippet in #Delphi Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a s...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTPS/Client-authenticated
HTTPS/Client-authenticated
Demonstrate how to connect to a web server over HTTPS where that server requires that the client present a certificate to prove who (s)he is. Unlike with the HTTPS request with authentication task, it is not acceptable to perform the authentication by a username/password or a set cookie. This task is in general useful...
#Python
Python
import httplib   connection = httplib.HTTPSConnection('www.example.com',cert_file='myCert.PEM') connection.request('GET','/index.html') response = connection.getresponse() data = response.read()  
Give a code snippet in #Python Demonstrate how to connect to a web server over HTTPS where that server requires that the client present a certificate to prove who (s)he is. Unlike with the HTTPS request with authentication task, it is not acceptable to perform the authentication by a username/password or a set cookie....
christopher/rosetta-code
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-bla...
#Oz
Oz
fun {Balance Col A X B} case Col#A#X#B of b#t(r t(r A X B) Y C )#Z#D then t(r t(b A X B) Y t(b C Z D)) [] b#t(r A X t(r B Y C))#Z#D then t(r t(b A X B) Y t(b C Z D)) [] b#A #X#t(r t(r B Y C) Z D) then t...
Give a code snippet in #Oz Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, impl...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /...
#Run_BASIC
Run BASIC
' ------------------------------------------------------------------------ 'XMLPARSER methods   '#handle ELEMENTCOUNT() - Return the number of child XML elements '#handle KEY$() - Return the key as a string from an XML expression like <key>value</key> '#handle VALUE$() - Return the value as a string from an XML expre...
Give a code snippet in #Run_BASIC Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gen...
christopher/rosetta-code
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Python
Python
  m='0' print(m) for i in range(0,6): m0=m m=m.replace('0','a') m=m.replace('1','0') m=m.replace('a','1') m=m0+m print(m)  
Give a code snippet in #Python Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
christopher/rosetta-code
http://rosettacode.org/wiki/Date_manipulation
Date manipulation
Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
#Ruby
Ruby
require 'time' d = "March 7 2009 7:30pm EST" t = Time.parse(d) puts t.rfc2822 puts t.zone   new = t + 12*3600 puts new.rfc2822 puts new.zone   # another timezone require 'rubygems' require 'active_support' zone = ActiveSupport::TimeZone['Beijing'] remote = zone.at(new) # or, remote = new.in_time_zone('Beijing') puts re...
Give a code snippet in #Ruby Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) t...
#CLU
CLU
magic_square = cluster is create, unparse, magic_number rep = array[array[int]]   create = proc (order: int) returns (cvt) signals (invalid) if order<1 cor order//2 = 0 then signal invalid end sq: rep := rep$fill_copy(1, order, array[int]$fill(1, order, 0)) x: int := (order+1)/2 ...
Give a code snippet in #CLU A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers a...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#AWK
AWK
# syntax: GAWK -f DIGITAL_ROOT.AWK BEGIN { n = split("627615,39390,588225,393900588225,10,199",arr,",") for (i=1; i<=n; i++) { dr = digitalroot(arr[i],10) printf("%12.0f has additive persistence %d and digital root of %d\n",arr[i],p,dr) } exit(0) } function digitalroot(n,b) { p = 0 # glo...
Give a code snippet in #AWK The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , re...
christopher/rosetta-code
http://rosettacode.org/wiki/Statistics/Normal_distribution
Statistics/Normal distribution
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random number generator and create a ...
#Julia
Julia
using Printf, Distributions, Gadfly   data = rand(Normal(0, 1), 1000) @printf("N = %i\n", length(data)) @printf("μ = %2.2f\tσ = %2.2f\n", mean(data), std(data)) @printf("range = (%2.2f, %2.2f\n)", minimum(data), maximum(data)) h = plot(x=data, Geom.histogram) draw(PNG("norm_hist.png", 10cm, 10cm), h)
Give a code snippet in #Julia The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random...
christopher/rosetta-code
http://rosettacode.org/wiki/EKG_sequence_convergence
EKG sequence convergence
The sequence is from the natural numbers and is defined by: a(1) = 1; a(2) = Start = 2; for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used. The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed)....
#XPL0
XPL0
int N, A(1+30);   func Used; int M; \Return 'true' if M is in array A int I; [for I:= 1 to N-1 do if M = A(I) then return true; return false; ];   func MinFactor; int Num; \Return minimum unused factor int Fac, Val, Min; [Fac:= 2; Min:= -1>>1; repeat if rem(Num/Fac) = 0 then \found a factor ...
Give a code snippet in #XPL0 The sequence is from the natural numbers and is defined by: a(1) = 1; a(2) = Start = 2; for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used. The sequence is called the EKG sequence (after its visual similarity to an el...
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"
#Raku
Raku
# with arguments supplied $ raku -e 'sub MAIN($x, $y) { say $x + $y }' 3 5 8   # missing argument: $ raku -e 'sub MAIN($x, $y) { say $x + $y }' 3 Usage: -e '...' x y
Give a code snippet in #Raku 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/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#C
C
#include <stdbool.h> #include <string.h>   static bool strings_are_equal(const char **strings, size_t nstrings) { for (size_t i = 1; i < nstrings; i++) if (strcmp(strings[0], strings[i]) != 0) return false; return true; }   static bool strings_are_in_ascending_order(const char **strings, siz...
Give a code snippet in #C Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false valu...
christopher/rosetta-code
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbe...
#Quackery
Quackery
1000000 eratosthenes   [ [] swap [ dup 0 != while 10 /mod rot swap join swap again ] swap witheach [ dip [ 10 * ] + ] ] is revnum ( n --> n )   [ dup isprime not iff [ drop false ] done dup revnum tuck = iff [ drop false ] done isprime ] is...
Give a code snippet in #Quackery An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th...
christopher/rosetta-code
http://rosettacode.org/wiki/OpenGL
OpenGL
Task Display a smooth shaded triangle with OpenGL. Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
#Euphoria
Euphoria
  include get.e include dll.e include machine.e include msgbox.e include constants.ew include GLfunc.ew include GLconst.ew   without warning   atom hRC, hDC, hWnd, hInstance, ClassName sequence keys keys = repeat(0,256) -- array to hold key presses   integer active, fullscreen, retval active = TRUE fullscreen = TRUE h...
Give a code snippet in #Euphoria Task Display a smooth shaded triangle with OpenGL. Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Suneido
Suneido
function () { }
Give a code snippet in #Suneido Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/1
Text processing/1
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another pr...
#Icon_and_Unicon
Icon and Unicon
record badrun(count,fromdate,todate) # record to track bad runs   procedure main() return mungetask1("readings1-input.txt","readings1-output.txt") end   procedure mungetask1(fin,fout)   fin := open(fin) | stop("Unable to open input file ",fin) fout := open(fout,"w") | stop("Unable to open output file ",fout)   F...
Give a code snippet in #Icon_and_Unicon This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Often data is produced by one program, in the wrong format for later use by another program ...
christopher/rosetta-code
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#SIMPOL
SIMPOL
type mypoint embed integer x integer y end type
Give a code snippet in #SIMPOL Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. ...
christopher/rosetta-code
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' Apostrophes NOT used as incorrect English   Function ordinal(n As UInteger) As String Dim ns As String = Str(n) Select Case Right(ns, 1) Case "0", "4" To "9" Return ns + "th" Case "1" If Right(ns, 2) = "11" Then Return ns + "th" Return ns + "st" Case "2" If...
Give a code snippet in #FreeBASIC Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#AutoHotkey
AutoHotkey
; By Uberi, http://www.autohotkey.com/board/topic/58599-turing-machine/ SetBatchLines, -1 OnExit, Exit SaveFilePath := A_ScriptFullPath ".ini" ; Defaults are for a 2-state_3-symbol turning machine. Format: ; machine state symbol on tape, symbol on tape | tape shift (- is left, + is right, 0 is halt) | machine state , R...
Give a code snippet in #AutoHotkey One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing ma...
christopher/rosetta-code
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#Python
Python
majors = 'north east south west'.split() majors *= 2 # no need for modulo later quarter1 = 'N,N by E,N-NE,NE by N,NE,NE by E,E-NE,E by N'.split(',') quarter2 = [p.replace('NE','EN') for p in quarter1]   def degrees2compasspoint(d): d = (d % 360) + 360/64 majorindex, minor = divmod(d, 90.) majorindex = i...
Give a code snippet in #Python There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and d...
christopher/rosetta-code
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the la...
#Kotlin
Kotlin
// Version 1.2.31   import java.io.Serializable import java.io.ByteArrayOutputStream import java.io.ByteArrayInputStream import java.io.ObjectOutputStream import java.io.ObjectInputStream   fun <T : Serializable> deepCopy(obj: T?): T? { if (obj == null) return null val baos = ByteArrayOutputStream() val oos...
Give a code snippet in #Kotlin Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this f...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#F.23
F#
  open System   let multTable () = Console.Write (" X".PadRight (4)) for i = 1 to 12 do Console.Write ((i.ToString "####").PadLeft 4) Console.Write "\n ___" for i = 1 to 12 do Console.Write " ___" Console.WriteLine () for row = 1 to 12 do Console.Write (row.ToString("###").PadLeft(3).Pad...
Give a code snippet in #F.23 Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
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 ...
#MAXScript
MAXScript
fn notSorted arr = ( if arr.count > 0 then ( local current = arr[1] for i in 2 to arr.count do ( if current > arr[i] then ( return true ) current = arr[i] ) ) false )   fn randSort x y = ( random -1 1 )  ...
Give a code snippet in #MAXScript 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 | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Logical_operations
Logical operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Toka
Toka
[ 0 <> [ ." true" ] [ ." false"] ifTrueFalse ] is .bool [ ( a b -- ) cr ." a = " over .bool ." b = " dup .bool cr ." a and b = " 2dup and .bool cr ." a or b = " over or .bool cr ." not a = " 0 = .bool ] is logic
Give a code snippet in #Toka 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/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#Haskell
Haskell
import Data.List (intercalate)   data DayOfWeek = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday deriving (Eq, Show)   -- the whole thing bases upon an infinite list of weeks   daysFrom1_1_1900 :: [DayOfWeek] daysFrom1_1_1900 = concat $ repeat [Monday, Tuesday, Wednesday, Thursday, Fri...
Give a code snippet in #Haskell The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (th...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#C.2B.2B
C++
#include <map> #include <vector> #include <iostream> #include <fstream> #include <utility> #include <functional> #include <string> #include <sstream> #include <algorithm> #include <cctype>   class CSV { public: CSV(void) : m_nCols( 0 ), m_nRows( 0 ) {}   bool open( const char* filename, char delim = ',' ) ...
Give a code snippet in #C.2B.2B CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, ch...
christopher/rosetta-code
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#Raku
Raku
sub fib($n) { die "Naughty fib" if $n < 0; return { $_ < 2 ?? $_ !! &?BLOCK($_-1) + &?BLOCK($_-2); }($n); }   say fib(10);
Give a code snippet in #Raku While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwante...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_join
Hash join
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash join" algorithm, and demonstrate tha...
#AppleScript
AppleScript
use framework "Foundation" -- Yosemite onwards, for record-handling functions   -- HASH JOIN -----------------------------------------------------------------   -- hashJoin :: [Record] -> [Record] -> String -> [Record] on hashJoin(tblA, tblB, strJoin) set {jA, jB} to splitOn("=", strJoin)   script instanceOfjB ...
Give a code snippet in #AppleScript An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Befunge
Befunge
52*"!dlroW ,olleH">:#,_@
Give a code snippet in #Befunge Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error...
christopher/rosetta-code
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. 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) The haversine formula is an equation important in navigation, g...
#Excel
Excel
HAVERSINE =LAMBDA(lla, LAMBDA(llb, LET( REM, "Approximate radius of Earth in km.", earthRadius, 6372.8,   sinHalfDeltaSquared, LAMBDA(x, SIN(x / 2) ^ 2)( RADIANS(llb - lla) ),   2 * earthRadius * ASIN( SQRT( ...
Give a code snippet in #Excel This page uses content from Wikipedia. The original article was at Haversine formula. 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) The haversine formula is an equa...
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"...
#Perl
Perl
use strict; use warnings; use feature 'say';   sub get_next { my($w,%wheels) = @_; my $wh = \@{$wheels{$w}}; # reference, not a copy my $value = $$wh[0][$$wh[1]]; $$wh[1] = ($$wh[1]+1) % @{$$wh[0]}; defined $wheels{$value} ? get_next($value,%wheels) : $value; }   sub spin_wheels { my(%wheels) = ...
Give a code snippet in #Perl 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#C.23
C#
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { //Use a streamwriter to write the text part of the encoding var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitm...
Give a code snippet in #C.23 Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
christopher/rosetta-code
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The follow...
#CoffeeScript
CoffeeScript
  gray_encode = (n) -> n ^ (n >> 1)   gray_decode = (g) -> n = g n ^= g while g >>= 1 n   for i in [0..32] console.log gray_decode gray_encode(i)  
Give a code snippet in #CoffeeScript Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There ar...
christopher/rosetta-code
http://rosettacode.org/wiki/Cramer%27s_rule
Cramer's rule
linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1...
#Racket
Racket
#lang typed/racket (require math/matrix)   (define A (matrix [[2 -1 5 1] [3 2 2 -6] [1 3 3 -1] [5 -2 -3 3]]))   (define B (col-matrix [ -3 -32 -47 49]))   (matrix->vector (matrix-solve A...
Give a code snippet in #Racket linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#Sidef
Sidef
var s = ""; var s = String.new;
Give a code snippet in #Sidef Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Oth...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Terra
Terra
C = terralib.includec("stdio.h")   terra hello(argc : int, argv : &rawstring) C.printf("Hello world!\n") return 0 end
Give a code snippet in #Terra Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error ...
christopher/rosetta-code
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion
Angles (geometric), normalization and conversion
This task is about the normalization and/or conversion of (geometric) angles using some common scales. The angular scales that will be used in this task are:   degree   gradian   mil   radian Definitions The angular scales used or referenced here:   turn   is a full turn or 360 degrees, also shown as 360º ...
#Delphi
Delphi
  program normalization_and_conversion;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Math;   function d2d(d: double): double; begin result := FMod(d, 360); end;   function g2g(g: double): double; begin result := FMod(g, 400); end;   function m2m(m: double): double; begin result := FMod(m, 6400); end;  ...
Give a code snippet in #Delphi This task is about the normalization and/or conversion of (geometric) angles using some common scales. The angular scales that will be used in this task are:   degree   gradian   mil   radian Definitions The angular scales used or referenced here:   turn   is a full turn or ...
christopher/rosetta-code
http://rosettacode.org/wiki/Inheritance/Multiple
Inheritance/Multiple
Multiple inheritance allows to specify that one class is a subclass of several other classes. Some languages allow multiple inheritance for arbitrary classes,   others restrict it to interfaces,   some don't allow it at all. Task Write two classes (or interfaces) Camera and MobilePhone,   then write a class Camer...
#C.23
C#
interface ICamera { // ... }   class MobilePhone { // ... }   class CameraPhone: ICamera, MobilePhone { // ... }
Give a code snippet in #C.23 Multiple inheritance allows to specify that one class is a subclass of several other classes. Some languages allow multiple inheritance for arbitrary classes,   others restrict it to interfaces,   some don't allow it at all. Task Write two classes (or interfaces) Camera and MobilePho...
christopher/rosetta-code
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n ...
#360_Assembly
360 Assembly
* FRACTRAN 17/02/2019 FRACTRAN CSECT USING FRACTRAN,R13 base register B 72(R15) skip savearea DC 17F'0' savearea SAVE (14,12) save previous context ST R13,4(R15) link backward ST...
Give a code snippet in #360_Assembly FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an...
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...
#Common_Lisp
Common Lisp
(defun binary-search (value array) (let ((low 0) (high (1- (length array))))   (do () ((< high low) nil) (let ((middle (floor (+ low high) 2)))   (cond ((> (aref array middle) value) (setf high (1- middle)))   ((< (aref array middle) value) (setf l...
Give a code snippet in #Common_Lisp 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 se...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_triangle
Prime triangle
You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangem...
#J
J
is_prime=: 1&p:@(+/)   is_prime_triangle=: {{ NB. y is index into L and thus analogous to *a p=. is_prime L{~y+0 1 if. N=y do. p return.end. i=. Y=. y+1 if. p do. if. is_prime_triangle Y do. 1 return.end.end. while. M>i=.i+2 do. if. is_prime L{~y,i do. L=: (L{~Y,i) (i,Y)} L if. is_prime_tria...
Give a code snippet in #J You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the...
#Swift
Swift
let opa = [ "^": (prec: 4, rAssoc: true), "*": (prec: 3, rAssoc: false), "/": (prec: 3, rAssoc: false), "+": (prec: 2, rAssoc: false), "-": (prec: 2, rAssoc: false), ]   func rpn(tokens: [String]) -> [String] { var rpn : [String] = [] var stack : [String] = [] // holds operators and left par...
Give a code snippet in #Swift Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RP...
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.
#Klong
Klong
  [1 2 3],[4 5 6]  :" join " [1 2 3 4 5 6]   [1 2],:\[[3 4] [5 6] [7 8]]  :" join each-left " [[1 2 3 4] [1 2 5 6] [1 2 7 8]]   [1 2],:/[[3 4] [5 6] [7 8]]  :" join each-right " [[3 4 1 2] [5 6 1 2] [7 8 1 2]]  
Give a code snippet in #Klong 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/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#PARI.2FGP
PARI/GP
beer(n)={ if(n == 1, print("1 bottle of beer on the wall"); print("1 bottle of beer"); print("Take one down and pass it around"); print("No bottles of beer on the wall") , print(n" bottles of beer on the wall"); print(n" bottles of beer"); print("Take one down and pass it around"); p...
Give a code snippet in #PARI.2FGP Task Implement a   HQ9+   interpreter or compiler.
christopher/rosetta-code
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language...
#Scala
Scala
val dog = "Benjamin" val Dog = "Samba" val DOG = "Bernie" println("There are three dogs named " + dog + ", " + Dog + ", and " + DOG + ".")
Give a code snippet in #Scala Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Sa...
christopher/rosetta-code
http://rosettacode.org/wiki/Synchronous_concurrency
Synchronous concurrency
The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th...
#Raku
Raku
sub MAIN ($infile) { $infile.IO.lines ==> printer() ==> my $count; say "printed $count lines"; }   sub printer(*@lines) { my $lines; for @lines { .say; ++$lines; } $lines; }
Give a code snippet in #Raku The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with differen...
christopher/rosetta-code
http://rosettacode.org/wiki/JortSort
JortSort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Quackery
Quackery
[ dup ' [ sortwith ] ]'[ nested join do = ] is jortsortwith ( [ --> b )
Give a code snippet in #Quackery Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick...
christopher/rosetta-code
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#Racket
Racket
  (define (foo x) (define (bar y) (+ x y)) (bar 2)) (foo 1) ; => 3 (bar 1) ; => error  
Give a code snippet in #Racket Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Z80_Assembly
Z80 Assembly
;MSX Bios calls CHPUT equ 000A2H ;print character A CHGET equ 0009FH ;wait for keyboard input INITXT equ 0006CH ;init TEXT1 mode (40 x 24), based on TXTNAM,TXTCGP and LINL40 LDIRVM equ 0005CH ;write BC times MEM(HL++) to VRAM(DE++)   ;MSX system variables TXTNAM equ...
Give a code snippet in #Z80_Assembly 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identif...
#D
D
import std.stdio;   void main() { auto Δ = 1; Δ++; writeln(Δ); }
Give a code snippet in #D Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task ...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#Groovy
Groovy
def formatCell = { cell -> "<td>${cell.replaceAll('&','&amp;').replaceAll('<','&lt;')}</td>" }   def formatRow = { row -> """<tr>${row.split(',').collect { cell -> formatCell(cell) }.join('')}</tr> """ }   def formatTable = { csv, header=false -> def rows = csv.split('\n').collect { row -> formatRow(row) } ...
Give a code snippet in #Groovy Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task C...
christopher/rosetta-code
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
sb = {1, 1}; Do[ sb = sb~Join~{Total@sb[[i - 1 ;; i]], sb[[i]]} , {i, 2, 1000} ] Take[sb, 15] Flatten[FirstPosition[sb, #] & /@ Range[10]] First@FirstPosition[sb, 100] AllTrue[Partition[Take[sb, 1000], 2, 1], Apply[GCD] /* EqualTo[1]]
Give a code snippet in #Mathematica_.2F_Wolfram_Language For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequenc...
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 ⋮ ⋮ ⋮ ⋱ ...
#F.C5.8Drmul.C3.A6
Fōrmulæ
  include "NSLog.incl"   local fn IdentityMatrix( n as NSInteger ) as CFStringRef NSInteger i, j CFMutableArrayRef tempArr = fn MutableArrayWithCapacity( n ) CFMutableStringRef mutStr = fn MutableStringWithCapacity( 0 )   for i = 0 to n - 1 MutableArrayRemoveAllObjects( tempArr ) for j = 0 to n - 1 MutableArrayInsertOb...
Give a code snippet in #F.C5.8Drmul.C3.A6 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 ⋯ ...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring
Substring
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 |...
#Erlang
Erlang
1> N = 3. 2> M = 5. 3> string:sub_string( "abcdefghijklm", N ). "cdefghijklm" 4> string:sub_string( "abcdefghijklm", N, N + M - 1 ). "cdefg" 6> string:sub_string( "abcdefghijklm", 1, string:len("abcdefghijklm") - 1 ). "abcdefghijkl" 7> Start_character = string:chr( "abcdefghijklm", $e ). 8> string:sub_strin...
Give a code snippet in #Erlang 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/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
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. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#Smalltalk
Smalltalk
  m := (FillInTheBlankMorph request: 'Number of rows?') asNumber. n := (FillInTheBlankMorph request: 'Number of columns?') asNumber. aMatrix := Matrix rows: m columns: n. aMatrix at: (aMatrix rowCount // 2) at: (aMatrix columnCount // 2) put: 3.4. e := aMatrix at: (aMatrix rowCount // 2) at: (aMatrix columnCo...
Give a code snippet in #Smalltalk 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. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those ...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other...
#Java
Java
import java.nio.file.Paths; //... other class code here public static boolean isEmptyDir(String dirName){ return Paths.get(dirName).toFile().listFiles().length == 0; }
Give a code snippet in #Java Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an emp...
christopher/rosetta-code
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#F.23
F#
[[
Give a code snippet in #F.23 A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed...
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...
#Wren
Wren
import "/big" for BigInt import "/fmt" for Conv, Fmt import "/sort" for Sort import "/ioutil" for Input   var nextLeftTruncatablePrimes = Fn.new { |n, radix, certainty| var probablePrimes = [] var baseString = (n == BigInt.zero) ? "" : n.toBaseString(radix) for (i in 1...radix) { var p = BigInt.from...
Give a code snippet in #Wren 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/Fast_Fourier_transform
Fast Fourier transform
Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude   (i.e.:   sqrt(re2 + im2)...
#Scheme
Scheme
; Compute and return the FFT of the given input vector using the Cooley-Tukey Radix-2 ; Decimation-in-Time (DIT) algorithm. The input is assumed to be a vector of complex ; numbers that is a power of two in length greater than zero.   (define fft-r2dit (lambda (in-vec) ; The constant ( -2 * pi * i ). (define...
Give a code snippet in #Scheme Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magn...
christopher/rosetta-code
http://rosettacode.org/wiki/Zumkeller_numbers
Zumkeller numbers
Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ...
#AppleScript
AppleScript
-- Sum n's proper divisors. on aliquotSum(n) if (n < 2) then return 0 set sum to 1 set sqrt to n ^ 0.5 set limit to sqrt div 1 if (limit = sqrt) then set sum to sum + limit set limit to limit - 1 end if repeat with i from 2 to limit if (n mod i is 0) then set sum to s...
Give a code snippet in #AppleScript Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the...
christopher/rosetta-code