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/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...
#Clojure
Clojure
> (apply str (take-while #(not (#{\# \;} %)) "apples # comment")) "apples "
Give a code snippet in #Clojure 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. ...
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 |...
#Avail
Avail
Method "logic ops_,_" is [ a : boolean; b : boolean; | Print: "not a: " ++ “¬a”; Print: "not b: " ++ “¬b”; Print: "a and b: " ++ “a ∧ b”; Print: "a or b: " ++ “a ∨ b”; Print: "a nand b: " ++ “a ↑ b”; Print: "a nor b: " ++ “a ↓ b”; Print: "a implies b: " ++ “a → b”; // = not a OR b ...
Give a code snippet in #Avail 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/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion 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 ...
#VBA
VBA
Option Base 1 Private Function insertion_sort(s As Variant) As Variant Dim temp As Variant Dim j As Integer For i = 2 To UBound(s) temp = s(i) j = i - 1 Do While s(j) > temp s(j + 1) = s(j) j = j - 1 If j = 0 Then Exit Do Loop s(j +...
Give a code snippet in #VBA Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort...
christopher/rosetta-code
http://rosettacode.org/wiki/Long_year
Long year
Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
#TypeScript
TypeScript
const isLongYear = (year: number): boolean => { const jan1: Date = new Date(year, 0, 1); const dec31: Date = new Date(year, 11, 31); return (4 == jan1.getDay() || 4 == dec31.getDay()) }   for (let y: number = 1995; y <= 2045; y++) { if (isLongYear(y)) { console.log(y) } }
Give a code snippet in #TypeScript Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#Julia
Julia
using Printf, Primes using DataStructures   function counttransitions(upto::Integer) cnt = counter(Pair{Int,Int}) tot = 0 prv, nxt = 2, 3 while nxt ≤ upto push!(cnt, prv % 10 => nxt % 10) prv = nxt nxt = nextprime(nxt + 1) tot += 1 end return sort(Dict(cnt)), tot ...
Give a code snippet in #Julia A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferen...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Break
Loops/Break
Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If the number 10 is never gener...
#JavaScript
JavaScript
for (;;) { var a = Math.floor(Math.random() * 20); print(a); if (a == 10) break; a = Math.floor(Math.random() * 20); print(a); }
Give a code snippet in #JavaScript Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the lo...
christopher/rosetta-code
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#Kotlin
Kotlin
// version 1.1.51   import java.util.Random   val r = Random() val b = Array(3) { IntArray(3) } // board -> 0: blank; -1: computer; 1: human   var bestI = 0 var bestJ = 0   fun checkWinner(): Int { for (i in 0..2) { if (b[i][0] != 0 && b[i][1] == b[i][0] && b[i][2] == b[i][0]) return b[i][0] if (b[...
Give a code snippet in #Kotlin Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld...
christopher/rosetta-code
http://rosettacode.org/wiki/Executable_library
Executable library
The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. Task detail Create a library/module/dll/shared object/... for a programming langua...
#BBC_BASIC
BBC BASIC
seqlen% = FNhailstone(27) PRINT "Sequence length for 27 is "; seqlen% maxlen% = 0 FOR number% = 2 TO 100000 seqlen% = FNhailstone(number%) IF seqlen% > maxlen% THEN maxlen% = seqlen% maxnum% = number% ENDIF NEXT PRINT "The number with the l...
Give a code snippet in #BBC_BASIC The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. Task detail Create a library/module/dll/shared ...
christopher/rosetta-code
http://rosettacode.org/wiki/Superellipse
Superellipse
A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a superellipse with n = 2.5, and a...
#AutoHotkey
AutoHotkey
n := 2.5 a := 200 b := 200 SuperEllipse(n, a, b) return   SuperEllipse(n, a, b){ global pToken := Gdip_Startup() π := 3.141592653589793, oCoord := [], oX := [], oY := [] nn := 2/n loop 361 { t := (A_Index-1) * π/180 ; https://en.wikipedia.org/wiki/Superellipse x := abs...
Give a code snippet in #AutoHotkey A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Dra...
christopher/rosetta-code
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a met...
#AWK
AWK
  # syntax: GAWK -f CARMICHAEL_3_STRONG_PSEUDOPRIMES.AWK # converted from C BEGIN { printf("%5s%8s%8s%13s\n","P1","P2","P3","PRODUCT") for (p1=2; p1<62; p1++) { if (!is_prime(p1)) { continue } for (h3=1; h3<p1; h3++) { for (d=1; d<h3+p1; d++) { if ((h3+p1)*(p1-1)%d == 0 && mod(-p1*...
Give a code snippet in #AWK A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investi...
christopher/rosetta-code
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In ...
#Delphi
Delphi
  note description : "Initial part, in order, of the sequence of Hamming numbers" math : "[ Hamming numbers, also known as regular numbers and 5-smooth numbers, are natural integers that have 2, 3 and 5 as their only prime factors. ]" computer_arithmetic : "[ ...
Give a code snippet in #Delphi Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming num...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#Arturo
Arturo
encoded: encode.url.slashes "http://foo bar/" print encoded
Give a code snippet in #Arturo Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes...
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...
#JavaScript
JavaScript
var L3 = new Object();   L3.not = function(a) { if (typeof a == "boolean") return !a; if (a == undefined) return undefined; throw("Invalid Ternary Expression."); }   L3.and = function(a, b) { if (typeof a == "boolean" && typeof b == "boolean") return a && b; if ((a == true && b == undefined) || (a == undefine...
Give a code snippet in #JavaScript 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#Factor
Factor
PREDICATE: my-int < integer [ 0 > ] [ 11 < ] bi and ;
Give a code snippet in #Factor Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
christopher/rosetta-code
http://rosettacode.org/wiki/Test_integerness
Test integerness
Mathematically, the integers Z are included in the rational numbers Q, which are included in the real numbers R, which can be generalized to the complex numbers C. This means that each of those larger sets, and the data types used to represent them, include some integers. Task[edit] Given a rational, real, or co...
#Raku
Raku
multi is-int ($n) { $n.narrow ~~ Int }   multi is-int ($n, :$tolerance!) { abs($n.round - $n) <= $tolerance }   multi is-int (Complex $n, :$tolerance!) { is-int($n.re, :$tolerance) && abs($n.im) < $tolerance }   # Testing:   for 25.000000, 24.999999, 25.000100, -2.1e120, -5e-2, Inf, NaN, 5.0+0.0i, 5-5i { pr...
Give a code snippet in #Raku Mathematically, the integers Z are included in the rational numbers Q, which are included in the real numbers R, which can be generalized to the complex numbers C. This means that each of those larger sets, and the data types used to represent them, include some integers. Task[edit]...
christopher/rosetta-code
http://rosettacode.org/wiki/Taxicab_numbers
Taxicab numbers
A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also known as:   taxi numbers   tax...
#EchoLisp
EchoLisp
  (require '(heap compile))   (define (scube a b) (+ (* a a a) (* b b b))) (compile 'scube "-f") ; "-f" means : no bigint, no rational used   ;; is n - a^3 a cube b^3? ;; if yes return b, else #f (define (taxi? n a (b 0)) (set! b (cbrt (- n (* a a a)))) ;; cbrt is ∛ (when (and (< b a) (integer? b)) b)) (compile 'tax...
Give a code snippet in #EchoLisp A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also...
christopher/rosetta-code
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Run_BASIC
Run BASIC
'------ delete input.txt ---------------- kill "input.txt" ' this is where we are kill "/input.txt" ' this is the root   ' ---- delete directory docs ---------- result = rmdir("Docs") ' directory where we are result = rmdir("/Docs") ' root directory
Give a code snippet in #Run_BASIC Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337346448646612254452369009474497523...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i";   const proc: main is func begin writeln(modPow(2988348162058574136915891421498819466320163312926952423791023078876139_, 2351399303373464486466122544523690094744975233415544072992656881240319_, 10_ ** 40)); end func;
Give a code snippet in #Seed7 Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 23513993033734...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Elena
Elena
import extensions; import system'routines;   extension op { stoogeSort() = self.stoogeSort(0, self.Length - 1);   stoogeSort(IntNumber i, IntNumber j) { if(self[j]<self[i]) { self.exchange(i,j) }; if (j - i > 1) { int t := (j - i + 1) ...
Give a code snippet in #Elena 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/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#OCaml
OCaml
Sys.getenv "HOME"
Give a code snippet in #OCaml Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell
Terminal control/Ringing the terminal bell
Task Make the terminal running the program ring its "bell". On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal.   It is usua...
#C
C
#include <stdio.h> int main() { printf("\a"); return 0; }
Give a code snippet in #C Task Make the terminal running the program ring its "bell". On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within...
christopher/rosetta-code
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#Action.21
Action!
;there are considered digits 0-5 because 6^6>5000 DEFINE MAXDIGIT="5" INT ARRAY powers(MAXDIGIT+1)   INT FUNC Power(BYTE x) INT res BYTE i   IF x=0 THEN RETURN (0) FI res=1 FOR i=0 TO x-1 DO res==*x OD RETURN (res)   BYTE FUNC IsMunchausen(INT x) INT sum,tmp BYTE d   tmp=x sum=0 WHILE tmp#0 ...
Give a code snippet in #Action.21 A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also s...
christopher/rosetta-code
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#PowerShell
PowerShell
  $Size = 100   $G = @() 1..$Size | ForEach { $G += ,( @( 1 ) * $Size ) }   $x = $y = $Size / 2   # Direction of next move $Dx = 1 $Dy = 0   # While we are still on the grid... While ( $x -ge 0 -and $y -ge 0 -and $x -lt $Size -and $y -lt $Size ) { # Change direction $Dx, $Dy = ( $Dy * $G[$x][$y] ), -( $D...
Give a code snippet in #PowerShell Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, wit...
christopher/rosetta-code
http://rosettacode.org/wiki/Barnsley_fern
Barnsley fern
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ƒ2   (chosen 85% of the time) ...
#Locomotive_Basic
Locomotive Basic
10 mode 2:ink 0,0:ink 1,18:randomize time 20 scale=38 30 maxpoints=20000: x=0: y=0 40 for z=1 to maxpoints 50 p=rnd*100 60 if p<=1 then nx=0: ny=0.16*y: goto 100 70 if p<=8 then nx=0.2*x-0.26*y: ny=0.23*x+0.22*y+1.6: goto 100 80 if p<=15 then nx=-0.15*x+0.28*y: ny=0.26*x+0.24*y+0.44: goto 100 90 nx=0.85*x+0.04*y: ny=-0...
Give a code snippet in #Locomotive_Basic A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#VBA
VBA
Private Function agm(a As Double, g As Double, Optional tolerance As Double = 0.000000000000001) As Double Do While Abs(a - g) > tolerance tmp = a a = (a + g) / 2 g = Sqr(tmp * g) Debug.Print a Loop agm = a End Function Public Sub main() Debug.Print agm(1, 1 / Sqr(2)) End...
Give a code snippet in #VBA This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers...
#Draco
Draco
\util.g   proc nonrec rdch() byte: char c; if read(c) then pretend(c, byte) else case ioerror() incase CH_MISSING: readln(); 10 default: 0 esac fi corp   proc nonrec wrch(byte b) void: if b=10 then writeln() else write(pretend(b, char...
Give a code snippet in #Draco Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of si...
christopher/rosetta-code
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi
Almkvist-Giullera formula for pi
The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 This formula can be used to calcul...
#Common_Lisp
Common Lisp
(ql:quickload :computable-reals :silent t) (use-package :computable-reals) (setq *print-prec* 70) (defparameter *iterations* 52)   ; factorial using computable-reals multiplication op to keep precision (defun !r (n) (let ((p 1)) (loop for i from 2 to n doing (setq p (*r p i))) p))   ; the nth integer term (de...
Give a code snippet in #Common_Lisp The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1...
christopher/rosetta-code
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Raku
Raku
my $a1 = 1; my $a2 = 0; my $d = 3.2;   say ' i d';   for 2 .. 13 -> $exp { my $a = $a1 + ($a1 - $a2) / $d; do { my $x = 0; my $y = 0; for ^2 ** $exp { $y = 1 - 2 * $y * $x; $x = $a - $x²; } $a -= $x / $y; } xx 10; $d = ($a1 - $a2) / ($a - ...
Give a code snippet in #Raku Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort
Sorting algorithms/Merge 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 ...
#Rust
Rust
  fn merge<T: Copy + PartialOrd>(x1: &[T], x2: &[T], y: &mut [T]) { assert_eq!(x1.len() + x2.len(), y.len()); let mut i = 0; let mut j = 0; let mut k = 0; while i < x1.len() && j < x2.len() { if x1[i] < x2[j] { y[k] = x1[i]; k += 1; i += 1; } else { y[k] = x2[j]; k += 1; j += 1; } } if i ...
Give a code snippet in #Rust Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#TypeScript
TypeScript
const detectNonLetterRegexp=/[^A-ZÀ-ÞЀ-Я]/g;   function stripDiacritics(phrase:string){ return phrase.normalize('NFD').replace(/[\u0300-\u036f]/g, "") }   function isPalindrome(phrase:string){ const TheLetters = stripDiacritics(phrase.toLocaleUpperCase().replace(detectNonLetterRegexp, '')); const middlePosi...
Give a code snippet in #TypeScript 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 (possib...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#ArnoldC
ArnoldC
IT'S SHOWTIME HEY CHRISTMAS TREE n YOU SET US UP @NO PROBLEMO STICK AROUND @NO PROBLEMO TALK TO THE HAND n GET TO THE CHOPPER n HERE IS MY INVITATION n GET UP @NO PROBLEMO ENOUGH TALK CHILL YOU HAVE BEEN TERMINATED
Give a code snippet in #ArnoldC Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations ...
christopher/rosetta-code
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#MATLAB
MATLAB
>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; >> y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]; >> polyfit(x,y,2)   ans =   2.999999999999998 2.000000000000019 0.999999999999956
Give a code snippet in #MATLAB Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficient...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#BQN
BQN
SumDigits ← { 𝕊 𝕩: 10 𝕊 𝕩; 𝕨 𝕊 0: 0; (𝕨|𝕩)+𝕨𝕊⌊𝕩÷𝕨 }   •Show SumDigits 1 •Show SumDigits 1234 •Show 16 SumDigits 254
Give a code snippet in #BQN Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
christopher/rosetta-code
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Swift
Swift
class Foo { }   var foos = [Foo]() for i in 0..<n { foos.append(Foo()) }   // incorrect version: var foos_WRONG = [Foo](count: n, repeatedValue: Foo()) // Foo() only evaluated once
Give a code snippet in #Swift Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are consider...
christopher/rosetta-code
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#PL.2FI
PL/I
*process or(!); quib: Proc Options(main); /********************************************************************* * 06.10.2013 Walter Pachl *********************************************************************/ put Edit*process or(!); quib: Proc Options(main); /**************************************************...
Give a code snippet in #PL.2FI Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An i...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#Scheme
Scheme
((lambda (x) (display "SPAM") (newline) (x x)) (lambda (x) (display "SPAM") (newline) (x x)))  
Give a code snippet in #Scheme Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loo...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting 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 ...
#ALGOL_68
ALGOL 68
PROC counting sort mm = (REF[]INT array, INT min, max)VOID: ( INT z := LWB array - 1; [min:max]INT count;   FOR i FROM LWB count TO UPB count DO count[i] := 0 OD; FOR i TO UPB array DO count[ array[i] ]+:=1 OD;   FOR i FROM LWB count TO UPB count DO FOR j TO count[i] DO array[z+:=1] := i OD OD );   PROC...
Give a code snippet in #ALGOL_68 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/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if ...
#Fortran
Fortran
  program element_operations implicit none   real(kind=4), dimension(3,3) :: a,b integer :: i   a=reshape([(i,i=1,9)],shape(a))   print*,'addition' b=a+a call print_arr(b)   print*,'multiplication' b=a*a call print_arr(b)   print*,'division' b=a/b call print_arr(b)   print*,'exponentiation' ...
Give a code snippet in #Fortran This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exp...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#VBScript
VBScript
' Roman numerals Encode - Visual Basic - 18/04/2019 Function toRoman(ByVal value) Dim arabic Dim roman Dim i, result arabic = Array(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1) roman = Array("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I") For i = 0 To 12 ...
Give a code snippet in #VBScript Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, ...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#Burlesque
Burlesque
ps++
Give a code snippet in #Burlesque A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, sepa...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Wortel
Wortel
@let {  ; using a fork (sum divided-by length) mean1 @(@sum / #)    ; using a function with a named argument mean2 &a / @sum a #a   [[  !mean1 [3 1 4 1 5 9 2]  !mean2 [3 1 4 1 5 9 2] ]] }
Give a code snippet in #Wortel Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an est...
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 ...
#VBScript
VBScript
  Set objFSO = CreateObject("Scripting.FileSystemObject") Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\unixdict.txt",1)   Set objUnixDict = CreateObject("Scripting.Dictionary") Set objSemordnilap = CreateObject("Scripting.Dictionary")   Do Until objInFile.AtEndOfStream ...
Give a code snippet in #VBScript 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 t...
christopher/rosetta-code
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#Pascal
Pascal
program BabbageProblem; (* Anything bracketed off like this is an explanatory comment. *) var n : longint; (* The VARiable n can hold a 'long', ie large, INTeger. *) begin n := 2; (* Start with n equal to 2. *) repeat n := n + 2 (* Increase n by 2. *) until (n * n) mod 1000000 = 269696; (* 'n * n' m...
Give a code snippet in #Pascal Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Com...
christopher/rosetta-code
http://rosettacode.org/wiki/Fork
Fork
Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
#Smalltalk
Smalltalk
'Here I am' displayNl. |a| a := [ (Delay forSeconds: 2) wait . 1 to: 100 do: [ :i | i displayNl ] ] fork. 'Child will start after 2 seconds' displayNl. "wait to avoid terminating first the parent; a better way should use semaphores" (Delay forSeconds: 10) wait.
Give a code snippet in #Smalltalk Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
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...
#Phix
Phix
with javascript_semantics sequence emirps = {} function rev(integer n) integer res = 0 while n do res = res*10+remainder(n,10) n = floor(n/10) end while return res end function function emirp(integer n) if is_prime(n) then integer r = rev(n) if r!=n and is_prime(r...
Give a code snippet in #Phix 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   e...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Batch_File
Batch File
<nul set/p"=Goodbye, World!" <nul set/p=Goodbye, World!
Give a code snippet in #Batch_File Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/...
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...
#C.23
C#
// Non-Generic Stack System.Collections.Stack stack = new System.Collections.Stack(); stack.Push( obj ); bool isEmpty = stack.Count == 0; object top = stack.Peek(); // Peek without Popping. top = stack.Pop();   // Generic Stack System.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>(); s...
Give a code snippet in #C.23 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 acc...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Dim s As String = "panda" Dim s1 As String = Mid(s, 2) Dim s2 As String = Left(s, Len(s) - 1) Dim s3 As String = Mid(s, 2, Len(s) - 2) Print s Print s1 Print s2 Print s3 Sleep
Give a code snippet in #FreeBASIC The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed...
christopher/rosetta-code
http://rosettacode.org/wiki/Break_OO_privacy
Break OO privacy
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is...
#Tcl
Tcl
package require Tcl 8.6   oo::class create Example { variable name constructor n {set name $n} method print {} {puts "Hello, I am $name"} } set e [Example new "Eric"] $e print set [info object namespace $e]::name "Edith" $e print
Give a code snippet in #Tcl Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool mig...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell
Terminal control/Ringing the terminal bell
Task Make the terminal running the program ring its "bell". On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal.   It is usua...
#Brainf.2A.2A.2A
Brainf***
I + + + +++ +-+-+ .
Give a code snippet in #Brainf.2A.2A.2A Task Make the terminal running the program ring its "bell". On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physic...
christopher/rosetta-code
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey se...
#Nim
Nim
import strformat   proc farey(n: int) = var f1 = (d: 0, n: 1) var f2 = (d: 1, n: n) write(stdout, fmt"0/1 1/{n}") while f2.n > 1: let k = (n + f1.n) div f2.n let aux = f1 f1 = f2 f2 = (f2.d * k - aux.d, f2.n * k - aux.n) write(stdout, fmt" {f2.d}/{f2.n}") write(stdout, "\n")   proc fareyLe...
Give a code snippet in #Nim The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   F...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_occurrences_of_a_substring
Count occurrences of a substring
Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It should return an integer cou...
#Swift
Swift
import Foundation   func countSubstring(str: String, substring: String) -> Int { return str.components(separatedBy: substring).count - 1 }   print(countSubstring(str: "the three truths", substring: "th")) print(countSubstring(str: "ababababab", substring: "abab"))
Give a code snippet in #Swift Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. ...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#EGL
EGL
  program OneHundredDoors   function main()   doors boolean[] = new boolean[100]; n int = 100;   for (i int from 1 to n) for (j int from i to n by i) doors[j] = !doors[j]; end end   for (i int from 1 to n) if (doors[i]) SysLib.writeStdo...
Give a code snippet in #EGL There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...)...
christopher/rosetta-code
http://rosettacode.org/wiki/Textonyms
Textonyms
When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms. Assuming the digit keys are mapped to letters as follows: 2 -> ABC 3 -> DEF 4 -> GHI 5 -> JKL 6 -> MNO 7 -> PQRS 8 -> TUV 9 -...
#Io
Io
main := method( setupLetterToDigitMapping   file := File clone openForReading("./unixdict.txt") words := file readLines file close   wordCount := 0 textonymCount := 0 dict := Map clone words foreach(word, (key := word asPhoneDigits) ifNonNil( wordCount = wordCount+1 ...
Give a code snippet in #Io When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms. Assuming the digit keys are mapped to letters as follows: 2 -> ABC 3 -> DEF 4 -> GHI 5 -> JKL 6 -> MNO 7 ...
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 ...
#AutoHotkey
AutoHotkey
start: Gui, Add, ListView, r20 w200, 1|2 data = ( foo,53 joe,34 bar,23 )   Loop, parse, data, `n { stringsplit, row, A_LoopField, `, LV_Add(row, row1, row2) } LV_ModifyCol() ; Auto-size columns Gui, Show msgbox, sorting by column1 LV_ModifyCol(1, "sort") ; sort by first column msgbox, sorting by column2 LV_ModifyC...
Give a code snippet in #AutoHotkey 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 | Qui...
christopher/rosetta-code
http://rosettacode.org/wiki/Huffman_coding
Huffman coding
Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you could just encode each letter wi...
#zkl
zkl
fcn buildHuffman(text){ //-->(encode dictionary, decode dictionary) ft:=Dictionary(); foreach c in (text){ ft[c]=ft.find(c,0)+1 } // leafs w/count   // build the tree, which is a list of lists of ... tree:=ft.pump(List,fcn([(c,cnt)]){ //-->L( (cnt, ((sym,code))), ...) L(cnt, L(L(c,""))) }).copy(...
Give a code snippet in #zkl Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you cou...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#TypeScript
TypeScript
function integer_classification(){ var sum:number=0, i:number,j:number; var try:number=0; var number_list:number[]={1,0,0}; for(i=2;i<=20000;i++){ try=i/2; sum=1; for(j=2;j<try;j++){ if (i%j) continue; try=i/j; sum+=j; if (j!=try) sum+=try; } if (sum<i){ number_list[d]++; continu...
Give a code snippet in #TypeScript These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as defi...
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...
#Oz
Oz
declare %% Creates a new class derived from BaseClass %% with an added feature (==public immutable attribute) fun {AddFeature BaseClass FeatureName FeatureValue} class DerivedClass from BaseClass feat %% "FeatureName" is escaped, otherwise a new variable %% refering to a private feature would...
Give a code snippet in #Oz 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 Metaprogr...
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#J
J
$ jq type true "boolean" false "boolean"
Give a code snippet in #J Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#8080_Assembly
8080 Assembly
cpu 8086 org 100h section .text mov di,10 ; DI is the divisor to find digits xor bp,bp ; Find first 20 Harshad numbers mov cx,20 first: call next mov ax,bp call print loop first mov bp,1000 ; Find first Harshad number > 1000 call next ; .. fall through (print and stop) mov ax,bp ;;; Print the number ...
Give a code snippet in #8080_Assembly The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task T...
christopher/rosetta-code
http://rosettacode.org/wiki/Atomic_updates
Atomic updates
Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the t...
#FreeBASIC
FreeBASIC
Randomize Timer Dim Shared As Uinteger cubo(1 To 10), a, i For i As Uinteger = 1 To 10 cubo(i) = Int(Rnd * 90) Next i   Function Display(cadena As String) As Uinteger Dim As Uinteger valor Print cadena; Spc(2); For i As Uinteger = 1 To 10 valor += cubo(i) Print Using "###"; cubo(i); ...
Give a code snippet in #FreeBASIC Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of al...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_operations
Bitwise 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 |...
#Free_Pascal
Free Pascal
program Bitwise; {$mode objfpc} var // Pascal uses a native int type as a default literal type // Make sure the operants work on an exact type. x:shortint = 2; y:ShortInt = 3; begin Writeln('2 and 3 = ', x and y); Writeln('2 or 3 = ', x or y); Writeln('2 xor 3 = ', x xor y); Writeln('not 2 = ', not x); ...
Give a code snippet in #Free_Pascal 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 Opera...
christopher/rosetta-code
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#Clojure
Clojure
(ns rosettacode.sudoku (:use [clojure.pprint :only (cl-format)]))   (defn- compatible? [m x y n] (let [n= #(= n (get-in m [%1 %2]))] (or (n= y x) (let [c (count m)] (and (zero? (get-in m [y x])) (not-any? #(or (n= y %) (n= % x)) (range c)) (let [zx (* c (quot x c)), zy (*...
Give a code snippet in #Clojure Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#REBOL
REBOL
  ; This is a line comment.   { Multi-line strings can be used as comments if you like }  
Give a code snippet in #REBOL Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#AppleScript
AppleScript
on kernighansEarthquakes(magnitudeToBeat) -- A local "owner" for the long AppleScript lists. Speeds up references to their items and properties. script o property individualEntries : {} property qualifyingEntries : {} end script   -- Read the text file assuming it's UTF-8 encoded and get...
Give a code snippet in #AppleScript Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example ...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Python
Python
import random rand = random.SystemRandom() rand.randint(1,10)
Give a code snippet in #Python Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
christopher/rosetta-code
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#C
C
#include <string.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <FreeImage.h>   #define NUM_PARTICLES 1000 #define SIZE 800   void draw_brownian_tree(int world[SIZE][SIZE]){ int px, py; // particle values int dx, dy; // offsets int i;   // set the seed world[rand() % SIZE][rand...
Give a code snippet in #C Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "s...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#Rust
Rust
use std::str;   fn main() { // Create new string let string = String::from("Hello world!"); println!("{}", string); assert_eq!(string, "Hello world!", "Incorrect string text");   // Create and assign value to string let mut assigned_str = String::new(); assert_eq!(assigned_str, "", "Incorrec...
Give a code snippet in #Rust Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings accord...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#zkl
zkl
foreach n in ([1..10,4]) {println(n)} [1..10,3].pump(Console.println)
Give a code snippet in #zkl Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Incre...
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#PicoLisp
PicoLisp
program demo = compile_string(#" string name=\"demo\"; string hello() { return(\"hello, i am \"+name); }");   demo()->hello(); Result: "hello, i am demo"
Give a code snippet in #PicoLisp Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if appl...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#6502_Assembly
6502 Assembly
;These are all equivalent: LDA #$41 LDA #65 LDA #%01000001 LDA #'A'
Give a code snippet in #6502_Assembly Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but s...
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...
#Ol
Ol
  #!/usr/bin/ol (import (otus random!))   (define MAX 65536) ; should be power of two ; size of game board (should be less than MAX) (define WIDTH 170) (define HEIGHT 96)   ; helper function (define (hash x y) (let ((x (mod (+ x WIDTH) WIDTH)) (y (mod (+ y HEIGHT) HEIGHT))) (+ (* y MAX) x)))   ; helper ...
Give a code snippet in #Ol 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...
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...
#11l
11l
V data = [(‘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’)...
Give a code snippet in #11l 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,Sa...
christopher/rosetta-code
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#zkl
zkl
fcn format(text,how){ words:=text.split("$").apply("split").flatten(); max:=words.reduce(fcn(p,n){ n=n.len(); n>p and n or p },0); wordsPerCol:=80/(max+1); fmt:=(switch(how){ case(-1){ "%%-%ds ".fmt(max).fmt } case(0) { fcn(max,w){ a:=(max-w.len())/2; b:=max-w.len() - a; String(" "*a...
Give a code snippet in #zkl Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left ...
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...
#MAXScript
MAXScript
fn lookAndSay num = ( local result = "" num += " " local current = num[1] local numReps = 1   for digit in 2 to num.count do ( if num[digit] != current then ( result += (numReps as string) + current numReps = 1 current = num[digit] ) ...
Give a code snippet in #MAXScript 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 sequ...
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
#Avail
Avail
Print: "Hello World!";
Give a code snippet in #Avail 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/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance m...
#Apex
Apex
// Static MyClass.method(someParameter);   // Instance myInstance.method(someParameter);
Give a code snippet in #Apex In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or c...
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...
#REXX
REXX
/*REXX program calculates GAMMA using the Taylor series coefficients; ≈80 decimal digits*/ /*The GAMMA function symbol is the Greek capital letter: Γ */ numeric digits 90 /*be able to handle extended precision.*/ parse arg LO HI . ...
Give a code snippet in #REXX 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/libr...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Action.21
Action!
;This is a comment   PROC Main() ;This is a comment as well RETURN
Give a code snippet in #Action.21 Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/String_append
String append
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 |...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program appendstr64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesAR...
Give a code snippet in #AArch64_Assembly 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#Pike
Pike
string s = "alphaBETA"; string s2 = "foo bar gazonk";   write("Upper: %O\nLower: %O\nCapitalize: %O\nSilly: %O\nElite: %O\n", upper_case(s), lower_case(s), String.capitalize(s), String.sillycaps(s2), String.Elite.elite_string(s2));  
Give a code snippet in #Pike Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not re...
christopher/rosetta-code
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the widt...
#C.2B.2B
C++
#include <iostream> #include <tuple>   union conv { int i; float f; };   float nextUp(float d) { if (isnan(d) || d == -INFINITY || d == INFINITY) return d; if (d == 0.0) return FLT_EPSILON;   conv c; c.f = d; c.i++;   return c.f; }   float nextDown(float d) { if (isnan(d) || d == -IN...
Give a code snippet in #C.2B.2B Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additio...
christopher/rosetta-code
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string....
#M2000_Interpreter
M2000 Interpreter
  Module WeaselAlgorithm { Print "Evolutionary Algorithm" \\ Weasel Algorithm \\ Using dynamic array, which expand if no fitness change, \\ and reduce to minimum when fitness changed \\ Abandon strings when fitness change \\ Also lambda function Mutate$ change when topscore=10, to c...
Give a code snippet in #M2000_Interpreter Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘close...
christopher/rosetta-code
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "osfiles.s7i";   const proc: main is func begin copyFile("input.txt", "output.txt"); end func;
Give a code snippet in #Seed7 File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file i...
christopher/rosetta-code
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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 Miller–Rabin primality test or Rabin–Miller prima...
#Oz
Oz
  %--------------------------------------------------------------------------% % module: Primality % file: Primality.oz % version: 17 DEC 2014 @ 6:50AM %--------------------------------------------------------------------------%   declare %--------------------------------------------------------------------------%   fu...
Give a code snippet in #Oz This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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 Miller–Rabin primalit...
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#CoffeeScript
CoffeeScript
dot_product = (ary1, ary2) -> if ary1.length != ary2.length throw "can't find dot product: arrays have different lengths" dotprod = 0 for v, i in ary1 dotprod += v * ary2[i] dotprod   console.log dot_product([ 1, 3, -5 ], [ 4, -2, -1 ]) # 3 try console.log dot_product([ 1, 3, -5 ], [ 4, -2, -1, 0 ]) #...
Give a code snippet in #CoffeeScript Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4,...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance m...
#ActionScript
ActionScript
// Static MyClass.method(someParameter);   // Instance myInstance.method(someParameter);
Give a code snippet in #ActionScript In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a sta...
christopher/rosetta-code
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. DEPARTMENT-NUMBERS.   DATA DIVISION. WORKING-STORAGE SECTION. 01 BANNER PIC X(24) VALUE "POLICE SANITATION FIRE". 01 COMBINATION. 03 FILLER PIC X(5) VALUE SPACES. 03 POLICE PIC 9. 03 FIL...
Give a code snippet in #COBOL There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (di...
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...
#Ring
Ring
decimals(0)   test = ["49927398716", "49927398717", "1234567812345678", "1234567812345670"] for n = 1 to len(test) see test[n] + " -> " + cardtest(test[n]) + nl next   func cardtest(numstr) revstring = revstr(numstr) s1 = revodd(revstring) s2 = reveven(revstring) s3 =right(string(s...
Give a code snippet in #Ring 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#CLU
CLU
prio_queue = cluster [P, T: type] is new, empty, push, pop where P has lt: proctype (P,P) returns (bool)   item = struct[prio: P, val: T] rep = array[item]   new = proc () returns (cvt) return (rep$create(0)) end new   empty = proc (pq: cvt) returns (bool) return (rep$...
Give a code snippet in #CLU A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priori...
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...
#Axe
Axe
"HELLO, WORLD"→Str1 Disp length(Str1)▶Dec,i
Give a code snippet in #Axe 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 contai...
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...
#Maxima
Maxima
life(A) := block( [p, q, B: zerofor(A), s], [p, q]: matrix_size(A), for i thru p do ( for j thru q do ( s: 0, if j > 1 then s: s + A[i, j - 1], if j < q then s: s + A[i, j + 1], if i > 1 then ( s: s + A[i - 1, j], if j > 1 then s: s + A[i - 1, j...
Give a code snippet in #Maxima The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead, ...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#Julia
Julia
input = parse.(Int, split(readline(stdin))) println(stdout, sum(input))
Give a code snippet in #Julia A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separate...
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...
#Haskell
Haskell
data Tree = Empty | Leaf Int | Node Tree Tree deriving (Eq, Show) t1 = Node (Leaf 1) (Node (Leaf 2) (Leaf 3))
Give a code snippet in #Haskell 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/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT - rename file ERROR/STOP RENAME ("input.txt","output.txt") - rename directory ERROR/STOP RENAME ("docs","mydocs",-std-)  
Give a code snippet in #TUSCRIPT Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the...
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)
#Nanoquery
Nanoquery
def isLeapYear(year) if (year % 100 = 0) return (year % 400 = 0) else return (year % 4 = 0) end end
Give a code snippet in #Nanoquery 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/Symmetric_difference
Symmetric difference
Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\displaystyle (A\cup B)\setminus (A...
#Tcl
Tcl
package require struct::set   set A {John Bob Mary Serena} set B {Jim Mary John Bob}   set AnotB [struct::set difference $A $B] set BnotA [struct::set difference $B $A] set SymDiff [struct::set union $AnotB $BnotA]   puts "A\\B = $AnotB" puts "B\\A = $BnotA" puts "A\u2296B = $SymDiff"   # Of course, the library alr...
Give a code snippet in #Tcl Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\displ...
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Rust
Rust
  fn main() { let x = 7.125;   println!("{:9}", x); println!("{:09}", x); println!("{:9}", -x); println!("{:09}", -x); }  
Give a code snippet in #Rust Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth%27s_power_tree
Knuth's power tree
(Knuth's power tree is used for computing   xn   efficiently.) Task Compute and show the list of Knuth's power tree integers necessary for the computation of:   xn   for any real   x   and any non-negative integer   n. Then, using those integers, calculate and show the exact values of (at least) the integer po...
#Ada
Ada
with Ada.Containers.Ordered_Maps; with Ada.Numerics.Big_Numbers.Big_Integers; with Ada.Text_IO; use Ada.Text_IO;   procedure Power_Tree is   Debug_On : constant Boolean := False;   generic type Result_Type is private; Base  : Result_Type; Identity : Result_Type; with function "*" (Lef...
Give a code snippet in #Ada (Knuth's power tree is used for computing   xn   efficiently.) Task Compute and show the list of Knuth's power tree integers necessary for the computation of:   xn   for any real   x   and any non-negative integer   n. Then, using those integers, calculate and show the exact values...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#VBA
VBA
Option Explicit Option Base 0 'Option Base 1 Private ArrResult   Sub test() 'compute Main_Combine 5, 3   'return Dim j As Long, i As Long, temp As String For i = LBound(ArrResult, 1) To UBound(ArrResult, 1) temp = vbNullString For j = LBound(ArrResult, 2) To UBound(ArrResult, 2) ...
Give a code snippet in #VBA Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0...
christopher/rosetta-code