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
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#PicoLisp
PicoLisp
(load "@lib/rsa.l") # Use the 'prime?' function from RSA package   (de truncatablePrime? (N Fun) (for (L (chop N) L (Fun L)) (T (= "0" (car L))) (NIL (prime? (format L))) T ) )   (let (Left 1000000 Right 1000000) (until (truncatablePrime? (dec 'Left) cdr)) (until (truncatablePrime? (dec 'Ri...
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#Pike
Pike
bool is_trunc_prime(int p, string direction) { while(p) { if( !p->probably_prime_p() ) return false; if(direction == "l") p = (int)p->digits()[1..]; else p = (int)p->digits()[..<1]; } return true; }   void main() { bool ltp_found, rtp_found; for(int prime = 10->pow(6); prime--; pri...
http://rosettacode.org/wiki/Tree_traversal
Tree traversal
Task Implement a binary tree where each node carries an integer,   and implement:   pre-order,   in-order,   post-order,     and   level-order   traversal. Use those traversals to output the following tree: 1 / \ / \ / \ 2 3 / \ / 4 5 6 / ...
#D
D
import std.stdio, std.traits;   const final class Node(T) { T data; Node left, right;   this(in T data, in Node left=null, in Node right=null) const pure nothrow { this.data = data; this.left = left; this.right = right; } }   // 'static' templated opCall can't be used in Node...
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#C.23
C#
string str = "Hello,How,Are,You,Today"; // or Regex.Split ( "Hello,How,Are,You,Today", "," ); // (Regex is in System.Text.RegularExpressions namespace) string[] strings = str.Split(','); Console.WriteLine(String.Join(".", strings));  
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#C.2B.2B
C++
#include <string> #include <sstream> #include <vector> #include <iterator> #include <iostream> #include <algorithm> int main() { std::string s = "Hello,How,Are,You,Today"; std::vector<std::string> v; std::istringstream buf(s); for(std::string token; getline(buf, token, ','); ) v.push_back(token)...
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#BBC_BASIC
BBC BASIC
start%=TIME:REM centi-second timer REM perform processing lapsed%=TIME-start%
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#Bracmat
Bracmat
( ( time = fun funarg t0 ret .  !arg:(?fun.?funarg) & clk$:?t0 & !fun$!funarg:?ret & (!ret.flt$(clk$+-1*!t0,3) s) ) & ( fib = .  !arg:<2&1 | fib$(!arg+-1)+fib$(!arg+-2) ) & time$(fib.30) )
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...
#Dyalect
Dyalect
type Employee(name,id,salary,department) with Lookup   func Employee.ToString() { "$\(this.salary) (name: \(this.name), id: \(this.id), department: \(this.department)" }   let employees = [ Employee("Tyler Bennett","E10297",32000,"D101"), Employee("John Rappl","E21437",47000,"D050"), Employee("George Wo...
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...
#BASIC
BASIC
  # basado en código de Antonio Rodrigo dos Santos Silva (gracias): # http://statusgear.freeforums.net/thread/17/basic-256-tic-tac-toe   global playerturn$ global endGame$ global space$ global player1Score$ global player2Score$ global invalidMove$ global tecla$ global keyQ$ global keyW$ global keyE$ global keyA$ global...
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion   %==The main thing==% %==First param - Number of disks==% %==Second param - Start pole==% %==Third param - End pole==% %==Fourth param - Helper pole==% call :move 4 START END HELPER echo. pause exit /b 0   %==The "function"==% :move setlocal set n=%1 set from=%2 set ...
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#J
J
(, -.)@]^:[&0]9 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 ...
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm
Tonelli-Shanks algorithm
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. 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 computational number theory, the Tonelli–Shanks algor...
#REXX
REXX
/* REXX (required by some interpreters) */ Numeric Digits 1000000 ttest ='[(10, 13), (56, 101), (1030, 10009), (44402, 100049)]' Do While pos('(',ttest)>0 Parse Var ttest '(' n ',' p ')' ttest r = tonelli(n, p) Say "n =" n "p =" p Say " roots :" r (p - r) End Exit   legendre: Procedure Parse Arg a,...
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#JavaScript
JavaScript
function tokenize(s, esc, sep) { for (var a=[], t='', i=0, e=s.length; i<e; i+=1) { var c = s.charAt(i) if (c == esc) t+=s.charAt(++i) else if (c != sep) t+=c else a.push(t), t='' } a.push(t) return a }   var s = 'one^|uno||three^^^^|four^^^|^cuatro|' document.write(s, '<br>') for (var a=tokenize(s,'^','...
http://rosettacode.org/wiki/Total_circles_area
Total circles area
Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal dig...
#Wren
Wren
import "/dynamic" for Tuple import "/math" for Nums   var Circle = Tuple.create("Circle", ["x", "y", "r"])   var circles = [ Circle.new( 1.6417233788, 1.6121789534, 0.0848270516), Circle.new(-1.4944608174, 1.2077959613, 1.1039549836), Circle.new( 0.6110294452, -0.6907087527, 0.9089162485), Circle.new(...
http://rosettacode.org/wiki/Topological_sort
Topological sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Haskell
Haskell
import Data.List ((\\), elemIndex, intersect, nub) import Data.Bifunctor (bimap, first)   combs 0 _ = [[]] combs _ [] = [] combs k (x:xs) = ((x :) <$> combs (k - 1) xs) ++ combs k xs   depLibs :: [(String, String)] depLibs = [ ( "des_system_lib" , "std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee") ...
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#NetLogo
NetLogo
  ;; "A Turing Turtle": a Turing Machine implemented in NetLogo ;; by Dan Dewey 1/16/2016 ;; ;; This NetLogo code implements a Turing Machine, see, e.g., ;; http://en.wikipedia.org/wiki/Turing_machine ;; The Turing machine fits nicely into the NetLogo paradigm in which ;; there are agents (aka the turtles), that ...
http://rosettacode.org/wiki/Totient_function
Totient function
The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the integers up to a given positiv...
#Nim
Nim
import strformat   func totient(n: int): int = var tot = n var nn = n var i = 2 while i * i <= nn: if nn mod i == 0: while nn mod i == 0: nn = nn div i dec tot, tot div i if i == 2: i = 1 inc i, 2 if nn > 1: dec tot,...
http://rosettacode.org/wiki/Topswops
Topswops
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is composed of reversing the first  ...
#Tcl
Tcl
package require struct::list   proc swap {listVar} { upvar 1 $listVar list set n [lindex $list 0] for {set i 0; set j [expr {$n-1}]} {$i<$j} {incr i;incr j -1} { set tmp [lindex $list $i] lset list $i [lindex $list $j] lset list $j $tmp } }   proc swaps {list} { for {set i 0} {[lindex $list 0] > ...
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#GAP
GAP
# GAP has an improved floating-point support since version 4.5   Pi := Acos(-1.0);   # Or use the built-in constant: Pi := FLOAT.PI;   r := Pi / 5.0; d := 36;   Deg := x -> x * Pi / 180;   Sin(r); Asin(last); Sin(Deg(d)); Asin(last); Cos(r); Acos(last); Cos(Deg(d)); Acos(last); Tan(r); Ata...
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#PL.2FI
PL/I
  Trabb: Procedure options (main); /* 11 November 2013 */   declare (i, n) fixed binary; declare s fixed (5,1) controlled; declare g fixed (15,5);   put ('Please type 11 values:'); do i = 1 to 11; allocate s; get (s); put (s); end; put skip(2) ('Results:'); do i = 1 to 11; ...
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#PL.2FM
PL/M
TPK: DO; /* external I/O and real mathematical routines */ WRITE$STRING: PROCEDURE( S ) EXTERNAL; DECLARE S POINTER; END; WRITE$REAL: PROCEDURE( R ) EXTERNAL; DECLARE R REAL; END; WRITE$NL: PROCEDURE EXTERNAL; END; READ$REAL: PROCEDURE( R ) REAL EXT...
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#PowerShell
PowerShell
  function Get-Tpk { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [double] $Number )   Begin {...
http://rosettacode.org/wiki/Truth_table
Truth table
A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function. Task Input a Boolean function from the user as a string then calculate and print a formatted truth table for the g...
#XBasic
XBasic
  PROGRAM "truthtables" VERSION "0.001"   $$MaxTop = 80   TYPE VARIABLE STRING*1 .name SBYTE .value END TYPE   TYPE STACKOFBOOL SSHORT .top SBYTE .elements[$$MaxTop] END TYPE   DECLARE FUNCTION Entry() INTERNAL FUNCTION IsOperator(c$) INTERNAL FUNCTION VariableIndex(c$) INTERNAL FUNCTION SetVariables(pos%) INTE...
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#PL.2FI
PL/I
  tp: procedure options (main); declare primes(1000000) bit (1); declare max_primes fixed binary (31); declare (i, k) fixed binary (31);   max_primes = hbound(primes, 1); call sieve;   /* Now search for primes that are right-truncatable. */ call right_truncatable;   /* Now search for primes...
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#PowerShell
PowerShell
function IsPrime ( [int] $num ) { $isprime = @{} 2..[math]::sqrt($num) | Where-Object { $isprime[$_] -eq $null } | ForEach-Object { $_ $isprime[$_] = $true for ( $i=$_*$_ ; $i -le $num; $i += $_ ) { $isprime[$i] = $false } } 2..$num | Where-Object { $isprime[$_] -...
http://rosettacode.org/wiki/Tree_traversal
Tree traversal
Task Implement a binary tree where each node carries an integer,   and implement:   pre-order,   in-order,   post-order,     and   level-order   traversal. Use those traversals to output the following tree: 1 / \ / \ / \ 2 3 / \ / 4 5 6 / ...
#E
E
def btree := [1, [2, [4, [7, null, null], null], [5, null, null]], [3, [6, [8, null, null], [9, null, null]], null]]   def backtrackingOrder(node, pre, mid, post) { switch (node) { match ==null {} ...
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Ceylon
Ceylon
shared void tokenizeAString() { value input = "Hello,How,Are,You,Today"; value tokens = input.split(','.equals); print(".".join(tokens)); }
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#CFEngine
CFEngine
bundle agent main { reports: "${with}" with => join(".", splitstring("Hello,How,Are,You,Today", ",", 99)); }  
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#C
C
#include <stdio.h> #include <time.h>   int identity(int x) { return x; }   int sum(int s) { int i; for(i=0; i < 1000000; i++) s += i; return s; }   #ifdef CLOCK_PROCESS_CPUTIME_ID /* cpu time in the current process */ #define CLOCKTYPE CLOCK_PROCESS_CPUTIME_ID #else /* this one should be appropriate to avoid err...
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...
#E
E
/** Turn a list of arrays into a list of maps with the given keys. */ def addKeys(keys, rows) { def res := [].diverge() for row in rows { res.push(__makeMap.fromColumns(keys, row)) } return res.snapshot() }   def data := addKeys( ["name", "id", "salary", "dept"], [["Tyler Bennett", "E10297", 3200...
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...
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion :newgame set a1=1 set a2=2 set a3=3 set a4=4 set a5=5 set a6=6 set a7=7 set a8=8 set a9=9 set ll=X set /a zz=0 :display1 cls echo Player: %ll% echo %a7%_%a8%_%a9% echo %a4%_%a5%_%a6% echo %a1%_%a2%_%a3% set /p myt=Where would you like to go (choose a number from 1-9 and press e...
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#BBC_BASIC
BBC BASIC
DIM Disc$(13),Size%(3) FOR disc% = 1 TO 13 Disc$(disc%) = STRING$(disc%," ")+STR$disc%+STRING$(disc%," ") IF disc%>=10 Disc$(disc%) = MID$(Disc$(disc%),2) Disc$(disc%) = CHR$17+CHR$(128+disc%-(disc%>7))+Disc$(disc%)+CHR$17+CHR$128 NEXT disc%   MODE 3 OFF ndisc...
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Java
Java
public class ThueMorse {   public static void main(String[] args) { sequence(6); }   public static void sequence(int steps) { StringBuilder sb1 = new StringBuilder("0"); StringBuilder sb2 = new StringBuilder("1"); for (int i = 0; i < steps; i++) { String tmp = sb1...
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#JavaScript
JavaScript
(function(steps) { 'use strict'; var i, tmp, s1 = '0', s2 = '1'; for (i = 0; i < steps; i++) { tmp = s1; s1 += s2; s2 += tmp; } console.log(s1); })(6);
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm
Tonelli-Shanks algorithm
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. 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 computational number theory, the Tonelli–Shanks algor...
#Sidef
Sidef
func tonelli(n, p) { legendre(n, p) == 1 || die "not a square (mod p)" var q = p-1 var s = valuation(q, 2) s == 1 ? return(powmod(n, (p + 1) >> 2, p)) : (q >>= s) var c = powmod(2 ..^ p -> first {|z| legendre(z, p) == -1}, q, p) var r = powmod(n, (q + 1) >> 1, p) var t = powmod(n, q, p) ...
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#jq
jq
# Tokenize the input using the string "escape" as the prefix escape string def tokenize(separator; escape):   # Helper functions: # mapper/1 is like map/1, but for each element, $e, in the input array, # if $e is an array, then it is inserted, # otherwise the elements of ($e|f) are inserted. def mapper(f): re...
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#Julia
Julia
function tokenize2(s::AbstractString, sep::Char, esc::Char) SPE = "\ufffe" SPF = "\uffff" s = replace(s, "$esc$esc", SPE) |> s -> replace(s, "$esc$sep", SPF) |> s -> last(s) == esc ? string(replace(s[1:end-1], esc, ""), esc) : replace(s, esc, "") return map(split(s, sep)) do token ...
http://rosettacode.org/wiki/Total_circles_area
Total circles area
Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal dig...
#XPL0
XPL0
real Circles, MinX, MaxX, MinY, MaxY, Temp, X, Y, DX, DY, Area; int N, Cnt1, Cnt2; def Del = 0.0005; def Inf = float(-1>>1); [\ X Y R Circles:= [ 1.6417233788, 1.6121789534, 0.0848270516, -1.4944608174, 1.2077959613, 1.1039549836, 0.6110294452, -0.6...
http://rosettacode.org/wiki/Topological_sort
Topological sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Huginn
Huginn
import Algorithms as algo; import Text as text;   class DirectedGraph { _adjecentVertices = {}; add_vertex( vertex_ ) { _adjecentVertices[vertex_] = []; } add_edge( from_, to_ ) { _adjecentVertices[from_].push( to_ ); } adjecent_vertices( vertex_ ) { return ( vertex_ ∈ _adjecentVertices ? _adjecentVertices....
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#Nim
Nim
import strutils, tables   proc runUTM(state, halt, blank: string, tape: seq[string] = @[], rules: seq[seq[string]]) = var st = state pos = 0 tape = tape rulesTable: Table[tuple[s0, v0: string], tuple[v1, dr, s1: string]]   if tape.len == 0: tape = @[blank] if pos < 0: pos += tape.len ...
http://rosettacode.org/wiki/Totient_function
Totient function
The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the integers up to a given positiv...
#Pascal
Pascal
{$IFDEF FPC} {$MODE DELPHI} {$IFEND} function gcd_mod(u, v: NativeUint): NativeUint;inline; //prerequisites u > v and u,v > 0 var t: NativeUInt; begin repeat t := u; u := v; v := t mod v; until v = 0; gcd_mod := u; end;   function Totient(n:NativeUint):NativeUint; var i : Na...
http://rosettacode.org/wiki/Topswops
Topswops
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is composed of reversing the first  ...
#Wren
Wren
import "/fmt" for Fmt   var maxn = 10 var maxl = 50   var steps = Fn.new { |n| var a = List.filled(maxl, null) var b = List.filled(maxl, null) var x = List.filled(maxl, 0) for (i in 0...maxl) { a[i] = List.filled(maxn + 1, 0) b[i] = List.filled(maxn + 1, 0) } a[0][0] = 1 var ...
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#Go
Go
package main   import ( "fmt" "math" )   const d = 30. const r = d * math.Pi / 180   var s = .5 var c = math.Sqrt(3) / 2 var t = 1 / math.Sqrt(3)   func main() { fmt.Printf("sin(%9.6f deg) = %f\n", d, math.Sin(d*math.Pi/180)) fmt.Printf("sin(%9.6f rad) = %f\n", r, math.Sin(r)) fmt.Printf("cos(%9.6f ...
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#PureBasic
PureBasic
Procedure.d f(x.d) ProcedureReturn Pow(Abs(x), 0.5) + 5 * x * x * x EndProcedure   Procedure split(i.s, delimeter.s, List o.d()) Protected index = CountString(i, delimeter) + 1 ;add 1 because last entry will not have a delimeter   While index > 0 AddElement(o()) o() = ValD(Trim(StringField(i, index, delim...
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#Prolog
Prolog
largest_left_truncatable_prime(N, N):- is_left_truncatable_prime(N), !. largest_left_truncatable_prime(N, P):- N > 1, N1 is N - 1, largest_left_truncatable_prime(N1, P).   is_left_truncatable_prime(P):- is_prime(P), is_left_truncatable_prime(P, P, 10).   is_left_truncatable_prime(P, _, N):- ...
http://rosettacode.org/wiki/Tree_traversal
Tree traversal
Task Implement a binary tree where each node carries an integer,   and implement:   pre-order,   in-order,   post-order,     and   level-order   traversal. Use those traversals to output the following tree: 1 / \ / \ / \ 2 3 / \ / 4 5 6 / ...
#Eiffel
Eiffel
note description : "Application for tree traversal demonstration" output : "[ Prints preorder, inorder, postorder and levelorder traversal of an example binary tree. ]" author : "Jascha Grübel" date : "$2014-01-07$" revision : "$1.0$"   class APPLICATION ...
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Clojure
Clojure
(apply str (interpose "." (.split #"," "Hello,How,Are,You,Today")))
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#CLU
CLU
% This iterator splits the string on a given character, % and returns each substring in order. tokenize = iter (s: string, c: char) yields (string) while ~string$empty(s) do next: int := string$indexc(c, s) if next = 0 then yield(s) break else yield(strin...
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#C.23
C#
using System; using System.Linq; using System.Threading; using System.Diagnostics;   class Program { static void Main(string[] args) { Stopwatch sw = new Stopwatch();   sw.Start(); DoSomething(); sw.Stop();   Console.WriteLine("DoSomething() took {0}ms.", sw.Elapsed.TotalMill...
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#C.2B.2B
C++
#include <ctime> #include <iostream> using namespace std;   int identity(int x) { return x; } int sum(int num) { for (int i = 0; i < 1000000; i++) num += i; return num; }   double time_it(int (*action)(int), int arg) { clock_t start_time = clock(); action(arg); clock_t finis_time = clock(); return ((dou...
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...
#EchoLisp
EchoLisp
  (lib 'struct) ;; tables are based upon structures (lib 'sql) ;; sql-select function   ;; input table (define emps (make-table (struct emp (name id salary dept)))) ;; output table (define high (make-table (struct out (dept name salary))))   ;; sort/group procedure (define (get-high num-records: N into: high) (sql-s...
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...
#Befunge
Befunge
v123456789 --- >9 >48*,:55+\-0g,1v >9>066+0p076+0p^ ^,," |"_v#%3:- < :,,0537051v>:#,_$#^5#,5#+<>:#v_55+ 74 1098709<^+55"---+---+---"0<v520 69 04560123 >:!#v_0\1v>$2-:6%v>803 6 +0g\66++0p^ $_>#% v#9:-1_ 6/5 5 vv5!/*88\%*28 ::g0_^>9/#v_ "I", ,,5v>5++0p82*/3-:*+\:^v,_@ >"uoY", 0+5<v0+66_v#!%2:_55v >:^:" win!"\ 1-^ g...
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#BCPL
BCPL
get "libhdr"   let start() be move(4, 1, 2, 3) and move(n, src, via, dest) be if n > 0 do $( move(n-1, src, dest, via) writef("Move disk from pole %N to pole %N*N", src, dest); move(n-1, via, src, dest) $)
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#jq
jq
def thueMorse: 0, ({sb0: "0", sb1: "1", n:1 } | while( true; {n: (.sb0|length), sb0: (.sb0 + .sb1), sb1: (.sb1 + .sb0)} ) | .sb0[.n:] | explode[] | . - 48);
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Julia
Julia
function thuemorse(len::Int) rst = Vector{Int8}(len) rst[1] = 0 i, imax = 2, 1 while i ≤ len while i ≤ len && i ≤ 2 * imax rst[i] = 1 - rst[i-imax] i += 1 end imax *= 2 end return rst end   println(join(thuemorse(100)))
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Kotlin
Kotlin
fun thueMorse(n: Int): String { val sb0 = StringBuilder("0") val sb1 = StringBuilder("1") repeat(n) { val tmp = sb0.toString() sb0.append(sb1) sb1.append(tmp) } return sb0.toString() }   fun main() { for (i in 0..6) println("$i : ${thueMorse(i)}") }
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm
Tonelli-Shanks algorithm
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. 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 computational number theory, the Tonelli–Shanks algor...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Numerics   Module Module1   Class Solution ReadOnly root1 As BigInteger ReadOnly root2 As BigInteger ReadOnly exists As Boolean   Sub New(r1 As BigInteger, r2 As BigInteger, e As Boolean) root1 = r1 root2 = r2 exists = e End ...
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#Kotlin
Kotlin
// version 1.1.3   const val SPE = "\ufffe" // unused unicode char in Specials block const val SPF = "\uffff" // ditto   fun tokenize(str: String, sep: Char, esc: Char): List<String> { var s = str.replace("$esc$esc", SPE).replace("$esc$sep", SPF) s = if (s.last() == esc) // i.e. 'esc' not escaping anything ...
http://rosettacode.org/wiki/Total_circles_area
Total circles area
Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal dig...
#zkl
zkl
circles:=File("circles.txt").pump(List,'wrap(line){ line.split().apply("toFloat") // L(x,y,r) }); # compute the bounding box of the circles x_min:=(0.0).min(circles.apply(fcn([(x,y,r)]){ x - r })); // (0) not used, just the list of numbers x_max:=(0.0).max(circles.apply(fcn([(x,y,r)]){ x + r })); y_min:=(0.0).m...
http://rosettacode.org/wiki/Topological_sort
Topological sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Icon_and_Unicon
Icon and Unicon
record graph(nodes,arcs) global ex_name, in_name   procedure main() show(tsort(getgraph())) end   procedure tsort(g) t := "" while (n := g.nodes -- pnodes(g)) ~== "" do { t ||:= "("||n||")" g := delete(g,n) } if g.nodes == '' then return t write("graph contains the cycle:") write("\t...
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#Pascal
Pascal
program project1; uses Classes, sysutils; type TCurrent = record state : string; input : char; end; TMovesTo = record state : string; output : char; moves : char; end; var ST, ET: TDateTime; C:TCurrent; M:TMovesTo; Tape, Rules:TStringList; TP:integer; //TP = Tape position Blank...
http://rosettacode.org/wiki/Totient_function
Totient function
The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the integers up to a given positiv...
#Perl
Perl
use utf8; binmode STDOUT, ":utf8";   sub gcd { my ($u, $v) = @_; while ($v) { ($u, $v) = ($v, $u % $v); } return abs($u); }   push @𝜑, 0; for $t (1..10000) { push @𝜑, scalar grep { 1 == gcd($_,$t) } 1..$t; }   printf "𝜑(%2d) = %3d%s\n", $_, $𝜑[$_], $_ - $𝜑[$_] - 1 ? '' : ' Prime' for 1 .. 25; print...
http://rosettacode.org/wiki/Topswops
Topswops
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is composed of reversing the first  ...
#XPL0
XPL0
code ChOut=8, CrLf=9, IntOut=11; int N, Max, Card1(16), Card2(16);   proc Topswop(D); \Conway's card swopping game int D; \depth of recursion int I, J, C, T; [if D # N then \generate N! permutations of 1..N in Card1 [for I:= 0 to N-1 do [for J:= 0 to D-1 do \ch...
http://rosettacode.org/wiki/Topswops
Topswops
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is composed of reversing the first  ...
#zkl
zkl
fcn topswops(n){ flip:=fcn(xa){ if (not xa[0]) return(0); xa.reverse(0,xa[0]+1); // inplace, ~4x faster than making new lists return(1 + self.fcn(xa)); }; (0).pump(n,List):Utils.Helpers.permute(_).pump(List,"copy",flip).reduce("max"); }   foreach n in ([1 .. 10]){ println(n, ": ", topswops(n...
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#Groovy
Groovy
def radians = Math.PI/4 def degrees = 45   def d2r = { it*Math.PI/180 } def r2d = { it*180/Math.PI }   println "sin(\u03C0/4) = ${Math.sin(radians)} == sin(45\u00B0) = ${Math.sin(d2r(degrees))}" println "cos(\u03C0/4) = ${Math.cos(radians)} == cos(45\u00B0) = ${Math.cos(d2r(degrees))}" println "tan(\u03C0/4) = ${Math...
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#Python
Python
Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> def f(x): return abs(x) ** 0.5 + 5 * x**3   >>> print(', '.join('%s:%s' % (x, v if v<=400 else "TOO LARGE!") for x,v in ((y, f(float(y))) for y in input('\n...
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#R
R
S <- scan(n=11)   f <- function(x) sqrt(abs(x)) + 5*x^3   for (i in rev(S)) { res <- f(i) if (res > 400) print("Too large!") else print(res) }
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#PureBasic
PureBasic
#MaxLim = 999999   Procedure is_Prime(n) If n<=1 : ProcedureReturn #False ElseIf n<4  : ProcedureReturn #True ElseIf n%2=0: ProcedureReturn #False ElseIf n<9  : ProcedureReturn #True ElseIf n%3=0: ProcedureReturn #False Else Protected r=Round(Sqr(n),#PB_Round_Down) Protected f=5 While f<=r ...
http://rosettacode.org/wiki/Tree_traversal
Tree traversal
Task Implement a binary tree where each node carries an integer,   and implement:   pre-order,   in-order,   post-order,     and   level-order   traversal. Use those traversals to output the following tree: 1 / \ / \ / \ 2 3 / \ / 4 5 6 / ...
#Elena
Elena
import extensions; import extensions'routines; import system'collections;   singleton DummyNode { get generic() = EmptyEnumerable; }   class Node { rprop int Value; rprop Node Left; rprop Node Right;   constructor new(int value) { Value := value }   constructor new(int ...
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#COBOL
COBOL
  identification division. program-id. tokenize.   environment division. configuration section. repository. function all intrinsic.   data division. working-storage section. 01 period constant as ".". 01 cmma constant as ",".   01 start-w...
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#Clojure
Clojure
  (defn fib [] (map first (iterate (fn [[a b]] [b (+ a b)]) [0 1])))   (time (take 100 (fib)))  
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#Common_Lisp
Common Lisp
CL-USER> (time (reduce #'+ (make-list 100000 :initial-element 1))) Evaluation took: 0.151 seconds of real time 0.019035 seconds of user run time 0.01807 seconds of system run time 0 calls to %EVAL 0 page faults and 2,400,256 bytes consed.
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...
#Elena
Elena
import system'collections; import system'routines; import extensions; import extensions'routines; import extensions'text;   class Employee { prop string Name; prop string ID; prop int Salary; prop string Department;   string toPrintable() = new StringWriter() .writePaddingRigh...
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...
#C
C
#include <stdio.h> #include <stdlib.h>   int b[3][3]; /* board. 0: blank; -1: computer; 1: human */   int check_winner() { int i; for (i = 0; i < 3; i++) { if (b[i][0] && b[i][1] == b[i][0] && b[i][2] == b[i][0]) return b[i][0]; if (b[0][i] && b[1][i] == b[0][i] && b[2][i] == b[0][i]) return b[0][i]; } if...
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Befunge
Befunge
48*2+1>#v_:!#@_0" ksid evoM">:#,_$:8/:.v >8v8:<$#<+9-+*2%3\*3/3:,+55.+1%3:$_,#!>#:< : >/!#^_:0\:8/1-8vv,_$8%:3/1+.>0" gep ot"^ ^++3-%3\*2/3:%8\*<>:^:"from peg "0\*8-1<
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Lambdatalk
Lambdatalk
    {def thue_morse {def thue_morse.r {lambda {:steps :s1 :s2 :i} {if {> :i :steps} then :s1 else {thue_morse.r :steps :s1:s2 :s2:s1 {+ :i 1}}}}} {lambda {:steps} {thue_morse.r :steps 0 1 1}}} -> thue_morse   {thue_morse 6} -> 0110100110010110100101100110100110010110011010010110100110010110    
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Lua
Lua
ThueMorse = {sequence = "0"}   function ThueMorse:show () print(self.sequence) end   function ThueMorse:addBlock () local newBlock = "" for bit = 1, self.sequence:len() do if self.sequence:sub(bit, bit) == "1" then newBlock = newBlock .. "0" else newBlock = newBlock ....
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm
Tonelli-Shanks algorithm
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. 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 computational number theory, the Tonelli–Shanks algor...
#Wren
Wren
import "/dynamic" for Tuple import "/big" for BigInt   var Solution = Tuple.create("Solution", ["root1", "root2", "exists"])   var ts = Fn.new { |n, p| if (n is Num) n = BigInt.new(n) if (p is Num) p = BigInt.new(p)   var powModP = Fn.new { |a, e| a.modPow(e, p) }   var ls = Fn.new { |a| powModP.call(a,...
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#Lingo
Lingo
-- in some movie script   on tokenize (str, sep, esc) l = [] _player.itemDelimiter = sep cnt = str.item.count repeat with i = 1 to cnt prev = l.getLast() -- can be VOID if _trailEscCount(prev, esc) mod 2 then l[l.count] = prev.char[1..prev.length-1]&sep&str.item[i] else l.add(str.item[i]...
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#Lua
Lua
function tokenise (str, sep, esc) local strList, word, escaped, ch = {}, "", false for pos = 1, #str do ch = str:sub(pos, pos) if ch == esc then if escaped then word = word .. ch escaped = false else escaped = true ...
http://rosettacode.org/wiki/Topological_sort
Topological sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#J
J
dependencySort=: monad define parsed=. <@;:;._2 y names=. {.&>parsed depends=. (> =@i.@#) names e.S:1 parsed depends=. (+. +./ .*.~)^:_ depends assert.-.1 e. (<0 1)|:depends (-.&names ~.;parsed),names /: +/"1 depends )
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#Perl
Perl
use strict; use warnings;   sub run_utm { my %o = @_; my $st = $o{state} // die "init head state undefined"; my $blank = $o{blank} // die "blank symbol undefined"; my @rules = @{$o{rules}} or die "rules undefined"; my @tape = $o{tape} ? @{$o{tape}} : ($blank); my $halt = $o{halt};   my $pos = $o{pos} // 0; $pos...
http://rosettacode.org/wiki/Totient_function
Totient function
The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the integers up to a given positiv...
#Phix
Phix
function totient(integer n) integer tot = n, i = 2 while i*i<=n do if mod(n,i)=0 then while true do n /= i if mod(n,i)!=0 then exit end if end while tot -= tot/i end if i += iff(i=2?1:2) end while if n>1 then ...
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#Haskell
Haskell
fromDegrees :: Floating a => a -> a fromDegrees deg = deg * pi / 180   toDegrees :: Floating a => a -> a toDegrees rad = rad * 180 / pi   main :: IO () main = mapM_ print [ sin (pi / 6) , sin (fromDegrees 30) , cos (pi / 6) , cos (fromDegrees 30) , tan (pi / 6) , tan (fromDegrees 30) ,...
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#Racket
Racket
  #lang racket   (define input (for/list ([i 11]) (printf "Enter a number (~a of 11): " (+ 1 i)) (read)))   (for ([x (reverse input)]) (define res (+ (sqrt (abs x)) (* 5 (expt x 3)))) (if (> res 400) (displayln "Overflow!") (printf "f(~a) = ~a\n" x res)))  
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#Raku
Raku
my @nums = prompt("Please type 11 space-separated numbers: ").words until @nums == 11; for @nums.reverse -> $n { my $r = $n.abs.sqrt + 5 * $n ** 3; say "$n\t{ $r > 400 ?? 'Urk!' !! $r }"; }
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#Python
Python
maxprime = 1000000   def primes(n): multiples = set() prime = [] for i in range(2, n+1): if i not in multiples: prime.append(i) multiples.update(set(range(i*i, n+1, i))) return prime   def truncatableprime(n): 'Return a longest left and right truncatable primes below ...
http://rosettacode.org/wiki/Tree_traversal
Tree traversal
Task Implement a binary tree where each node carries an integer,   and implement:   pre-order,   in-order,   post-order,     and   level-order   traversal. Use those traversals to output the following tree: 1 / \ / \ / \ 2 3 / \ / 4 5 6 / ...
#Elisa
Elisa
  component BinaryTreeTraversals (Tree, Element); type Tree; type Node = Tree; Tree (LeftTree = Tree, Element, RightTree = Tree) -> Tree; Leaf (Element) -> Node; Node (Tree) -> Node; Item (Node) ...
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#CoffeeScript
CoffeeScript
  arr = "Hello,How,Are,You,Today".split "," console.log arr.join "."  
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#ColdFusion
ColdFusion
  <cfoutput> <cfset wordListTag = "Hello,How,Are,You,Today"> #Replace( wordListTag, ",", ".", "all" )# </cfoutput>  
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#D
D
import std.stdio, std.datetime;   int identity(int x) { return x; }   int sum(int num) { foreach (i; 0 .. 100_000_000) num += i; return num; }   double timeIt(int function(int) func, int arg) { StopWatch sw; sw.start(); func(arg); sw.stop(); return sw.peek().usecs / 1_000_000.0; ...
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#E
E
def countTo(x) { println("Counting...") for _ in 1..x {} println("Done!") }   def MX := <unsafe:java.lang.management.makeManagementFactory> def threadMX := MX.getThreadMXBean() require(threadMX.isCurrentThreadCpuTimeSupported()) threadMX.setThreadCpuTimeEnabled(true)   for count in [10000, 100000] { def start := th...
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...
#Elixir
Elixir
defmodule TopRank do def per_groupe(data, n) do String.split(data, ~r/(\n|\r\n|\r)/, trim: true) |> Enum.drop(1) |> Enum.map(fn person -> String.split(person,",") end) |> Enum.group_by(fn person -> department(person) end) |> Enum.each(fn {department,group} -> IO.puts "Department: #{depart...
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...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace RosettaTicTacToe { class Program {   /*================================================================ *Pieces (players and board) *================================================================*/ ...
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#BQN
BQN
Move ← { 𝕩⊑⊸≤0 ? ⟨⟩; 𝕊 n‿from‿to‿via: l ← 𝕊 ⟨n-1, from, via, to⟩ r ← 𝕊 ⟨n-1, via, to, from⟩ l∾(<from‿to)∾r } {"Move disk from pole "∾(•Fmt 𝕨)∾" to pole "∾•Fmt 𝕩}´˘>Move 4‿1‿2‿3
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ThueMorse[Range[20]]
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Modula-2
Modula-2
MODULE ThueMorse; FROM Strings IMPORT Concat; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE Sequence(steps : CARDINAL); TYPE String = ARRAY[0..128] OF CHAR; VAR sb1,sb2,tmp : String; i : CARDINAL; BEGIN sb1 := "0"; sb2 := "1";   WHILE i<steps DO tmp := sb1; Concat(sb1, s...
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm
Tonelli-Shanks algorithm
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. 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 computational number theory, the Tonelli–Shanks algor...
#zkl
zkl
var BN=Import("zklBigNum"); fcn modEq(a,b,p) { (a-b)%p==0 } fcn legendre(a,p){ a.powm((p - 1)/2,p) }   fcn tonelli(n,p){ //(BigInt,Int|BigInt) _assert_(legendre(n,p)==1, "not a square (mod p)"+vm.arglist); q,s:=p-1,0; while(q.isEven){ q/=2; s+=1; } if(s==1) return(n.powm((p+1)/4,p)); z:=[BN(2)..p].filter...
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[Tokenize] Tokenize[str_String, escape_String : "^", sep_String : "|"] := Module[{results = {}, token = "", state = 0, a}, a = Characters[str]; Do[ If[state == 0, Switch[c, escape, state = 1 , sep, AppendTo[results, token]; token = ""; , _, token = token...
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#Nim
Nim
import streams   proc tokenize(s: Stream, sep: static[char] = '|', esc: static[char] = '^'): seq[string] = var buff = "" while not s.atEnd(): let c = s.readChar case c of sep: result.add buff buff = "" of esc: buff.add s.readChar else: buff.add c result.add buff   for i...