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/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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon. The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on. A tool exists that extracts library dependencies. Task Write a function that will return a valid compile order of VHDL libraries from their dependencies. Assume library names are single words. Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given. Any self dependencies should be ignored. Any un-orderable dependencies should be flagged. Use the following data as an example: LIBRARY LIBRARY DEPENDENCIES ======= ==================== des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee dw01 ieee dw01 dware gtech dw02 ieee dw02 dware dw03 std synopsys dware dw03 dw02 dw01 ieee gtech dw04 dw04 ieee dw01 dware gtech dw05 dw05 ieee dware dw06 dw06 ieee dware dw07 ieee dware dware ieee dware gtech ieee gtech ramlib std ieee std_cell_lib ieee std_cell_lib synopsys Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01. C.f.   Topological sort/Extracted top item. There are two popular algorithms for topological sorting:   Kahn's 1962 topological sort [1]   depth-first search [2] [3]
#Java
Java
import java.util.*;   public class TopologicalSort {   public static void main(String[] args) { String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05," + "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys";   Graph g = new Graph(s, new int[][]{ {2, 0}, {2, 14}, {2, 13}, {2, 4}, {2, 3}, {2, 12}, {2, 1}, {3, 1}, {3, 10}, {3, 11}, {4, 1}, {4, 10}, {5, 0}, {5, 14}, {5, 10}, {5, 4}, {5, 3}, {5, 1}, {5, 11}, {6, 1}, {6, 3}, {6, 10}, {6, 11}, {7, 1}, {7, 10}, {8, 1}, {8, 10}, {9, 1}, {9, 10}, {10, 1}, {11, 1}, {12, 0}, {12, 1}, {13, 1} });   System.out.println("Topologically sorted order: "); System.out.println(g.topoSort()); } }   class Graph { String[] vertices; boolean[][] adjacency; int numVertices;   public Graph(String s, int[][] edges) { vertices = s.split(","); numVertices = vertices.length; adjacency = new boolean[numVertices][numVertices];   for (int[] edge : edges) adjacency[edge[0]][edge[1]] = true; }   List<String> topoSort() { List<String> result = new ArrayList<>(); List<Integer> todo = new LinkedList<>();   for (int i = 0; i < numVertices; i++) todo.add(i);   try { outer: while (!todo.isEmpty()) { for (Integer r : todo) { if (!hasDependency(r, todo)) { todo.remove(r); result.add(vertices[r]); // no need to worry about concurrent modification continue outer; } } throw new Exception("Graph has cycles"); } } catch (Exception e) { System.out.println(e); return null; } return result; }   boolean hasDependency(Integer r, List<Integer> todo) { for (Integer c : todo) { if (adjacency[r][c]) return true; } return false; } }
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 a machine capable of taking the definition of any other Turing machine and executing it. Of course, you will not have an infinite tape, but you should emulate this as much as is possible. The three permissible actions on the tape are "left", "right" and "stay". To test your universal Turing machine (and prove your programming language is Turing complete!), you should execute the following two Turing machines based on the following definitions. Simple incrementer States: q0, qf Initial state: q0 Terminating states: qf Permissible symbols: B, 1 Blank symbol: B Rules: (q0, 1, 1, right, q0) (q0, B, 1, stay, qf) The input for this machine should be a tape of 1 1 1 Three-state busy beaver States: a, b, c, halt Initial state: a Terminating states: halt Permissible symbols: 0, 1 Blank symbol: 0 Rules: (a, 0, 1, right, b) (a, 1, 1, left, c) (b, 0, 1, left, a) (b, 1, 1, right, b) (c, 0, 1, left, b) (c, 1, 1, stay, halt) The input for this machine should be an empty tape. Bonus: 5-state, 2-symbol probable Busy Beaver machine from Wikipedia States: A, B, C, D, E, H Initial state: A Terminating states: H Permissible symbols: 0, 1 Blank symbol: 0 Rules: (A, 0, 1, right, B) (A, 1, 1, left, C) (B, 0, 1, right, C) (B, 1, 1, right, B) (C, 0, 1, right, D) (C, 1, 0, left, E) (D, 0, 1, left, A) (D, 1, 1, left, D) (E, 0, 1, stay, H) (E, 1, 0, left, A) The input for this machine should be an empty tape. This machine runs for more than 47 millions steps.
#Phix
Phix
with javascript_semantics enum name, initState, endState, blank, rules -- Machine definitions constant incrementer = { /*name =*/ "Simple incrementer", /*initState =*/ "q0", /*endState =*/ "qf", /*blank =*/ "B", /*rules =*/ { {"q0", "1", "1", "right", "q0"}, {"q0", "B", "1", "stay", "qf"} } } constant threeStateBB = { /*name =*/ "Three-state busy beaver", /*initState =*/ "a", /*endState =*/ "halt", /*blank =*/ "0", /*rules =*/ { {"a", "0", "1", "right", "b"}, {"a", "1", "1", "left", "c"}, {"b", "0", "1", "left", "a"}, {"b", "1", "1", "right", "b"}, {"c", "0", "1", "left", "b"}, {"c", "1", "1", "stay", "halt"} } } constant fiveStateBB = { /*name =*/ "Five-state busy beaver", /*initState =*/ "A", /*endState =*/ "H", /*blank =*/ "0", /*rules =*/ { {"A", "0", "1", "right", "B"}, {"A", "1", "1", "left", "C"}, {"B", "0", "1", "right", "C"}, {"B", "1", "1", "right", "B"}, {"C", "0", "1", "right", "D"}, {"C", "1", "0", "left", "E"}, {"D", "0", "1", "left", "A"}, {"D", "1", "1", "left", "D"}, {"E", "0", "1", "stay", "H"}, {"E", "1", "0", "left", "A"} } } procedure show(string state, integer headpos, sequence tape) printf(1," %-6s | ",{state}) for p=1 to length(tape) do printf(1,iff(p=headpos?"[%s]":" %s "),{tape[p]}) end for printf(1,"\n") end procedure -- a universal turing machine procedure UTM(sequence machine, sequence tape, integer countOnly=0) string state = machine[initState] integer headpos = 1, counter = 0 printf(1,"\n\n%s\n%s\n",{machine[name],repeat('=',length(machine[name]))}) if not countOnly then printf(1," State | Tape [head]\n---------------------\n") end if while 1 do if headpos>length(tape) then tape = append(tape,machine[blank]) elsif headpos<1 then tape = prepend(tape,machine[blank]) headpos = 1 end if if not countOnly then show(state, headpos, tape) end if for i=1 to length(machine[rules]) do sequence rule = machine[rules][i] if rule[1]=state and rule[2]=tape[headpos] then tape[headpos] = rule[3] if rule[4] == "left" then headpos -= 1 end if if rule[4] == "right" then headpos += 1 end if state = rule[5] exit end if end for counter += 1 if state=machine[endState] then exit end if end while if countOnly then printf(1,"Steps taken: %d\n",{counter}) else show(state, headpos, tape) end if end procedure atom t0 = time() UTM(incrementer, {"1", "1", "1"}) UTM(threeStateBB, {}) if platform()!=JS then -- 1min 7s UTM(fiveStateBB, {}, countOnly:=1) end if ?elapsed(time()-t0)
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 positive integer   n   that are relatively prime to   n   counts the integers   k   in the range   1 ≤ k ≤ n   for which the greatest common divisor   gcd(n,k)   is equal to   1   counts numbers   ≤ n   and   prime to   n If the totient number   (for N)   is one less than   N,   then   N   is prime. Task Create a   totient   function and:   Find and display   (1 per line)   for the 1st   25   integers:   the integer   (the index)   the totient number for that integer   indicate if that integer is prime   Find and display the   count   of the primes up to          100   Find and display the   count   of the primes up to       1,000   Find and display the   count   of the primes up to     10,000   Find and display the   count   of the primes up to   100,000     (optional) Show all output here. Related task   Perfect totient numbers Also see   Wikipedia: Euler's totient function.   MathWorld: totient function.   OEIS: Euler totient function phi(n).
#PicoLisp
PicoLisp
(gc 32) (de gcd (A B) (until (=0 B) (let M (% A B) (setq A B B M) ) ) (abs A) ) (de totient (N) (let C 0 (for I N (and (=1 (gcd N I)) (inc 'C)) ) (cons C (= C (dec N))) ) ) (de p? (N) (let C 0 (for A N (and (cdr (totient A)) (inc 'C) ) ) C ) ) (let Fmt (3 7 10) (tab Fmt "N" "Phi" "Prime?") (tab Fmt "-" "---" "------") (for N 25 (tab Fmt N (car (setq @ (totient N))) (cdr @) ) ) ) (println (mapcar p? (25 100 1000 10000 100000)) )
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 is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle). For the inverse functions,   use the same number and convert its answer to radians and degrees. If your language does not have trigonometric functions available or only has some available,   write functions to calculate the functions based on any   known approximation or identity.
#HicEst
HicEst
pi = 4.0 * ATAN(1.0) dtor = pi / 180.0 rtod = 180.0 / pi radians = pi / 4.0 degrees = 45.0   WRITE(ClipBoard) SIN(radians), SIN(degrees*dtor) WRITE(ClipBoard) COS(radians), COS(degrees*dtor) WRITE(ClipBoard) TAN(radians), TAN(degrees*dtor) WRITE(ClipBoard) ASIN(SIN(radians)), ASIN(SIN(degrees*dtor))*rtod WRITE(ClipBoard) ACOS(COS(radians)), ACOS(COS(degrees*dtor))*rtod WRITE(ClipBoard) ATAN(TAN(radians)), ATAN(TAN(degrees*dtor))*rtod
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 the algorithm. From the wikipedia entry: ask for 11 numbers to be read into a sequence S reverse sequence S for each item in sequence S result := call a function to do an operation if result overflows alert user else print result The task is to implement the algorithm: Use the function:     f ( x ) = | x | 0.5 + 5 x 3 {\displaystyle f(x)=|x|^{0.5}+5x^{3}} The overflow condition is an answer of greater than 400. The 'user alert' should not stop processing of other items of the sequence. Print a prompt before accepting eleven, textual, numeric inputs. You may optionally print the item as well as its associated result, but the results must be in reverse order of input. The sequence   S   may be 'implied' and so not shown explicitly. Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#REXX
REXX
/*REXX program implements the Trabb─Pardo-Knuth algorithm for N numbers (default is 11).*/ numeric digits 200 /*the number of digits precision to use*/ parse arg N .; if N=='' | N=="," then N=11 /*Not specified? Then use the default.*/ maxValue= 400 /*the maximum value f(x) can have. */ wid= 20 /* ··· but only show this many digits.*/ frac= 5 /* ··· show this # of fractional digs.*/ say ' _____' /* ◄─── this SAY displays a vinculum.*/ say 'function: ƒ(x) ≡ √ │x│ + (5 * x^3)' prompt= 'enter ' N " numbers for the Trabb─Pardo─Knuth algorithm: (or Quit)"   do ask=0; say; /*░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░*/ say prompt; say; pull $; say /*░*/ if abbrev('QUIT',$,1) then do; say 'quitting.'; exit 1; end /*░*/ ok=0 /*░*/ select /*validate there're N numbers.*/ /*░*/ when $='' then say "no numbers entered" /*░*/ when words($)<N then say "not enough numbers entered" /*░*/ when words($)>N then say "too many numbers entered" /*░*/ otherwise ok=1 /*░*/ end /*select*/ /*░*/ if \ok then iterate /* [↓] W=max width. */ /*░*/ w=0; do v=1 for N; _=word($, v); w=max(w, length(_) ) /*░*/ if datatype(_, 'N') then iterate /*numeric ?*/ /*░*/ say _ "isn't numeric"; iterate ask /*░*/ end /*v*/ /*░*/ leave /*░*/ end /*ask*/ /*░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░*/   say 'numbers entered: ' $ say do i=N by -1 for N; #=word($, i) / 1 /*process the numbers in reverse. */ g = fmt( f( # ) ) /*invoke function ƒ with arg number.*/ gw=right( 'ƒ('#") ", w+7) /*nicely formatted ƒ(number). */ if g>maxValue then say gw "is > " maxValue ' ['space(g)"]" else say gw " = " g end /*i*/ /* [↑] display the result to terminal.*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ f: procedure; parse arg x; return sqrt( abs(x) ) + 5 * x**3 /*──────────────────────────────────────────────────────────────────────────────────────*/ fmt: z=right(translate(format(arg(1), wid, frac), 'e', "E"), wid) /*right adjust; use e*/ if pos(.,z)\==0 then z=left(strip(strip(z,'T',0),"T",.),wid) /*strip trailing 0 &.*/ return right(z, wid - 4*(pos('e', z)==0) ) /*adjust: no exponent*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; numeric form; h=d+6 numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g *.5'e'_ % 2 do j=0 while h>9; m.j=h; h=h % 2 + 1; end /*j*/ do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g
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, 739, 73, and 7 formed by removing digits from its right are also prime. No zeroes are allowed in truncatable primes. Task The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied). Related tasks Find largest left truncatable prime in a given base Sieve of Eratosthenes See also Truncatable Prime from MathWorld.]
#Quackery
Quackery
1000000 eratosthenes   [ false swap number$ witheach [ char 0 = if [ conclude not ] ] ] is haszero ( n --> b )   [ 10 / ] is truncright ( n --> n )   [ number$ behead drop $->n drop ] is truncleft ( n --> n )   [ dup isprime not iff [ drop false ] done dup haszero iff [ drop false ] done true swap [ truncleft dup 0 > while dup isprime not iff [ dip not ] done again ] drop ] is ltruncatable ( n --> b )   [ dup isprime not iff [ drop false ] done dup haszero iff [ drop false ] done true swap [ truncright dup 0 > while dup isprime not iff [ dip not ] done again ] drop ] is rtruncatable ( n --> b )   say "Left: " 1000000 times [ i ltruncatable if [ i echo conclude ] ] cr say "Right: " 1000000 times [ i rtruncatable if [ i echo conclude ] ] cr
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 / / \ 7 8 9 The correct output should look like this: preorder: 1 2 4 7 5 3 6 8 9 inorder: 7 4 2 5 1 8 6 9 3 postorder: 7 4 5 2 8 9 6 3 1 level-order: 1 2 3 4 5 6 7 8 9 See also   Wikipedia article:   Tree traversal.
#Elixir
Elixir
defmodule Tree_Traversal do defp tnode, do: {} defp tnode(v), do: {:node, v, {}, {}} defp tnode(v,l,r), do: {:node, v, l, r}   defp preorder(_,{}), do: :ok defp preorder(f,{:node,v,l,r}) do f.(v) preorder(f,l) preorder(f,r) end   defp inorder(_,{}), do: :ok defp inorder(f,{:node,v,l,r}) do inorder(f,l) f.(v) inorder(f,r) end   defp postorder(_,{}), do: :ok defp postorder(f,{:node,v,l,r}) do postorder(f,l) postorder(f,r) f.(v) end   defp levelorder(_, []), do: [] defp levelorder(f, [{}|t]), do: levelorder(f, t) defp levelorder(f, [{:node,v,l,r}|t]) do f.(v) levelorder(f, t++[l,r]) end defp levelorder(f, x), do: levelorder(f, [x])   def main do tree = tnode(1, tnode(2, tnode(4, tnode(7), tnode()), tnode(5, tnode(), tnode())), tnode(3, tnode(6, tnode(8), tnode(9)), tnode())) f = fn x -> IO.write "#{x} " end IO.write "preorder: " preorder(f, tree) IO.write "\ninorder: " inorder(f, tree) IO.write "\npostorder: " postorder(f, tree) IO.write "\nlevelorder: " levelorder(f, tree) IO.puts "" end end   Tree_Traversal.main
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: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Common_Lisp
Common Lisp
(defun comma-split (string) (loop for start = 0 then (1+ finish) for finish = (position #\, string :start start) collecting (subseq string start finish) until (null finish)))   (defun write-with-periods (strings) (format t "~{~A~^.~}" 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: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Cowgol
Cowgol
include "cowgol.coh"; include "strings.coh";   # Tokenize a string. Note: the string is modified in place. sub tokenize(sep: uint8, str: [uint8], out: [[uint8]]): (length: intptr) is length := 0; loop [out] := str; out := @next out; length := length + 1; while [str] != 0 and [str] != sep loop str := @next str; end loop; if [str] == sep then [str] := 0; str := @next str; else break; end if; end loop; end sub;   # The string var string: [uint8] := "Hello,How,Are,You,Today";   # Make a mutable copy var buf: uint8[64]; CopyString(string, &buf[0]);   # Tokenize the copy var parts: [uint8][64]; var length := tokenize(',', &buf[0], &parts[0]) as @indexof parts;   # Print each string var i: @indexof parts := 0; while i < length loop print(parts[i]); print(".\n"); i := i + 1; end loop;
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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Elena
Elena
import system'calendar; import system'routines; import system'threading; import system'math; import extensions;   someProcess() { threadControl.sleep(1000);   new Range(0,10000).filterBy:(x => x.mod:2 == 0).summarize(); }   public program() { var start := now;   someProcess();   var end := now;   console.printLine("Time elapsed in msec:",(end - start).Milliseconds) }
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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Elixir
Elixir
iex(10)> :timer.tc(fn -> Enum.each(1..100000, fn x -> x*x end) end) {236000, :ok}
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,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190
#Erlang
Erlang
<-module( top_rank_per_group ).   -export( [employees/0, employees_in_department/2, highest_payed/2, task/1] ).   -record( employee, {name, id, salery, department} ).   employees() -> [#employee{name="Tyler Bennett", id="E10297", salery=32000, department="D101"}, #employee{name="John Rappl", id="E21437", salery=47000, department="D101"}, #employee{name="George Woltman", id="E00127", salery=53500, department="D050"}, #employee{name="Adam Smith", id="E63535", salery=18000, department="D202"}, #employee{name="Claire Buckman", id="E39876", salery=27800, department="D202"}, #employee{name="David McClellan", id="E04242", salery=41500, department="D101"}, #employee{name="Rich Holcomb", id="E01234", salery=49500, department="D202"}, #employee{name="Nathan Adams", id="E41298", salery=21900, department="D050"}, #employee{name="Richard Potter", id="E43128", salery=15900, department="D101"}, #employee{name="David Motsinger", id="E27002", salery=19250, department="D202"}, #employee{name="Tim Sampair", id="E03033", salery=27000, department="D101"}, #employee{name="Kim Arlich", id="E10001", salery=57000, department="D190"}, #employee{name="Timothy Grove", id="E16398", salery=29900, department="D190"}].   employees_in_department( Department, Employees ) -> [X || #employee{department=D}=X <- Employees, D =:= Department].   highest_payed( N, Employees ) -> {Highest, _T} = lists:split( N, lists:reverse(lists:keysort(#employee.salery, Employees)) ), Highest.   task( N ) -> Employees = employees(), Departments = lists:usort( [X || #employee{department=X} <- Employees] ), Employees_in_departments = [employees_in_department(X, Employees) || X <- Departments], Highest_payed_in_departments = [highest_payed(N, Xs) || Xs <- Employees_in_departments], [task_write(X) || X <- Highest_payed_in_departments].       task_write( Highest_payeds ) -> [io:fwrite( "~p ~p: ~p~n", [Department, Salery, Name]) || #employee{department=Department, salery=Salery, name=Name} <- Highest_payeds], io:nl().  
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.   Wikipedia tic-tac-toe.
#C.2B.2B
C++
  #include <windows.h> #include <iostream> #include <string>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- enum players { Computer, Human, Draw, None }; const int iWin[8][3] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } };   //-------------------------------------------------------------------------------------------------- class ttt { public: ttt() { _p = rand() % 2; reset(); }   void play() { int res = Draw; while( true ) { drawGrid(); while( true ) { if( _p ) getHumanMove(); else getComputerMove();   drawGrid();   res = checkVictory(); if( res != None ) break;   ++_p %= 2; }   if( res == Human ) cout << "CONGRATULATIONS HUMAN --- You won!"; else if( res == Computer ) cout << "NOT SO MUCH A SURPRISE --- I won!"; else cout << "It's a draw!";   cout << endl << endl;   string r; cout << "Play again( Y / N )? "; cin >> r; if( r != "Y" && r != "y" ) return;   ++_p %= 2; reset();   } }   private: void reset() { for( int x = 0; x < 9; x++ ) _field[x] = None; }   void drawGrid() { system( "cls" );   COORD c = { 0, 2 }; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );   cout << " 1 | 2 | 3 " << endl; cout << "---+---+---" << endl; cout << " 4 | 5 | 6 " << endl; cout << "---+---+---" << endl; cout << " 7 | 8 | 9 " << endl << endl << endl;   int f = 0; for( int y = 0; y < 5; y += 2 ) for( int x = 1; x < 11; x += 4 ) { if( _field[f] != None ) { COORD c = { x, 2 + y }; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); string o = _field[f] == Computer ? "X" : "O"; cout << o; } f++; }   c.Y = 9; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); }   int checkVictory() { for( int i = 0; i < 8; i++ ) { if( _field[iWin[i][0]] != None && _field[iWin[i][0]] == _field[iWin[i][1]] && _field[iWin[i][1]] == _field[iWin[i][2]] ) { return _field[iWin[i][0]]; } }   int i = 0; for( int f = 0; f < 9; f++ ) { if( _field[f] != None ) i++; } if( i == 9 ) return Draw;   return None; }   void getHumanMove() { int m; cout << "Enter your move ( 1 - 9 ) "; while( true ) { m = 0; do { cin >> m; } while( m < 1 && m > 9 );   if( _field[m - 1] != None ) cout << "Invalid move. Try again!" << endl; else break; }   _field[m - 1] = Human; }   void getComputerMove() { int move = 0;   do{ move = rand() % 9; } while( _field[move] != None );   for( int i = 0; i < 8; i++ ) { int try1 = iWin[i][0], try2 = iWin[i][1], try3 = iWin[i][2];   if( _field[try1] != None && _field[try1] == _field[try2] && _field[try3] == None ) { move = try3; if( _field[try1] == Computer ) break; }   if( _field[try1] != None && _field[try1] == _field[try3] && _field[try2] == None ) { move = try2; if( _field[try1] == Computer ) break; }   if( _field[try2] != None && _field[try2] == _field[try3] && _field[try1] == None ) { move = try1; if( _field[try2] == Computer ) break; } } _field[move] = Computer;   }     int _p; int _field[9]; }; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { srand( GetTickCount() );   ttt tic; tic.play();   return 0; } //--------------------------------------------------------------------------------------------------  
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Bracmat
Bracmat
( ( move = n from to via .  !arg:(?n,?from,?to,?via) & (  !n:>0 & move$(!n+-1,!from,!via,!to) & out$("Move disk from pole " !from " to pole " !to) & move$(!n+-1,!via,!to,!from) | ) ) & 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
#NewLISP
NewLISP
(define (Thue-Morse loops) (setf TM '(0)) (println TM) (for (i 1 (-- loops)) (setf tmp TM) (replace '0 tmp '_) (replace '1 tmp '0) (replace '_ tmp '1) (setf TM (append TM tmp)) (println TM) ) )   (Thue-Morse 5) (exit)  
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
#Nim
Nim
import sequtils, strutils   iterator thueMorse(maxSteps = int.high): string = var val = @[0] var count = 0 while true: yield val.join() inc count if count == maxSteps: break val &= val.mapIt(1 - it)   for bits in thueMorse(6): echo bits
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 separated by the separators, become the elements of the output list. Empty fields should be preserved, even at the start and end. Rules for escaping: "Escaped" means preceded by an occurrence of the escape character that is not already escaped itself. When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special). Each occurrence of the escape character that was used to escape something, should not become part of the output. Test case Demonstrate that your function satisfies the following test-case: Input Output string: one^|uno||three^^^^|four^^^|^cuatro| separator character: | escape character: ^ one|uno three^^ four^|cuatro (Print the output list in any format you like, as long as it is it easy to see what the fields are.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#OCaml
OCaml
let split_with_escaping ~esc ~sep s = let len = String.length s in let buf = Buffer.create 16 in let rec loop i = if i = len then [Buffer.contents buf] else if s.[i] = esc && i + 1 < len then begin Buffer.add_char buf s.[i + 1]; loop (i + 2) end else if s.[i] = sep then begin let s = Buffer.contents buf in Buffer.clear buf; s :: loop (i + 1) end else begin Buffer.add_char buf s.[i]; loop (i + 1) end in loop 0
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon. The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on. A tool exists that extracts library dependencies. Task Write a function that will return a valid compile order of VHDL libraries from their dependencies. Assume library names are single words. Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given. Any self dependencies should be ignored. Any un-orderable dependencies should be flagged. Use the following data as an example: LIBRARY LIBRARY DEPENDENCIES ======= ==================== des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee dw01 ieee dw01 dware gtech dw02 ieee dw02 dware dw03 std synopsys dware dw03 dw02 dw01 ieee gtech dw04 dw04 ieee dw01 dware gtech dw05 dw05 ieee dware dw06 dw06 ieee dware dw07 ieee dware dware ieee dware gtech ieee gtech ramlib std ieee std_cell_lib ieee std_cell_lib synopsys Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01. C.f.   Topological sort/Extracted top item. There are two popular algorithms for topological sorting:   Kahn's 1962 topological sort [1]   depth-first search [2] [3]
#JavaScript
JavaScript
const libs = `des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee dw01 ieee dw01 dware gtech dw02 ieee dw02 dware dw03 std synopsys dware dw03 dw02 dw01 ieee gtech dw04 dw04 ieee dw01 dware gtech dw05 dw05 ieee dware dw06 dw06 ieee dware dw07 ieee dware dware ieee dware gtech ieee gtech ramlib std ieee std_cell_lib ieee std_cell_lib synopsys`;   // A map of the input data, with the keys as the packages, and the values as // and array of packages on which it depends. const D = libs .split('\n') .map(e => e.split(' ').filter(e => e != '')) .reduce((p, c) => p.set(c[0], c.filter((e, i) => i > 0 && e !== c[0] ? e : null)), new Map()); [].concat(...D.values()).forEach(e => { D.set(e, D.get(e) || []) });   // The above map rotated so that it represents a DAG of the form // Map { // A => [ A, B, C], // B => [C], // C => [] // } // where each key represents a node, and the array contains the edges. const G = [...D.keys()].reduce((p, c) => p.set( c, [...D.keys()].filter(e => D.get(e).includes(c))), new Map() );   // An array of leaf nodes; nodes with 0 in degrees. const Q = [...D.keys()].filter(e => D.get(e).length == 0);   // The result array. const S = []; while (Q.length) { const u = Q.pop(); S.push(u); G.get(u).forEach(v => { D.set(v, D.get(v).filter(e => e !== u)); if (D.get(v).length == 0) { Q.push(v); } }); }   console.log('Solution:', S);  
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 a machine capable of taking the definition of any other Turing machine and executing it. Of course, you will not have an infinite tape, but you should emulate this as much as is possible. The three permissible actions on the tape are "left", "right" and "stay". To test your universal Turing machine (and prove your programming language is Turing complete!), you should execute the following two Turing machines based on the following definitions. Simple incrementer States: q0, qf Initial state: q0 Terminating states: qf Permissible symbols: B, 1 Blank symbol: B Rules: (q0, 1, 1, right, q0) (q0, B, 1, stay, qf) The input for this machine should be a tape of 1 1 1 Three-state busy beaver States: a, b, c, halt Initial state: a Terminating states: halt Permissible symbols: 0, 1 Blank symbol: 0 Rules: (a, 0, 1, right, b) (a, 1, 1, left, c) (b, 0, 1, left, a) (b, 1, 1, right, b) (c, 0, 1, left, b) (c, 1, 1, stay, halt) The input for this machine should be an empty tape. Bonus: 5-state, 2-symbol probable Busy Beaver machine from Wikipedia States: A, B, C, D, E, H Initial state: A Terminating states: H Permissible symbols: 0, 1 Blank symbol: 0 Rules: (A, 0, 1, right, B) (A, 1, 1, left, C) (B, 0, 1, right, C) (B, 1, 1, right, B) (C, 0, 1, right, D) (C, 1, 0, left, E) (D, 0, 1, left, A) (D, 1, 1, left, D) (E, 0, 1, stay, H) (E, 1, 0, left, A) The input for this machine should be an empty tape. This machine runs for more than 47 millions steps.
#PHL
PHL
module turing;   extern printf;   struct @Command { field @Integer tape {get:tape,set:stape}; field @Integer move {get:move,set:smove}; field @Integer next {get:next,set:snext};   @Command init(@Integer tape, @Integer move, @Integer next) [ this.stape(tape); this.smove(move); this.snext(next); return this; ] };   doc 2 dimansional array structure;   struct @Rules {   field @Integer maxstates { get: maxstates, set: smaxstates }; field @Integer maxvalue { get: maxvalue, set: smaxvalue };   field @Array<@Array<@Command> > table {get: t, set: st};   @Rules init(@Integer states, @Integer values) [ this.smaxstates(states); this.smaxvalue(values); this.st(new @Array<@Array<@Command> >.init(states)); return this; ]   @Void setRule(@Integer state, @Integer tape, @Command command) [ if (null == this::t.get(state)) { this::t.set(state, new @Array<@Command>.init(this::maxvalue)); } this::t.get(state).set(tape, command); ]   @Command getRule(@Integer state, @Integer tape) [ return this::t.get(state).get(tape); ]   };   @Void emulateTuring(@Rules rules, @Integer start, @Integer stop, @Array<@Integer> tape, @Integer blank) [ var tapepointer = 0; var state = start;   doc output; printf("Tape\tState\n");   while (state != stop) { doc add more cells to the tape; if (tapepointer == tape::size) tape.add(blank); if (tapepointer == 0-1) { tape = (new @Array<@Integer>..blank).addAll(tape); tapepointer = 0; }   doc output; for (var i = 0; i < tape::size; i=i+1) { printf("%i", tape.get(i)); } printf("\t%i\n", state); for (var i = 0; i < tapepointer; i=i+1) { printf(" "); } printf("^\n");   doc the value of the current cell; var tapeval = tape.get(tapepointer);   doc the current state; var command = rules.getRule(state, tapeval);   tape.set(tapepointer, command::tape); tapepointer = tapepointer + command::move; state = command::next; }   doc output; for (var i = 0; i < tape::size; i=i+1) { printf("%i", tape.get(i)); } printf("\t%i\n", state); for (var i = 0; i < tapepointer; i=i+1) { printf(" "); } printf("^\n"); ]   @Integer main [   doc incrementer;   doc 2 states, 2 symbols;   var rules = new @Rules.init(2, 2);   doc q0, 1 -> 1, right, q0; doc q0, B -> 1, stay, qf;   rules.setRule(0, 1, new @Command.init(1, 1, 0)); rules.setRule(0, 0, new @Command.init(1, 0, 1));   doc tape = [1, 1, 1];   var tape = new @Array<@Integer>..1..1..1;   doc start turing machine;   emulateTuring(rules, 0, 1, tape, 0);   doc ---------------------------------------------------;   doc three state busy beaver;   doc 4 states, 2 symbols;   rules = new @Rules.init(4, 2);   doc a, 0 -> 1, right, b a, 1 -> 1, left, c b, 0 -> 1, left, a b, 1 -> 1, right, b c, 0 -> 1, left, b c, 1 -> 1, stay, halt ;   doc a = 0, b = 1, c = 2, halt = 3;   rules.setRule(0, 0, new @Command.init(1, 1, 1)); rules.setRule(0, 1, new @Command.init(1, 0-1, 2)); rules.setRule(1, 0, new @Command.init(1, 0-1, 0)); rules.setRule(1, 1, new @Command.init(1, 1, 1)); rules.setRule(2, 0, new @Command.init(1, 0-1, 1)); rules.setRule(2, 1, new @Command.init(1, 0, 3));   doc tape = [];   tape = new @Array<@Integer>;   doc start turing machine;   emulateTuring(rules, 0, 3, tape, 0); return 0; ]
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 positive integer   n   that are relatively prime to   n   counts the integers   k   in the range   1 ≤ k ≤ n   for which the greatest common divisor   gcd(n,k)   is equal to   1   counts numbers   ≤ n   and   prime to   n If the totient number   (for N)   is one less than   N,   then   N   is prime. Task Create a   totient   function and:   Find and display   (1 per line)   for the 1st   25   integers:   the integer   (the index)   the totient number for that integer   indicate if that integer is prime   Find and display the   count   of the primes up to          100   Find and display the   count   of the primes up to       1,000   Find and display the   count   of the primes up to     10,000   Find and display the   count   of the primes up to   100,000     (optional) Show all output here. Related task   Perfect totient numbers Also see   Wikipedia: Euler's totient function.   MathWorld: totient function.   OEIS: Euler totient function phi(n).
#Python
Python
from math import gcd   def φ(n): return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)   if __name__ == '__main__': def is_prime(n): return φ(n) == n - 1   for n in range(1, 26): print(f" φ({n}) == {φ(n)}{', is prime' if is_prime(n) else ''}") count = 0 for n in range(1, 10_000 + 1): count += is_prime(n) if n in {100, 1000, 10_000}: print(f"Primes up to {n}: {count}")
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 is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle). For the inverse functions,   use the same number and convert its answer to radians and degrees. If your language does not have trigonometric functions available or only has some available,   write functions to calculate the functions based on any   known approximation or identity.
#IDL
IDL
deg = 35 ; arbitrary number of degrees rad = !dtor*deg ; system variables !dtor and !radeg convert between rad and deg
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 the algorithm. From the wikipedia entry: ask for 11 numbers to be read into a sequence S reverse sequence S for each item in sequence S result := call a function to do an operation if result overflows alert user else print result The task is to implement the algorithm: Use the function:     f ( x ) = | x | 0.5 + 5 x 3 {\displaystyle f(x)=|x|^{0.5}+5x^{3}} The overflow condition is an answer of greater than 400. The 'user alert' should not stop processing of other items of the sequence. Print a prompt before accepting eleven, textual, numeric inputs. You may optionally print the item as well as its associated result, but the results must be in reverse order of input. The sequence   S   may be 'implied' and so not shown explicitly. Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#Ring
Ring
  # Project : Trabb Pardo–Knuth algorithm   decimals(3) x = list(11) for n=1 to 11 x[n] = n next   s = [-5, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6] for i = 1 to 11 see string(i) + " => " + s[i] + nl next see copy("-", 20) + nl i = i - 1   while i > 0 see "f(" + string(s[i]) + ") = " x = f(s[i]) if x > 400 see "-=< overflow >=-" + nl else see x + nl ok i = i - 1 end   func f(n) return sqrt(fabs(n)) + 5 * pow(n, 3)  
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 the algorithm. From the wikipedia entry: ask for 11 numbers to be read into a sequence S reverse sequence S for each item in sequence S result := call a function to do an operation if result overflows alert user else print result The task is to implement the algorithm: Use the function:     f ( x ) = | x | 0.5 + 5 x 3 {\displaystyle f(x)=|x|^{0.5}+5x^{3}} The overflow condition is an answer of greater than 400. The 'user alert' should not stop processing of other items of the sequence. Print a prompt before accepting eleven, textual, numeric inputs. You may optionally print the item as well as its associated result, but the results must be in reverse order of input. The sequence   S   may be 'implied' and so not shown explicitly. Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#Ruby
Ruby
def f(x) x.abs ** 0.5 + 5 * x ** 3 end   puts "Please enter 11 numbers:" nums = 11.times.map{ gets.to_f }   nums.reverse_each do |n| print "f(#{n}) = " res = f(n) puts res > 400 ? "Overflow!" : res end
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, 739, 73, and 7 formed by removing digits from its right are also prime. No zeroes are allowed in truncatable primes. Task The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied). Related tasks Find largest left truncatable prime in a given base Sieve of Eratosthenes See also Truncatable Prime from MathWorld.]
#Racket
Racket
  #lang racket (require math/number-theory)   (define (truncate-right n) (quotient n 10))   (define (truncate-left n) (define s (number->string n)) (string->number (substring s 1 (string-length s))))   (define (contains-zero? n) (member #\0 (string->list (number->string n))))   (define (truncatable? truncate n) (and (prime? n) (not (contains-zero? n)) (or (< n 10) (truncatable? truncate (truncate n)))))   ; largest left truncatable prime (for/first ([n (in-range 1000000 1 -1)] #:when (truncatable? truncate-left n)) n)   ; largest right truncatable prime (for/first ([n (in-range 1000000 1 -1)] #:when (truncatable? truncate-right n)) n)   ; Output: 998443 739399  
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 / / \ 7 8 9 The correct output should look like this: preorder: 1 2 4 7 5 3 6 8 9 inorder: 7 4 2 5 1 8 6 9 3 postorder: 7 4 5 2 8 9 6 3 1 level-order: 1 2 3 4 5 6 7 8 9 See also   Wikipedia article:   Tree traversal.
#Erlang
Erlang
-module(tree_traversal). -export([main/0]). -export([preorder/2, inorder/2, postorder/2, levelorder/2]). -export([tnode/0, tnode/1, tnode/3]).   -define(NEWLINE, io:format("~n")).   tnode() -> {}. tnode(V) -> {node, V, {}, {}}. tnode(V,L,R) -> {node, V, L, R}.   preorder(_,{}) -> ok; preorder(F,{node,V,L,R}) -> F(V), preorder(F,L), preorder(F,R).   inorder(_,{}) -> ok; inorder(F,{node,V,L,R}) -> inorder(F,L), F(V), inorder(F,R).   postorder(_,{}) -> ok; postorder(F,{node,V,L,R}) -> postorder(F,L), postorder(F,R), F(V).   levelorder(_, []) -> []; levelorder(F, [{}|T]) -> levelorder(F, T); levelorder(F, [{node,V,L,R}|T]) -> F(V), levelorder(F, T++[L,R]); levelorder(F, X) -> levelorder(F, [X]).   main() -> Tree = tnode(1, tnode(2, tnode(4, tnode(7), tnode()), tnode(5, tnode(), tnode())), tnode(3, tnode(6, tnode(8), tnode(9)), tnode())), F = fun(X) -> io:format("~p ",[X]) end, preorder(F, Tree), ?NEWLINE, inorder(F, Tree), ?NEWLINE, postorder(F, Tree), ?NEWLINE, levelorder(F, Tree), ?NEWLINE.
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: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Crystal
Crystal
puts "Hello,How,Are,You,Today".split(',').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: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#D
D
void main() { import std.stdio, std.string;   "Hello,How,Are,You,Today".split(',').join('.').writeln; }
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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Erlang
Erlang
  5> {Time,Result} = timer:tc(fun () -> lists:foreach(fun(X) -> X*X end, lists:seq(1,100000)) end). {226391,ok} 6> Time/1000000. % Time is in microseconds. 0.226391 7> % Time is in microseconds.  
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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Euphoria
Euphoria
atom t t = time() some_procedure() t = time() - t printf(1,"Elapsed %f seconds.\n",t)
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,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190
#F.23
F#
let 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"; "Rich Holcomb", "E01234", 49500, "D202"; "Nathan Adams", "E41298", 21900, "D050"; "Richard Potter", "E43128", 15900, "D101"; "David Motsinger", "E27002", 19250, "D202"; "Tim Sampair", "E03033", 27000, "D101"; "Kim Arlich", "E10001", 57000, "D190"; "Timothy Grove", "E16398", 29900, "D190"; ]   let topRank n = Seq.groupBy (fun (_, _, _, d) -> d) data |> Seq.map (snd >> Seq.sortBy (fun (_, _, s, _) -> -s) >> Seq.take n)
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.   Wikipedia tic-tac-toe.
#Common_Lisp
Common Lisp
  (defun generate-board () (loop repeat 9 collect nil))   (defparameter *straights* '((1 2 3) (4 5 6) (7 8 9) (1 4 7) (2 5 8) (3 6 9) (1 5 9) (3 5 7))) (defparameter *current-player* 'x)   (defun get-board-elt (n board) (nth (1- n) board))   (defun legal-p (n board) (null (get-board-elt n board)))   (defun set-board-elt (n board symbol) (if (legal-p n board) (setf (nth (1- n) board) symbol) (progn (format t "Illegal move. Try again.~&") (set-board-elt (read) board symbol))))   (defun list-legal-moves (board) (loop for i from 1 to (length board) when (legal-p i board) collect i))   (defun get-random-element (lst) (nth (random (length lst)) lst))   (defun multi-non-nil-eq (lst) (and (notany #'null lst) (notany #'null (mapcar #'(lambda (x) (eq (car lst) x)) lst)) (car lst)))   (defun elements-of-straights (board) (loop for i in *straights* collect (loop for j from 0 to 2 collect (get-board-elt (nth j i) board))))   (defun find-winner (board) (car (remove-if #'null (mapcar #'multi-non-nil-eq (elements-of-straights board)))))   (defun set-player (mark) (format t "Shall a computer play as ~a? (y/n)~&" mark) (let ((response (read))) (cond ((equalp response 'y) t) ((equalp response 'n) nil) (t (format t "Come again?~&") (set-player mark)))))   (defun player-move (board symbol) (format t "~%Player ~a, please input your move.~&" symbol) (set-board-elt (read) board symbol) (format t "~%"))   (defun computer-move (board symbol) (let ((move (get-random-element (list-legal-moves board)))) (set-board-elt move board symbol) (format t "~%computer selects ~a~%~%" move)))   (defun computer-move-p (current-player autoplay-x-p autoplay-o-p) (if (eq current-player 'x) autoplay-x-p autoplay-o-p))   (defun perform-turn (current-player board autoplay-x-p autoplay-o-p) (if (computer-move-p current-player autoplay-x-p autoplay-o-p) (computer-move board current-player) (player-move board current-player)))   (defun switch-player () (if (eq *current-player* 'x) (setf *current-player* 'o) (setf *current-player* 'x)))   (defun display-board (board) (loop for i downfrom 2 to 0 do (loop for j from 1 to 3 initially (format t "|") do (format t "~a|" (or (get-board-elt (+ (* 3 i) j) board) (+ (* 3 i) j))) finally (format t "~&"))))   (defun tic-tac-toe () (setf *current-player* 'x) (let ((board (generate-board)) (autoplay-x-p (set-player 'x)) (autoplay-o-p (set-player 'o))) (format t "~%") (loop until (or (find-winner board) (null (list-legal-moves board))) do (display-board board) do (perform-turn *current-player* board autoplay-x-p autoplay-o-p) do (switch-player) finally (if (find-winner board) (format t "The winner is ~a!" (find-winner board)) (format t "It's a tie.")))))  
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Brainf.2A.2A.2A
Brainf***
[ This implementation is recursive and uses a stack, consisting of frames that are 8 bytes long. The layout is as follows:   Byte Description 0 recursion flag (the program stops if the flag is zero) 1 the step which is currently executed 4 means a call to move(a, c, b, n - 1) 3 means a call to move(a, b, c, 1) 2 means a call to move(b, a, c, n - 1) 1 prints the source and dest pile 2 flag to check whether the current step has already been done or if it still must be executed 3 the step which will be executed in the next loop 4 the source pile 5 the helper pile 6 the destination pile 7 the number of disks to move   The first stack frame (0 0 0 0 0 0 0 0) is used to abort the recursion. ]   >>>>>>>>   These are the parameters for the program (1 4 1 0 'a 'b 'c 5) +>++++>+>> >>>>++++++++[<++++++++++++>-]< [<<<+>+>+>-]<<<+>++>+++>+++++> <<<<<<<<   [> while (recurse) [- if (step gt 0) >[-]+< todo = 1 [- if (step gt 1) [- if (step gt 2) [- if (step gt 3) >>+++<< next = 3 >-< todo = 0 >>>>>>[>+>+<<-]>[<+>-]> n dup - [[-] if (sub(n 1) gt 0) <+>>>++++> push (1 0 0 4)   copy and push a <<<<<<<<[>>>>>>>>+>+ <<<<<<<<<-]>>>>>>>> >[<<<<<<<<<+>>>>>>>>>-]< >   copy and push c <<<<<<<[>>>>>>>+>+ <<<<<<<<-]>>>>>>> >[<<<<<<<<+>>>>>>>>-]< >   copy and push b <<<<<<<<<[>>>>>>>>>+>+ <<<<<<<<<<-]>>>>>>>>> >[<<<<<<<<<<+>>>>>>>>>>-]< >   copy n and push sub(n 1) <<<<<<<<[>>>>>>>>+>+ <<<<<<<<<-]>>>>>>>> >[<<<<<<<<<+>>>>>>>>>-]< - >> ] <<<<<<<< ] >[-< if ((step gt 2) and todo) >>++<< next = 2 >>>>>>> +>>>+> push 1 0 0 1 a b c 1 <<<<<<<<[>>>>>>>>+>+ <<<<<<<<<-]>>>>>>>> >[<<<<<<<<<+>>>>>>>>>-]< > a <<<<<<<<[>>>>>>>>+>+ <<<<<<<<<-]>>>>>>>> >[<<<<<<<<<+>>>>>>>>>-]< > b <<<<<<<<[>>>>>>>>+>+ <<<<<<<<<-]>>>>>>>> >[<<<<<<<<<+>>>>>>>>>-]< > c + >> >]< ] >[-< if ((step gt 1) and todo) >>>>>>[>+>+<<-]>[<+>-]> n dup - [[-] if (n sub 1 gt 0) <+>>>++++> push (1 0 0 4)   copy and push b <<<<<<<[>>>>>>>+ <<<<<<<-]>>>>>>> >[<<<<<<<<+>>>>>>>>-]< >   copy and push a <<<<<<<<<[>>>>>>>>>+ <<<<<<<<<-]>>>>>>>>> >[<<<<<<<<<<+>>>>>>>>>>-]< >   copy and push c <<<<<<<<[>>>>>>>>+ <<<<<<<<-]>>>>>>>> >[<<<<<<<<<+>>>>>>>>>-]< >   copy n and push sub(n 1) <<<<<<<<[>>>>>>>>+>+ <<<<<<<<<-]>>>>>>>> >[<<<<<<<<<+>>>>>>>>>-]< - >> ] <<<<<<<< >]< ] >[-< if ((step gt 0) and todo) >>>>>>> >++++[<++++++++>-]< >>++++++++[<+++++++++>-]<++++ >>++++++++[<++++++++++++>-]<+++++ >>+++++++++[<++++++++++++>-]<+++ <<< >.+++++++>.++.--.<<. >>-.+++++.----.<<. >>>.<---.+++.>+++.+.+.<.<<. >.>--.+++++.---.++++. -------.+++.<<. >>>++.-------.-.<<<. >+.>>+++++++.---.-----.<<<. <<<<.>>>>. >>----.>++++++++.<+++++.<<. >.>>.---.-----.<<<. <<.>>++++++++++++++. >>>[-]<[-]<[-]<[-] +++++++++++++.---.[-] <<<<<<< >]< >>[<<+>>-]<< step = next ] return with clear stack frame <[-]>[-]>[-]>[-]>[-]>[-]>[-]>[-]<<<<<< <<<<<<<< >>[<<+>>-]<< step = next < ]
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
#OASYS_Assembler
OASYS Assembler
; Thue-Morse sequence   [*'A]  ; Ensure the vocabulary is not empty [&]  ; Declare the initialization procedure %#1>  ; Initialize length counter %@*>  ; Create first object ,#1>  ; Initialize loop counter :  ; Begin loop  %@<.#<PI  ; Print current cell *.#%@<.#<NOT>  ; Create new cell  %@%@<NXT>  ; Advance to next cell ,#,#<DN>  ; Decrement loop counter ,#</  ; Check if loop counter is now zero  %#%#<2MUL>  ; Double length counter ,#%#<>  ; Reset loop counter  %@FO>  ; Reset object pointer CR  ; Line break |  ; Repeat loop
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
#Objeck
Objeck
class ThueMorse { function : Main(args : String[]) ~ Nil { Sequence(6); }   function : Sequence(steps : Int) ~ Nil { sb1 := "0"; sb2 := "1"; for(i := 0; i < steps; i++;) { tmp := String->New(sb1); sb1 += sb2; sb2 += tmp; }; sb1->PrintLine(); } }  
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 separated by the separators, become the elements of the output list. Empty fields should be preserved, even at the start and end. Rules for escaping: "Escaped" means preceded by an occurrence of the escape character that is not already escaped itself. When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special). Each occurrence of the escape character that was used to escape something, should not become part of the output. Test case Demonstrate that your function satisfies the following test-case: Input Output string: one^|uno||three^^^^|four^^^|^cuatro| separator character: | escape character: ^ one|uno three^^ four^|cuatro (Print the output list in any format you like, as long as it is it easy to see what the fields are.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Perl
Perl
sub tokenize { my ($string, $sep, $esc) = (shift, quotemeta shift, quotemeta shift);   my @fields = split /$esc . (*SKIP)(*FAIL) | $sep/sx, $string, -1; return map { s/$esc(.)/$1/gsr } @fields; }
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon. The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on. A tool exists that extracts library dependencies. Task Write a function that will return a valid compile order of VHDL libraries from their dependencies. Assume library names are single words. Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given. Any self dependencies should be ignored. Any un-orderable dependencies should be flagged. Use the following data as an example: LIBRARY LIBRARY DEPENDENCIES ======= ==================== des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee dw01 ieee dw01 dware gtech dw02 ieee dw02 dware dw03 std synopsys dware dw03 dw02 dw01 ieee gtech dw04 dw04 ieee dw01 dware gtech dw05 dw05 ieee dware dw06 dw06 ieee dware dw07 ieee dware dware ieee dware gtech ieee gtech ramlib std ieee std_cell_lib ieee std_cell_lib synopsys Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01. C.f.   Topological sort/Extracted top item. There are two popular algorithms for topological sorting:   Kahn's 1962 topological sort [1]   depth-first search [2] [3]
#jq
jq
# independent/0 emits an array of the dependencies that have no dependencies # Input: an object representing a normalized dependency graph def independent: . as $G | reduce keys[] as $key ([]; . + ((reduce $G[$key][] as $node ([]; if ($G[$node] == null or ($G[$node]|length)==0) then . + [$node] else . end )))) | unique;   # normalize/0 eliminates self-dependencies in the input dependency graph. # Input: an object representing a dependency graph. def normalize: . as $G | reduce keys[] as $key ($G; .[$key] as $nodes | if $nodes and ($nodes|index($key)) then .[$key] = $nodes - [$key] else . end);     # minus/1 removes all the items in ary from each of the values in the input object # Input: an object representing a dependency graph def minus(ary): . as $G | with_entries(.value -= ary);   # tsort/0 emits the topologically sorted nodes of the input, # in ">" order. # Input is assumed to be an object representing a dependency # graph and need not be normalized. def tsort: # _sort: input: [L, Graph], where L is the tsort so far def _tsort:   def done: [.[]] | all( length==0 );   .[0] as $L | .[1] as $G | if ($G|done) then $L + (($G|keys) - $L) else ($G|independent) as $I | if (($I|length) == 0) then error("the dependency graph is cyclic: \($G)") else [ ($L + $I), ($G|minus($I))] | _tsort end end;   normalize | [[], .] | _tsort ;   tsort
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 a machine capable of taking the definition of any other Turing machine and executing it. Of course, you will not have an infinite tape, but you should emulate this as much as is possible. The three permissible actions on the tape are "left", "right" and "stay". To test your universal Turing machine (and prove your programming language is Turing complete!), you should execute the following two Turing machines based on the following definitions. Simple incrementer States: q0, qf Initial state: q0 Terminating states: qf Permissible symbols: B, 1 Blank symbol: B Rules: (q0, 1, 1, right, q0) (q0, B, 1, stay, qf) The input for this machine should be a tape of 1 1 1 Three-state busy beaver States: a, b, c, halt Initial state: a Terminating states: halt Permissible symbols: 0, 1 Blank symbol: 0 Rules: (a, 0, 1, right, b) (a, 1, 1, left, c) (b, 0, 1, left, a) (b, 1, 1, right, b) (c, 0, 1, left, b) (c, 1, 1, stay, halt) The input for this machine should be an empty tape. Bonus: 5-state, 2-symbol probable Busy Beaver machine from Wikipedia States: A, B, C, D, E, H Initial state: A Terminating states: H Permissible symbols: 0, 1 Blank symbol: 0 Rules: (A, 0, 1, right, B) (A, 1, 1, left, C) (B, 0, 1, right, C) (B, 1, 1, right, B) (C, 0, 1, right, D) (C, 1, 0, left, E) (D, 0, 1, left, A) (D, 1, 1, left, D) (E, 0, 1, stay, H) (E, 1, 0, left, A) The input for this machine should be an empty tape. This machine runs for more than 47 millions steps.
#PicoLisp
PicoLisp
# Finite state machine (de turing (Tape Init Halt Blank Rules Verbose) (let (Head 1 State Init Rule NIL S 'start C (length Tape)) (catch NIL (loop (state 'S (start 'print (when (=0 C) (setq Tape (insert Head Tape Blank)) (inc 'C) ) ) (print 'lookup (when Verbose (for (N . I) Tape (if (= N Head) (print (list I)) (prin I) ) ) (prinl) ) (when (= State Halt) (throw NIL) ) ) (lookup 'do (setq Rule (find '((X) (and (= (car X) State) (= (cadr X) (car (nth Tape Head))) ) ) Rules ) ) ) (do 'step (setq Tape (place Head Tape (caddr Rule))) ) (step 'print (cond ((= (cadddr Rule) 'R) (inc 'Head)) ((= (cadddr Rule) 'L) (dec 'Head)) ) (cond ((< Head 1) (setq Tape (insert Head Tape Blank)) (inc 'C) (one Head) ) ((> Head C) (setq Tape (insert Head Tape Blank)) (inc 'C) ) ) (setq State (last Rule)) ) ) ) ) ) Tape )   (println "Simple incrementer") (turing '(1 1 1) 'A 'H 'B '((A 1 1 R A) (A B 1 S H)) T)   (println "Three-state busy beaver") (turing '() 'A 'H 0 '((A 0 1 R B) (A 1 1 L C) (B 0 1 L A) (B 1 1 R B) (C 0 1 L B) (C 1 1 S H)) T )   (println "Five-state busy beaver") (let Tape (turing '() 'A 'H 0 '((A 0 1 R B) (A 1 1 L C) (B 0 1 R C) (B 1 1 R B) (C 0 1 R D) (C 1 0 L E) (D 0 1 L A) (D 1 1 L D) (E 0 1 S H) (E 1 0 L A)) NIL) (println '0s: (cnt '((X) (= 0 X)) Tape)) (println '1s: (cnt '((X) (= 1 X)) Tape)) )   (bye)
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 positive integer   n   that are relatively prime to   n   counts the integers   k   in the range   1 ≤ k ≤ n   for which the greatest common divisor   gcd(n,k)   is equal to   1   counts numbers   ≤ n   and   prime to   n If the totient number   (for N)   is one less than   N,   then   N   is prime. Task Create a   totient   function and:   Find and display   (1 per line)   for the 1st   25   integers:   the integer   (the index)   the totient number for that integer   indicate if that integer is prime   Find and display the   count   of the primes up to          100   Find and display the   count   of the primes up to       1,000   Find and display the   count   of the primes up to     10,000   Find and display the   count   of the primes up to   100,000     (optional) Show all output here. Related task   Perfect totient numbers Also see   Wikipedia: Euler's totient function.   MathWorld: totient function.   OEIS: Euler totient function phi(n).
#Quackery
Quackery
[ [ dup while tuck mod again ] drop abs ] is gcd ( n n --> n )     [ 0 swap dup times [ i over gcd 1 = rot + swap ] drop ] is totient ( n --> n )   [ 0 temp put times [ i dup 1+ totient = temp tally ] temp take ] is primecount ( n --> n )   25 times [ say "The totient of " i^ 1+ dup echo say " is " dup totient dup echo say ", so it is " 1+ != if say "not " say "prime." cr ] cr ' [ 100 1000 10000 100000 ] witheach [ say "There are " dup primecount echo say " primes up to " echo say "." cr ]
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 is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle). For the inverse functions,   use the same number and convert its answer to radians and degrees. If your language does not have trigonometric functions available or only has some available,   write functions to calculate the functions based on any   known approximation or identity.
#Icon_and_Unicon
Icon and Unicon
invocable all procedure main()   d := 30 # degrees r := dtor(d) # convert to radians   every write(f := !["sin","cos","tan"],"(",r,")=",y := f(r)," ",fi := "a" || f,"(",y,")=",x := fi(y)," rad = ",rtod(x)," deg") end
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 the algorithm. From the wikipedia entry: ask for 11 numbers to be read into a sequence S reverse sequence S for each item in sequence S result := call a function to do an operation if result overflows alert user else print result The task is to implement the algorithm: Use the function:     f ( x ) = | x | 0.5 + 5 x 3 {\displaystyle f(x)=|x|^{0.5}+5x^{3}} The overflow condition is an answer of greater than 400. The 'user alert' should not stop processing of other items of the sequence. Print a prompt before accepting eleven, textual, numeric inputs. You may optionally print the item as well as its associated result, but the results must be in reverse order of input. The sequence   S   may be 'implied' and so not shown explicitly. Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#Rust
Rust
  use std::io::{self, BufRead};   fn op(x: f32) -> Option<f32> { let y = x.abs().sqrt() + 5.0 * x * x * x; if y < 400.0 { Some(y) } else { None } }   fn main() { println!("Please enter 11 numbers (one number per line)"); let stdin = io::stdin();   let xs = stdin .lock() .lines() .map(|ox| ox.unwrap().trim().to_string()) .flat_map(|s| str::parse::<f32>(&s)) .take(11) .collect::<Vec<_>>();   for x in xs.into_iter().rev() { match op(x) { Some(y) => println!("{}", y), None => println!("overflow"), }; } }  
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 the algorithm. From the wikipedia entry: ask for 11 numbers to be read into a sequence S reverse sequence S for each item in sequence S result := call a function to do an operation if result overflows alert user else print result The task is to implement the algorithm: Use the function:     f ( x ) = | x | 0.5 + 5 x 3 {\displaystyle f(x)=|x|^{0.5}+5x^{3}} The overflow condition is an answer of greater than 400. The 'user alert' should not stop processing of other items of the sequence. Print a prompt before accepting eleven, textual, numeric inputs. You may optionally print the item as well as its associated result, but the results must be in reverse order of input. The sequence   S   may be 'implied' and so not shown explicitly. Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#Scala
Scala
object TPKa extends App { final val numbers = scala.collection.mutable.MutableList[Double]() final val in = new java.util.Scanner(System.in) while (numbers.length < CAPACITY) { print("enter a number: ") try { numbers += in.nextDouble() } catch { case _: Exception => in.next() println("invalid input, try again") } }   numbers reverseMap { x => val fx = Math.pow(Math.abs(x), .5D) + 5D * (Math.pow(x, 3)) if (fx < THRESHOLD) print("%8.3f -> %8.3f\n".format(x, fx)) else print("%8.3f -> %s\n".format(x, Double.PositiveInfinity.toString)) }   private final val THRESHOLD = 400D private final val CAPACITY = 11 }
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, 739, 73, and 7 formed by removing digits from its right are also prime. No zeroes are allowed in truncatable primes. Task The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied). Related tasks Find largest left truncatable prime in a given base Sieve of Eratosthenes See also Truncatable Prime from MathWorld.]
#Raku
Raku
constant ltp = $[2, 3, 5, 7], -> @ltp { $[ grep { .&is-prime }, ((1..9) X~ @ltp) ] } ... *;   constant rtp = $[2, 3, 5, 7], -> @rtp { $[ grep { .&is-prime }, (@rtp X~ (1..9)) ] } ... *;   say "Highest ltp = ", ltp[5][*-1]; say "Highest rtp = ", rtp[5][*-1];
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 / / \ 7 8 9 The correct output should look like this: preorder: 1 2 4 7 5 3 6 8 9 inorder: 7 4 2 5 1 8 6 9 3 postorder: 7 4 5 2 8 9 6 3 1 level-order: 1 2 3 4 5 6 7 8 9 See also   Wikipedia article:   Tree traversal.
#Euphoria
Euphoria
constant VALUE = 1, LEFT = 2, RIGHT = 3   constant tree = {1, {2, {4, {7, 0, 0}, 0}, {5, 0, 0}}, {3, {6, {8, 0, 0}, {9, 0, 0}}, 0}}   procedure preorder(object tree) if sequence(tree) then printf(1,"%d ",{tree[VALUE]}) preorder(tree[LEFT]) preorder(tree[RIGHT]) end if end procedure   procedure inorder(object tree) if sequence(tree) then inorder(tree[LEFT]) printf(1,"%d ",{tree[VALUE]}) inorder(tree[RIGHT]) end if end procedure   procedure postorder(object tree) if sequence(tree) then postorder(tree[LEFT]) postorder(tree[RIGHT]) printf(1,"%d ",{tree[VALUE]}) end if end procedure   procedure lo(object tree, sequence more) if sequence(tree) then more &= {tree[LEFT],tree[RIGHT]} printf(1,"%d ",{tree[VALUE]}) end if if length(more) > 0 then lo(more[1],more[2..$]) end if end procedure   procedure level_order(object tree) lo(tree,{}) end procedure   puts(1,"preorder: ") preorder(tree) puts(1,'\n')   puts(1,"inorder: ") inorder(tree) puts(1,'\n')   puts(1,"postorder: ") postorder(tree) puts(1,'\n')   puts(1,"level-order: ") level_order(tree) puts(1,'\n')
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: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Delphi
Delphi
  program Tokenize_a_string;   {$APPTYPE CONSOLE}   uses System.SysUtils;   var Words: TArray<string>;   begin Words := 'Hello,How,Are,You,Today'.Split([',']); Writeln(string.Join(#10, Words));   Readln; end.    
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: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Dyalect
Dyalect
var str = "Hello,How,Are,You,Today" var strings = str.Split(',') print(values: strings, separator: ".")
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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#F.23
F#
  open System.Diagnostics let myfunc data = let timer = new Stopwatch() timer.Start() let result = data |> expensive_processing timer.Stop() printf "elapsed %d ms" timer.ElapsedMilliseconds result  
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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Factor
Factor
USING: kernel sequences tools.time ;   [ 10000 <iota> sum drop ] time
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,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190
#Factor
Factor
USING: accessors assocs fry io kernel math.parser sequences sorting ; IN: top-rank   TUPLE: employee name id salary department ;   CONSTANT: employees { T{ employee f "Tyler Bennett" "E10297" 32000 "D101" } T{ employee f "John Rappl" "E21437" 47000 "D050" } T{ employee f "George Woltman" "E00127" 53500 "D101" } T{ employee f "Adam Smith" "E63535" 18000 "D202" } T{ employee f "Claire Buckman" "E39876" 27800 "D202" } T{ employee f "David McClellan" "E04242" 41500 "D101" } T{ employee f "Rich Holcomb" "E01234" 49500 "D202" } T{ employee f "Nathan Adams" "E41298" 21900 "D050" } T{ employee f "Richard Potter" "E43128" 15900 "D101" } T{ employee f "David Motsinger" "E27002" 19250 "D202" } T{ employee f "Tim Sampair" "E03033" 27000 "D101" } T{ employee f "Kim Arlich" "E10001" 57000 "D190" } T{ employee f "Timothy Grove" "E16398" 29900 "D190" } }   : group-by ( seq quot -- hash ) H{ } clone [ '[ dup @ _ push-at ] each ] keep ; inline   : prepare-departments ( seq -- departments ) [ department>> ] group-by [ [ salary>> ] inv-sort-with ] assoc-map ;   : first-n-each ( seq n quot -- ) [ short head-slice ] dip each ; inline   : main ( -- ) employees prepare-departments [ [ "Department " write write ":" print ] dip 3 [ [ id>> write " $" write ] [ salary>> number>string write " " write ] [ name>> print ] tri ] first-n-each nl ] assoc-each ;
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.   Wikipedia tic-tac-toe.
#D
D
import std.stdio, std.string, std.algorithm, std.conv, std.random, std.ascii, std.array, std.range, std.math;   struct GameBoard { dchar[9] board = "123456789"; enum : dchar { human = 'X', computer = 'O' } enum Game { going, humanWins, computerWins, draw }   const pure nothrow @safe @nogc invariant() { int nHuman = 0, nComputer = 0; foreach (immutable i, immutable c; board) if (c.isDigit) assert(i == c - '1'); // In correct position? else { assert(c == human || c == computer); (c == human ? nHuman : nComputer)++; } assert(abs(nHuman - nComputer) <= 1); }   string toString() const pure { return format("%(%-(%s|%)\n-+-+-\n%)", board[].chunks(3)); }   bool isAvailable(in int i) const pure nothrow @safe @nogc { return i >= 0 && i < 9 && board[i].isDigit; }   auto availablePositions() const pure nothrow @safe /*@nogc*/ { return 9.iota.filter!(i => isAvailable(i)); }   Game winner() const pure nothrow @safe /*@nogc*/ { static immutable wins = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]];   foreach (immutable win; wins) { immutable bw0 = board[win[0]]; if (bw0.isDigit) continue; // Nobody wins on this one.   if (bw0 == board[win[1]] && bw0 == board[win[2]]) return bw0 == GameBoard.human ? Game.humanWins : Game.computerWins; }   return availablePositions.empty ? Game.draw: Game.going; }   bool isFinished() const pure nothrow @safe /*@nogc*/ { return winner != Game.going; }   int computerMove() const // Random move. out(res) { assert(res >= 0 && res < 9 && isAvailable(res)); } body { // return availablePositions.array.choice; return availablePositions.array[uniform(0, $)]; } }     GameBoard playGame() { GameBoard board; bool playsHuman = true;   while (!board.isFinished) { board.writeln;   int move; if (playsHuman) { do { writef("Your move (available moves: %s)? ", board.availablePositions.map!q{ a + 1 }); readf("%d\n", &move); move--; // Zero based indexing. if (move < 0) return board; } while (!board.isAvailable(move)); } else move = board.computerMove;   assert(board.isAvailable(move)); writefln("\n%s chose %d", playsHuman ? "You" : "I", move + 1); board.board[move] = playsHuman ? GameBoard.human : GameBoard.computer; playsHuman = !playsHuman; // Switch player. }   return board; }     void main() { "Tic-tac-toe game player.\n".writeln; immutable outcome = playGame.winner;   final switch (outcome) { case GameBoard.Game.going: "Game stopped.".writeln; break; case GameBoard.Game.humanWins: "\nYou win!".writeln; break; case GameBoard.Game.computerWins: "\nI win.".writeln; break; case GameBoard.Game.draw: "\nDraw".writeln; break; } }
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#C
C
#include <stdio.h>   void move(int n, int from, int via, int to) { if (n > 1) { move(n - 1, from, to, via); printf("Move disk from pole %d to pole %d\n", from, to); move(n - 1, via, from, to); } else { printf("Move disk from pole %d to pole %d\n", from, to); } } int main() { move(4, 1,2,3); return 0; }
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
#OCaml
OCaml
(* description: Counts the number of bits set to 1 input: the number to have its bit counted output: the number of bits set to 1 *) let count_bits v = let rec aux c v = if v <= 0 then c else aux (c + (v land 1)) (v lsr 1) in aux 0 v   let () = for i = 0 to pred 256 do print_char ( match (count_bits i) mod 2 with | 0 -> '0' | 1 -> '1' | _ -> assert false) done; print_newline ()
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
#Pascal
Pascal
Program ThueMorse;   function fThueMorse(maxLen: NativeInt):AnsiString; //double by appending the flipped original 0 -> 1;1 -> 0 //Flipping between two values:x oszillating A,B,A,B -> x_next = A+B-x //Beware A+B < High(Char), the compiler will complain ... const cVal0 = '^';cVal1 = 'v';// cVal0 = '0';cVal1 = '1';   var pOrg, pRpl : pansiChar; i,k,ml : NativeUInt;//MaxLen: NativeInt Begin iF maxlen < 1 then Begin result := ''; EXIT; end; //setlength only one time setlength(result,Maxlen);   pOrg := @result[1]; pOrg[0] := cVal0; IF maxlen = 1 then EXIT;   pRpl := pOrg; inc(pRpl); k := 1; ml:= Maxlen; repeat i := 0; repeat pRpl[0] := ansichar(Ord(cVal0)+Ord(cVal1)-Ord(pOrg[i])); inc(pRpl); inc(i); until i>=k; inc(k,k); until k+k> ml; // the rest i := 0; k := ml-k; IF k > 0 then repeat pRpl[0] := ansichar(Ord(cVal0)+Ord(cVal1)-Ord(pOrg[i])); inc(pRpl); inc(i) until i>=k; end;   var i : integer; Begin For i := 0 to 8 do writeln(i:3,' ',fThueMorse(i)); fThueMorse(1 shl 30); {$IFNDEF LINUX}readln;{$ENDIF} 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 separated by the separators, become the elements of the output list. Empty fields should be preserved, even at the start and end. Rules for escaping: "Escaped" means preceded by an occurrence of the escape character that is not already escaped itself. When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special). Each occurrence of the escape character that was used to escape something, should not become part of the output. Test case Demonstrate that your function satisfies the following test-case: Input Output string: one^|uno||three^^^^|four^^^|^cuatro| separator character: | escape character: ^ one|uno three^^ four^|cuatro (Print the output list in any format you like, as long as it is it easy to see what the fields are.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Phix
Phix
function tokenize(string s, integer sep, integer esc) sequence ret = {} string word = "" integer skip = 0 if length(s)!=0 then for i=1 to length(s) do integer si = s[i] if skip then word &= si skip = 0 elsif si=esc then skip = 1 elsif si=sep then ret = append(ret,word) word = "" else word &= si end if end for ret = append(ret,word) end if return ret end function ?tokenize("one^|uno||three^^^^|four^^^|^cuatro|",'|','^')
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon. The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on. A tool exists that extracts library dependencies. Task Write a function that will return a valid compile order of VHDL libraries from their dependencies. Assume library names are single words. Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given. Any self dependencies should be ignored. Any un-orderable dependencies should be flagged. Use the following data as an example: LIBRARY LIBRARY DEPENDENCIES ======= ==================== des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee dw01 ieee dw01 dware gtech dw02 ieee dw02 dware dw03 std synopsys dware dw03 dw02 dw01 ieee gtech dw04 dw04 ieee dw01 dware gtech dw05 dw05 ieee dware dw06 dw06 ieee dware dw07 ieee dware dware ieee dware gtech ieee gtech ramlib std ieee std_cell_lib ieee std_cell_lib synopsys Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01. C.f.   Topological sort/Extracted top item. There are two popular algorithms for topological sorting:   Kahn's 1962 topological sort [1]   depth-first search [2] [3]
#Julia
Julia
function toposort(data::Dict{T,Set{T}}) where T data = copy(data) for (k, v) in data delete!(v, k) end extraitems = setdiff(reduce(∪, values(data)), keys(data)) for item in extraitems data[item] = Set{T}() end rst = Vector{T}() while true ordered = Set(item for (item, dep) in data if isempty(dep)) if isempty(ordered) break end append!(rst, ordered) data = Dict{T,Set{T}}(item => setdiff(dep, ordered) for (item, dep) in data if item ∉ ordered) end @assert isempty(data) "a cyclic dependency exists amongst $(keys(data))" return rst end   data = Dict{String,Set{String}}( "des_system_lib" => Set(split("std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee")), "dw01" => Set(split("ieee dw01 dware gtech")), "dw02" => Set(split("ieee dw02 dware")), "dw03" => Set(split("std synopsys dware dw03 dw02 dw01 ieee gtech")), "dw04" => Set(split("dw04 ieee dw01 dware gtech")), "dw05" => Set(split("dw05 ieee dware")), "dw06" => Set(split("dw06 ieee dware")), "dw07" => Set(split("ieee dware")), "dware" => Set(split("ieee dware")), "gtech" => Set(split("ieee gtech")), "ramlib" => Set(split("std ieee")), "std_cell_lib" => Set(split("ieee std_cell_lib")), "synopsys" => Set(), )   println("# Topologically sorted:\n - ", join(toposort(data), "\n - "))
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 a machine capable of taking the definition of any other Turing machine and executing it. Of course, you will not have an infinite tape, but you should emulate this as much as is possible. The three permissible actions on the tape are "left", "right" and "stay". To test your universal Turing machine (and prove your programming language is Turing complete!), you should execute the following two Turing machines based on the following definitions. Simple incrementer States: q0, qf Initial state: q0 Terminating states: qf Permissible symbols: B, 1 Blank symbol: B Rules: (q0, 1, 1, right, q0) (q0, B, 1, stay, qf) The input for this machine should be a tape of 1 1 1 Three-state busy beaver States: a, b, c, halt Initial state: a Terminating states: halt Permissible symbols: 0, 1 Blank symbol: 0 Rules: (a, 0, 1, right, b) (a, 1, 1, left, c) (b, 0, 1, left, a) (b, 1, 1, right, b) (c, 0, 1, left, b) (c, 1, 1, stay, halt) The input for this machine should be an empty tape. Bonus: 5-state, 2-symbol probable Busy Beaver machine from Wikipedia States: A, B, C, D, E, H Initial state: A Terminating states: H Permissible symbols: 0, 1 Blank symbol: 0 Rules: (A, 0, 1, right, B) (A, 1, 1, left, C) (B, 0, 1, right, C) (B, 1, 1, right, B) (C, 0, 1, right, D) (C, 1, 0, left, E) (D, 0, 1, left, A) (D, 1, 1, left, D) (E, 0, 1, stay, H) (E, 1, 0, left, A) The input for this machine should be an empty tape. This machine runs for more than 47 millions steps.
#Prolog
Prolog
turing(Config, Rules, TapeIn, TapeOut) :- call(Config, IS, _, _, _, _), perform(Config, Rules, IS, {[], TapeIn}, {Ls, Rs}), reverse(Ls, Ls1), append(Ls1, Rs, TapeOut).   perform(Config, Rules, State, TapeIn, TapeOut) :- call(Config, _, FS, RS, B, Symbols), ( memberchk(State, FS) -> TapeOut = TapeIn ; memberchk(State, RS) -> {LeftIn, RightIn} = TapeIn, symbol(RightIn, Symbol, RightRem, B), memberchk(Symbol, Symbols), once(call(Rules, State, Symbol, NewSymbol, Action, NewState)), memberchk(NewSymbol, Symbols), action(Action, {LeftIn, [NewSymbol|RightRem]}, {LeftOut, RightOut}, B), perform(Config, Rules, NewState, {LeftOut, RightOut}, TapeOut) ).   symbol([], B, [], B). symbol([Sym|Rs], Sym, Rs, _).   action(left, {Lin, Rin}, {Lout, Rout}, B) :- left(Lin, Rin, Lout, Rout, B). action(stay, Tape, Tape, _). action(right, {Lin, Rin}, {Lout, Rout}, B) :- right(Lin, Rin, Lout, Rout, B).   left([], Rs, [], [B|Rs], B). left([L|Ls], Rs, Ls, [L|Rs], _).   right(L, [], [B|L], [], B). right(L, [S|Rs], [S|L], Rs, _).
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 positive integer   n   that are relatively prime to   n   counts the integers   k   in the range   1 ≤ k ≤ n   for which the greatest common divisor   gcd(n,k)   is equal to   1   counts numbers   ≤ n   and   prime to   n If the totient number   (for N)   is one less than   N,   then   N   is prime. Task Create a   totient   function and:   Find and display   (1 per line)   for the 1st   25   integers:   the integer   (the index)   the totient number for that integer   indicate if that integer is prime   Find and display the   count   of the primes up to          100   Find and display the   count   of the primes up to       1,000   Find and display the   count   of the primes up to     10,000   Find and display the   count   of the primes up to   100,000     (optional) Show all output here. Related task   Perfect totient numbers Also see   Wikipedia: Euler's totient function.   MathWorld: totient function.   OEIS: Euler totient function phi(n).
#Racket
Racket
#lang racket   (require math/number-theory)   (define (prime*? n) (= (totient n) (sub1 n)))   (for ([n (in-range 1 26)]) (printf "φ(~a) = ~a~a~a\n" n (totient n) (if (prime*? n) " is prime" "") (if (prime? n) " (confirmed)" "")))   (for/fold ([count 0] #:result (void)) ([n (in-range 1 10001)]) (define new-count (if (prime*? n) (add1 count) count)) (when (member n '(100 1000 10000)) (printf "Primes up to ~a: ~a\n" n new-count)) new-count)
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 is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle). For the inverse functions,   use the same number and convert its answer to radians and degrees. If your language does not have trigonometric functions available or only has some available,   write functions to calculate the functions based on any   known approximation or identity.
#J
J
(1&o. , 2&o. ,: 3&o.) (4 %~ o. 1) , 180 %~ o. 45 0.707107 0.707107 0.707107 0.707107 1 1
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 the algorithm. From the wikipedia entry: ask for 11 numbers to be read into a sequence S reverse sequence S for each item in sequence S result := call a function to do an operation if result overflows alert user else print result The task is to implement the algorithm: Use the function:     f ( x ) = | x | 0.5 + 5 x 3 {\displaystyle f(x)=|x|^{0.5}+5x^{3}} The overflow condition is an answer of greater than 400. The 'user alert' should not stop processing of other items of the sequence. Print a prompt before accepting eleven, textual, numeric inputs. You may optionally print the item as well as its associated result, but the results must be in reverse order of input. The sequence   S   may be 'implied' and so not shown explicitly. Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#Sidef
Sidef
var nums; do { nums = Sys.readln("Please type 11 space-separated numbers: ").nums } while(nums.len != 11)   nums.reverse.each { |n| var r = (n.abs.sqrt + (5 * n**3)); say "#{n}\t#{ r > 400 ? 'Urk!' : r }"; }
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 the algorithm. From the wikipedia entry: ask for 11 numbers to be read into a sequence S reverse sequence S for each item in sequence S result := call a function to do an operation if result overflows alert user else print result The task is to implement the algorithm: Use the function:     f ( x ) = | x | 0.5 + 5 x 3 {\displaystyle f(x)=|x|^{0.5}+5x^{3}} The overflow condition is an answer of greater than 400. The 'user alert' should not stop processing of other items of the sequence. Print a prompt before accepting eleven, textual, numeric inputs. You may optionally print the item as well as its associated result, but the results must be in reverse order of input. The sequence   S   may be 'implied' and so not shown explicitly. Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#Sinclair_ZX81_BASIC
Sinclair ZX81 BASIC
10 DIM A(11) 20 PRINT "ENTER ELEVEN NUMBERS:" 30 FOR I=1 TO 11 40 INPUT A(I) 50 NEXT I 60 FOR I=11 TO 1 STEP -1 70 LET Y=SQR ABS A(I)+5*A(I)**3 80 IF Y<=400 THEN GOTO 110 90 PRINT A(I),"TOO LARGE" 100 GOTO 120 110 PRINT A(I),Y 120 NEXT I
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 the algorithm. From the wikipedia entry: ask for 11 numbers to be read into a sequence S reverse sequence S for each item in sequence S result := call a function to do an operation if result overflows alert user else print result The task is to implement the algorithm: Use the function:     f ( x ) = | x | 0.5 + 5 x 3 {\displaystyle f(x)=|x|^{0.5}+5x^{3}} The overflow condition is an answer of greater than 400. The 'user alert' should not stop processing of other items of the sequence. Print a prompt before accepting eleven, textual, numeric inputs. You may optionally print the item as well as its associated result, but the results must be in reverse order of input. The sequence   S   may be 'implied' and so not shown explicitly. Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#Swift
Swift
import Foundation   print("Enter 11 numbers for the Trabb─Pardo─Knuth algorithm:")   let f: (Double) -> Double = { sqrt(fabs($0)) + 5 * pow($0, 3) }   (1...11) .generate() .map { i -> Double in print("\(i): ", terminator: "") guard let s = readLine(), let n = Double(s) else { return 0 } return n } .reverse() .forEach { let result = f($0) print("f(\($0))", result > 400.0 ? "OVERFLOW" : result, separator: "\t") }  
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, 739, 73, and 7 formed by removing digits from its right are also prime. No zeroes are allowed in truncatable primes. Task The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied). Related tasks Find largest left truncatable prime in a given base Sieve of Eratosthenes See also Truncatable Prime from MathWorld.]
#REXX
REXX
/*REXX program finds largest left─ and right─truncatable primes ≤ 1m (or argument 1).*/ parse arg hi .; if hi=='' then hi= 1000000 /*Not specified? Then use default of 1m*/ call genP /*generate some primes, about hi ÷ 2 */ /* [↓] find largest left truncatable P*/ do L=# by -1 for # /*search from top end; get the length.*/ do k=1 for length(@.L); _= right(@.L, k) /*validate all left truncatable primes.*/ if \!._ then iterate L /*Truncated number not prime? Skip it.*/ end /*k*/ leave /*egress, found left truncatable prime.*/ end /*L*/ /* [↓] find largest right truncated P.*/ do R=# by -1 for # /*search from top end; get the length.*/ do k=1 for length(@.R); _= left(@.R, k) /*validate all right truncatable primes*/ if \!._ then iterate R /*Truncated number not prime? Skip it.*/ end /*k*/ leave /*egress, found right truncatable prime*/ end /*R*/   say 'The largest left─truncatable prime ≤' hi " is " right(@.L, w) say 'The largest right─truncatable prime ≤' hi " is " right(@.R, w) exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ genP: !.= 0; w= length(hi) /*placeholders for primes; max width. */ @.1=2; @.2=3; @.3=5; @.4=7; @.5=11 /*define some low primes. */  !.2=1;  !.3=1;  !.5=1;  !.7=1;  !.11=1 /* " " " " flags. */ #=5; s.#= @.# **2 /*number of primes so far; prime². */ /* [↓] generate more primes ≤ high.*/ do j=@.#+2 by 2 for max(0, hi%2-@.#%2-1) /*find odd primes from here on. */ parse var j '' -1 _; if _==5 then iterate /*J divisible by 5? (right dig)*/ if j// 3==0 then iterate /*" " " 3? */ if j// 7==0 then iterate /*" " " 7? */ /* [↑] the above five lines saves time*/ do k=5 while s.k<=j /* [↓] divide by the known odd primes.*/ if j // @.k == 0 then iterate j /*Is J ÷ X? Then not prime. ___ */ end /*k*/ /* [↑] only process numbers ≤ √ J */ #= #+1; @.#= j; s.#= j*j;  !.j= 1 /*bump # of Ps; assign next P; P²; P# */ end /*j*/ return
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 / / \ 7 8 9 The correct output should look like this: preorder: 1 2 4 7 5 3 6 8 9 inorder: 7 4 2 5 1 8 6 9 3 postorder: 7 4 5 2 8 9 6 3 1 level-order: 1 2 3 4 5 6 7 8 9 See also   Wikipedia article:   Tree traversal.
#F.23
F#
open System open System.IO   type Tree<'a> = | Tree of 'a * Tree<'a> * Tree<'a> | Empty   let rec inorder tree = seq { match tree with | Tree(x, left, right) -> yield! inorder left yield x yield! inorder right | Empty -> () }   let rec preorder tree = seq { match tree with | Tree(x, left, right) -> yield x yield! preorder left yield! preorder right | Empty -> () }   let rec postorder tree = seq { match tree with | Tree(x, left, right) -> yield! postorder left yield! postorder right yield x | Empty -> () }   let levelorder tree = let rec loop queue = seq { match queue with | [] -> () | (Empty::tail) -> yield! loop tail | (Tree(x, l, r)::tail) -> yield x yield! loop (tail @ [l; r]) } loop [tree]   [<EntryPoint>] let main _ = let tree = Tree (1, Tree (2, Tree (4, Tree (7, Empty, Empty), Empty), Tree (5, Empty, Empty)), Tree (3, Tree (6, Tree (8, Empty, Empty), Tree (9, Empty, Empty)), Empty))   let show x = printf "%d " x   printf "preorder: " preorder tree |> Seq.iter show printf "\ninorder: " inorder tree |> Seq.iter show printf "\npostorder: " postorder tree |> Seq.iter show printf "\nlevel-order: " levelorder tree |> Seq.iter show 0
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: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#D.C3.A9j.C3.A0_Vu
Déjà Vu
!print join "." 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: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#E
E
".".rjoin("Hello,How,Are,You,Today".split(","))
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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Forth
Forth
: time: ( "word" -- ) utime 2>R ' EXECUTE utime 2R> D- <# # # # # # # [CHAR] . HOLD #S #> TYPE ." seconds" ;   1000 time: MS \ 1.000081 seconds ok
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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Fortran
Fortran
  c The subroutine to analyze subroutine do_something() c For testing we just do nothing for 3 seconds call sleep(3) return end   c Main Program program timing integer(kind=8) start,finish,rate call system_clock(count_rate=rate) call system_clock(start) c Here comes the function we want to time call do_something() call system_clock(finish) write(6,*) 'Elapsed Time in seconds:',float(finish-start)/rate return end  
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,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190
#Forth
Forth
  \ Written in ANS-Forth; tested under VFX. \ Requires the novice package: http://www.forth.org/novice.html \ The following should already be done: \ include novice.4th \ include list.4th   marker TopRank.4th   \ This demonstrates how I typically use lists. A program such as this does not need any explicit iteration, so it is more like Factor than C. \ I would define high-level languages as those that allow programs to be written without explicit iteration. Iteration is a major source of bugs. \ The C library has QSORT that hides iteration, but user-written code very rarely uses this technique, and doesn't in the TopRank example.     \ ****** \ ****** The following defines our data-structure. \ ****** Pretty much every struct definition has these basic functions. \ ******   list w field .name \ string w field .id \ string w field .salary \ integer w field .dept \ string constant employee   : init-employee ( name id salary department node -- node ) init-list >r hstr r@ .dept ! r@ .salary ! hstr r@ .id ! hstr r@ .name ! r> ;   : new-employee ( name id salary dept -- node ) employee alloc init-employee ;   : <kill-employee> ( node -- ) dup .name @ dealloc dup .id @ dealloc dup .dept @ dealloc dealloc ;   : kill-employee ( head -- ) each[ <kill-employee> ]each ;   : <clone-employee> ( node -- new-node ) clone-node dup .name @ hstr over .name ! dup .id @ hstr over .id ! dup .dept @ hstr over .dept ! ;   : clone-employee ( head -- new-head ) nil swap each[ <clone-employee> link ]each ;   : <show-employee> ( node -- ) dup .id @ count type 4 spaces dup .dept @ count type 4 spaces dup .salary @ . 4 spaces dup .name @ count type cr drop ;   : show-employee ( head -- ) cr each[ <show-employee> ]each ;     \ ****** \ ****** The following code is specific to the query that we want to do in this example problem. \ ******   : employee-dept-salary ( new-node node -- new-node ? ) \ for use by FIND-PRIOR or INSERT-ORDERED 2dup .dept @ count rot .dept @ count compare  ?dup if A>B = nip exit then .salary @ over .salary @ < ;   : <top> ( n rank current-dept head node -- n rank current-dept head ) 2>r \ -- n rank current-dept dup count r@ .dept @ count compare A=B <> if \ we have a new department 2drop \ discard RANK and CURRENT-DEPT 0 r@ .dept @ then \ start again with a new RANK and CURRENT-DEPT rover rover > if \ if N > RANK then it is good r> r> over \ -- n rank current-dept node head node <clone-employee> link \ -- n rank current-dept node head >r >r then \ -- n rank current-dept swap 1+ swap \ increment RANK rdrop r> ; \ -- n rank current-dept head   : top ( n head -- new-head ) \ make a new list of the top N salary earners in each dept \ requires that list be sorted by dept-salary >r 0 c" xxx" nil \ -- n rank current-dept new-head \ initially for an invalid department r> ['] <top> each 3nip ;     \ ****** \ ****** The following is a test of the program using sample data. \ ******   nil ' employee-dept-salary c" Tyler Bennett" c" E10297" 32000 c" D101" new-employee insert-ordered c" John Rappl" c" E21437" 47000 c" D050" new-employee insert-ordered c" George Woltman" c" E00127" 53500 c" D101" new-employee insert-ordered c" Adam Smith" c" E63535" 18000 c" D202" new-employee insert-ordered c" Claire Buckman" c" E39876" 27800 c" D202" new-employee insert-ordered c" David McClellan" c" E04242" 41500 c" D101" new-employee insert-ordered c" Rich Holcomb" c" E01234" 49500 c" D202" new-employee insert-ordered c" Nathan Adams" c" E41298" 21900 c" D050" new-employee insert-ordered c" Richard Potter" c" E43128" 15900 c" D101" new-employee insert-ordered c" David Motsinger" c" E27002" 19250 c" D202" new-employee insert-ordered c" Tim Sampair" c" E03033" 27000 c" D101" new-employee insert-ordered c" Kim Arlich" c" E10001" 57000 c" D190" new-employee insert-ordered c" Timothy Grove" c" E16398" 29900 c" D190" new-employee insert-ordered drop constant test-data   cr .( N = 0 ) 0 test-data top dup show-employee kill-employee   cr .( N = 1 ) 1 test-data top dup show-employee kill-employee   cr .( N = 2 ) 2 test-data top dup show-employee kill-employee   cr .( N = 3 ) 3 test-data top dup show-employee kill-employee   test-data kill-employee  
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.   Wikipedia tic-tac-toe.
#EasyLang
EasyLang
len f[] 9 state = 0 textsize 14 # func init . . linewidth 2 clear color 666 move 34 4 line 34 80 move 62 4 line 62 80 move 10 28 line 86 28 move 10 56 line 86 56 linewidth 2.5 for i range 9 f[i] = 0 . if state = 1 timer 0.2 . . func draw ind . . c = ind mod 3 r = ind div 3 x = c * 28 + 20 y = r * 28 + 14 if f[ind] = 4 color 900 move x - 7 y - 7 line x + 7 y + 7 move x + 7 y - 7 line x - 7 y + 7 elif f[ind] = 1 color 009 move x y circle 10 color -2 circle 7.5 . . func sum3 a d . st . for i range 3 s += f[a] a += d . if s = 3 st = -1 elif s = 12 st = 1 . . func rate . res done . res = 0 for i range 3 call sum3 i * 3 1 res . for i range 3 call sum3 i 3 res . call sum3 0 4 res call sum3 2 2 res cnt = 1 for i range 9 if f[i] = 0 cnt += 1 . . res *= cnt done = 1 if res = 0 and cnt > 1 done = 0 . . func minmax player alpha beta . rval rmov . call rate rval done if done = 1 if player = 1 rval = -rval . else rval = alpha start = random 9 mov = start repeat if f[mov] = 0 f[mov] = player call minmax (5 - player) (-beta) (-rval) val h val = -val f[mov] = 0 if val > rval rval = val rmov = mov . . mov = (mov + 1) mod 9 until mov = start or rval >= beta . . . func show_result val . . color 555 move 16 84 if val < 0 # this never happens text "You won" elif val > 0 text "You lost" else text "Tie" . state += 2 . func computer . . call minmax 4 -11 11 val mov f[mov] = 4 call draw mov call rate val done state = 0 if done = 1 call show_result val . . func human . . mov = floor ((mouse_x - 6) / 28) + 3 * floor (mouse_y / 28) if f[mov] = 0 f[mov] = 1 call draw mov state = 1 timer 0.5 . . on timer call rate val done if done = 1 call show_result val else call computer . . on mouse_down if state = 0 if mouse_x > 6 and mouse_x < 90 and mouse_y < 84 call human . elif state >= 2 state -= 2 call init . . call init
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#C.23
C#
public void move(int n, int from, int to, int via) { if (n == 1) { System.Console.WriteLine("Move disk from pole " + from + " to pole " + to); } else { move(n - 1, from, via, to); move(1, from, to, via); move(n - 1, via, to, from); } }
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
#Perl
Perl
sub complement { my $s = shift;   $s =~ tr/01/10/;   return $s; }   my $str = '0';   for (0..6) { say $str; $str .= complement($str); }  
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
#Phix
Phix
string tm = "0" for i=1 to 8 do printf(1,"%s\n",tm) tm &= sq_sub('0'+'1',tm) end for
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 separated by the separators, become the elements of the output list. Empty fields should be preserved, even at the start and end. Rules for escaping: "Escaped" means preceded by an occurrence of the escape character that is not already escaped itself. When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special). Each occurrence of the escape character that was used to escape something, should not become part of the output. Test case Demonstrate that your function satisfies the following test-case: Input Output string: one^|uno||three^^^^|four^^^|^cuatro| separator character: | escape character: ^ one|uno three^^ four^|cuatro (Print the output list in any format you like, as long as it is it easy to see what the fields are.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PicoLisp
PicoLisp
(de tokenize (Str Sep Esc) (split (make (for (L (chop Str) L) (let C (pop 'L) (cond ((= C Esc) (link (pop 'L))) ((= C Sep) (link 0)) (T (link C)) ) ) ) ) 0 ) )
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 separated by the separators, become the elements of the output list. Empty fields should be preserved, even at the start and end. Rules for escaping: "Escaped" means preceded by an occurrence of the escape character that is not already escaped itself. When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special). Each occurrence of the escape character that was used to escape something, should not become part of the output. Test case Demonstrate that your function satisfies the following test-case: Input Output string: one^|uno||three^^^^|four^^^|^cuatro| separator character: | escape character: ^ one|uno three^^ four^|cuatro (Print the output list in any format you like, as long as it is it easy to see what the fields are.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PowerShell
PowerShell
  function Split-String ([string]$String, [char]$Separator, [char]$Escape) { if ($String -notmatch "\$Separator|\$Escape") {return $String}   [bool]$escaping = $false [string]$output = ""   for ($i = 0; $i -lt $String.Length; $i++) { [char]$character = $String.Substring($i,1)   if ($escaping) { $output += $character $escaping = $false } else { switch ($character) { {$_ -eq $Separator} {$output; $output = ""; break} {$_ -eq $Escape} {$escaping = $true  ; break} Default {$output += $character} } } }   if ($String[-1] -eq $Separator) {[String]::Empty} }  
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon. The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on. A tool exists that extracts library dependencies. Task Write a function that will return a valid compile order of VHDL libraries from their dependencies. Assume library names are single words. Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given. Any self dependencies should be ignored. Any un-orderable dependencies should be flagged. Use the following data as an example: LIBRARY LIBRARY DEPENDENCIES ======= ==================== des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee dw01 ieee dw01 dware gtech dw02 ieee dw02 dware dw03 std synopsys dware dw03 dw02 dw01 ieee gtech dw04 dw04 ieee dw01 dware gtech dw05 dw05 ieee dware dw06 dw06 ieee dware dw07 ieee dware dware ieee dware gtech ieee gtech ramlib std ieee std_cell_lib ieee std_cell_lib synopsys Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01. C.f.   Topological sort/Extracted top item. There are two popular algorithms for topological sorting:   Kahn's 1962 topological sort [1]   depth-first search [2] [3]
#Kotlin
Kotlin
// version 1.1.51   val s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05, " + "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys"   val deps = mutableListOf( 2 to 0, 2 to 14, 2 to 13, 2 to 4, 2 to 3, 2 to 12, 2 to 1, 3 to 1, 3 to 10, 3 to 11, 4 to 1, 4 to 10, 5 to 0, 5 to 14, 5 to 10, 5 to 4, 5 to 3, 5 to 1, 5 to 11, 6 to 1, 6 to 3, 6 to 10, 6 to 11, 7 to 1, 7 to 10, 8 to 1, 8 to 10, 9 to 1, 9 to 10, 10 to 1, 11 to 1, 12 to 0, 12 to 1, 13 to 1 )   class Graph(s: String, edges: List<Pair<Int,Int>>) {   val vertices = s.split(", ") val numVertices = vertices.size val adjacency = List(numVertices) { BooleanArray(numVertices) }   init { for (edge in edges) adjacency[edge.first][edge.second] = true }   fun hasDependency(r: Int, todo: List<Int>): Boolean { return todo.any { adjacency[r][it] } }   fun topoSort(): List<String>? { val result = mutableListOf<String>() val todo = MutableList<Int>(numVertices) { it } try { outer@ while(!todo.isEmpty()) { for ((i, r) in todo.withIndex()) { if (!hasDependency(r, todo)) { todo.removeAt(i) result.add(vertices[r]) continue@outer } } throw Exception("Graph has cycles") } } catch (e: Exception) { println(e) return null } return result } }   fun main(args: Array<String>) { val g = Graph(s, deps) println("Topologically sorted order:") println(g.topoSort()) println() // now insert 3 to 6 at index 10 of deps deps.add(10, 3 to 6) val g2 = Graph(s, deps) println("Following the addition of dw04 to the dependencies of dw01:") println(g2.topoSort()) }
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 a machine capable of taking the definition of any other Turing machine and executing it. Of course, you will not have an infinite tape, but you should emulate this as much as is possible. The three permissible actions on the tape are "left", "right" and "stay". To test your universal Turing machine (and prove your programming language is Turing complete!), you should execute the following two Turing machines based on the following definitions. Simple incrementer States: q0, qf Initial state: q0 Terminating states: qf Permissible symbols: B, 1 Blank symbol: B Rules: (q0, 1, 1, right, q0) (q0, B, 1, stay, qf) The input for this machine should be a tape of 1 1 1 Three-state busy beaver States: a, b, c, halt Initial state: a Terminating states: halt Permissible symbols: 0, 1 Blank symbol: 0 Rules: (a, 0, 1, right, b) (a, 1, 1, left, c) (b, 0, 1, left, a) (b, 1, 1, right, b) (c, 0, 1, left, b) (c, 1, 1, stay, halt) The input for this machine should be an empty tape. Bonus: 5-state, 2-symbol probable Busy Beaver machine from Wikipedia States: A, B, C, D, E, H Initial state: A Terminating states: H Permissible symbols: 0, 1 Blank symbol: 0 Rules: (A, 0, 1, right, B) (A, 1, 1, left, C) (B, 0, 1, right, C) (B, 1, 1, right, B) (C, 0, 1, right, D) (C, 1, 0, left, E) (D, 0, 1, left, A) (D, 1, 1, left, D) (E, 0, 1, stay, H) (E, 1, 0, left, A) The input for this machine should be an empty tape. This machine runs for more than 47 millions steps.
#Python
Python
from __future__ import print_function   def run_utm( state = None, blank = None, rules = [], tape = [], halt = None, pos = 0): st = state if not tape: tape = [blank] if pos < 0: pos += len(tape) if pos >= len(tape) or pos < 0: raise Error( "bad init position") rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)   while True: print(st, '\t', end=" ") for i, v in enumerate(tape): if i == pos: print("[%s]" % (v,), end=" ") else: print(v, end=" ") print()   if st == halt: break if (st, tape[pos]) not in rules: break   (v1, dr, s1) = rules[(st, tape[pos])] tape[pos] = v1 if dr == 'left': if pos > 0: pos -= 1 else: tape.insert(0, blank) if dr == 'right': pos += 1 if pos >= len(tape): tape.append(blank) st = s1     # EXAMPLES   print("incr machine\n") run_utm( halt = 'qf', state = 'q0', tape = list("111"), blank = 'B', rules = map(tuple, ["q0 1 1 right q0".split(), "q0 B 1 stay qf".split()] ) )   print("\nbusy beaver\n") run_utm( halt = 'halt', state = 'a', blank = '0', rules = map(tuple, ["a 0 1 right b".split(), "a 1 1 left c".split(), "b 0 1 left a".split(), "b 1 1 right b".split(), "c 0 1 left b".split(), "c 1 1 stay halt".split()] ) )   print("\nsorting test\n") run_utm(halt = 'STOP', state = 'A', blank = '0', tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(), rules = map(tuple, ["A 1 1 right A".split(), "A 2 3 right B".split(), "A 0 0 left E".split(), "B 1 1 right B".split(), "B 2 2 right B".split(), "B 0 0 left C".split(), "C 1 2 left D".split(), "C 2 2 left C".split(), "C 3 2 left E".split(), "D 1 1 left D".split(), "D 2 2 left D".split(), "D 3 1 right A".split(), "E 1 1 left E".split(), "E 0 0 right STOP".split()] ) )  
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 positive integer   n   that are relatively prime to   n   counts the integers   k   in the range   1 ≤ k ≤ n   for which the greatest common divisor   gcd(n,k)   is equal to   1   counts numbers   ≤ n   and   prime to   n If the totient number   (for N)   is one less than   N,   then   N   is prime. Task Create a   totient   function and:   Find and display   (1 per line)   for the 1st   25   integers:   the integer   (the index)   the totient number for that integer   indicate if that integer is prime   Find and display the   count   of the primes up to          100   Find and display the   count   of the primes up to       1,000   Find and display the   count   of the primes up to     10,000   Find and display the   count   of the primes up to   100,000     (optional) Show all output here. Related task   Perfect totient numbers Also see   Wikipedia: Euler's totient function.   MathWorld: totient function.   OEIS: Euler totient function phi(n).
#Raku
Raku
use Prime::Factor;   my \𝜑 = 0, |(1..*).hyper.map: -> \t { t * [*] t.&prime-factors.squish.map: { 1 - 1/$_ } }   printf "𝜑(%2d) = %3d %s\n", $_, 𝜑[$_], $_ - 𝜑[$_] - 1 ?? '' !! 'Prime' for 1 .. 25;   (1e2, 1e3, 1e4, 1e5).map: -> $limit { say "\nCount of primes <= $limit: " ~ +(^$limit).grep: {$_ == 𝜑[$_] + 1} }
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 is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle). For the inverse functions,   use the same number and convert its answer to radians and degrees. If your language does not have trigonometric functions available or only has some available,   write functions to calculate the functions based on any   known approximation or identity.
#Java
Java
public class Trig { public static void main(String[] args) { //Pi / 4 is 45 degrees. All answers should be the same. double radians = Math.PI / 4; double degrees = 45.0; //sine System.out.println(Math.sin(radians) + " " + Math.sin(Math.toRadians(degrees))); //cosine System.out.println(Math.cos(radians) + " " + Math.cos(Math.toRadians(degrees))); //tangent System.out.println(Math.tan(radians) + " " + Math.tan(Math.toRadians(degrees))); //arcsine double arcsin = Math.asin(Math.sin(radians)); System.out.println(arcsin + " " + Math.toDegrees(arcsin)); //arccosine double arccos = Math.acos(Math.cos(radians)); System.out.println(arccos + " " + Math.toDegrees(arccos)); //arctangent double arctan = Math.atan(Math.tan(radians)); System.out.println(arctan + " " + Math.toDegrees(arctan)); } }
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 the algorithm. From the wikipedia entry: ask for 11 numbers to be read into a sequence S reverse sequence S for each item in sequence S result := call a function to do an operation if result overflows alert user else print result The task is to implement the algorithm: Use the function:     f ( x ) = | x | 0.5 + 5 x 3 {\displaystyle f(x)=|x|^{0.5}+5x^{3}} The overflow condition is an answer of greater than 400. The 'user alert' should not stop processing of other items of the sequence. Print a prompt before accepting eleven, textual, numeric inputs. You may optionally print the item as well as its associated result, but the results must be in reverse order of input. The sequence   S   may be 'implied' and so not shown explicitly. Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#Symsyn
Symsyn
  |Trabb Pardo–Knuth algorithm   a : 11 0   i if i LE 10 [] $s ~ $s w w a.i + i goif endif 10 i if i GE 0 call f if x GT 400 'too large' $s else ~ x $s endif ~ i $r + ' ' $r + $r $s.1 $s [] - i goif endif stop   f a.i t * t t x * x t x * 5 x abs t sqrt t y + y x return  
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 the algorithm. From the wikipedia entry: ask for 11 numbers to be read into a sequence S reverse sequence S for each item in sequence S result := call a function to do an operation if result overflows alert user else print result The task is to implement the algorithm: Use the function:     f ( x ) = | x | 0.5 + 5 x 3 {\displaystyle f(x)=|x|^{0.5}+5x^{3}} The overflow condition is an answer of greater than 400. The 'user alert' should not stop processing of other items of the sequence. Print a prompt before accepting eleven, textual, numeric inputs. You may optionally print the item as well as its associated result, but the results must be in reverse order of input. The sequence   S   may be 'implied' and so not shown explicitly. Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#Tcl
Tcl
# Helper procedures proc f {x} {expr {abs($x)**0.5 + 5*$x**3}} proc overflow {y} {expr {$y > 400}}   # Read in 11 numbers, with nice prompting fconfigure stdout -buffering none for {set n 1} {$n <= 11} {incr n} { puts -nonewline "number ${n}: " lappend S [scan [gets stdin] "%f"] }   # Process and print results in reverse order foreach x [lreverse $S] { set result [f $x] if {[overflow $result]} { puts "${x}: TOO LARGE!" } else { puts "${x}: $result" } }
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, 739, 73, and 7 formed by removing digits from its right are also prime. No zeroes are allowed in truncatable primes. Task The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied). Related tasks Find largest left truncatable prime in a given base Sieve of Eratosthenes See also Truncatable Prime from MathWorld.]
#Ring
Ring
  # Project : Truncatable primes   for n = 1000000 to 1 step -1 flag = 1 flag2 = 1 strn = string(n) for nr = 1 to len(strn) if strn[nr] = "0" flag2 = 0 ok next if flag2 = 1 for m = 1 to len(strn) strp = right(strn, m) if isprime(number(strp)) else flag = 0 exit ok next if flag = 1 nend = n exit ok ok next see "Largest left truncatable prime : " + nend + nl   for n = 1000000 to 1 step -1 flag = 1 strn = string(n) for m = 1 to len(strn) strp = left(strn, len(strn) - m + 1) if isprime(number(strp)) else flag = 0 exit ok next if flag = 1 nend = n exit ok next see "Largest right truncatable prime : " + nend + nl   func isprime num if (num <= 1) return 0 ok if (num % 2 = 0 and num != 2) return 0 ok for i = 3 to floor(num / 2) -1 step 2 if (num % i = 0) return 0 ok next return 1  
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, 739, 73, and 7 formed by removing digits from its right are also prime. No zeroes are allowed in truncatable primes. Task The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied). Related tasks Find largest left truncatable prime in a given base Sieve of Eratosthenes See also Truncatable Prime from MathWorld.]
#Ruby
Ruby
def left_truncatable?(n) truncatable?(n) {|i| i.to_s[1..-1].to_i} end     def right_truncatable?(n) truncatable?(n) {|i| i/10} end   def truncatable?(n, &trunc_func) return false if n.to_s.include? "0" loop do n = trunc_func.call(n) return true if n.zero? return false unless Prime.prime?(n) end end   require 'prime' primes = Prime.each(1_000_000).to_a.reverse   p primes.detect {|p| left_truncatable? p} p primes.detect {|p| right_truncatable? p}
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 / / \ 7 8 9 The correct output should look like this: preorder: 1 2 4 7 5 3 6 8 9 inorder: 7 4 2 5 1 8 6 9 3 postorder: 7 4 5 2 8 9 6 3 1 level-order: 1 2 3 4 5 6 7 8 9 See also   Wikipedia article:   Tree traversal.
#Factor
Factor
USING: accessors combinators deques dlists fry io kernel math.parser ; IN: rosetta.tree-traversal   TUPLE: node data left right ;   CONSTANT: example-tree T{ node f 1 T{ node f 2 T{ node f 4 T{ node f 7 f f } f } T{ node f 5 f f } } T{ node f 3 T{ node f 6 T{ node f 8 f f } T{ node f 9 f f } } f } }   : preorder ( node quot: ( data -- ) -- ) [ [ data>> ] dip call ] [ [ left>> ] dip over [ preorder ] [ 2drop ] if ] [ [ right>> ] dip over [ preorder ] [ 2drop ] if ] 2tri ; inline recursive   : inorder ( node quot: ( data -- ) -- ) [ [ left>> ] dip over [ inorder ] [ 2drop ] if ] [ [ data>> ] dip call ] [ [ right>> ] dip over [ inorder ] [ 2drop ] if ] 2tri ; inline recursive   : postorder ( node quot: ( data -- ) -- ) [ [ left>> ] dip over [ postorder ] [ 2drop ] if ] [ [ right>> ] dip over [ postorder ] [ 2drop ] if ] [ [ data>> ] dip call ] 2tri ; inline recursive   : (levelorder) ( dlist quot: ( data -- ) -- ) over deque-empty? [ 2drop ] [ [ dup pop-front ] dip { [ [ data>> ] dip call drop ] [ drop left>> [ swap push-back ] [ drop ] if* ] [ drop right>> [ swap push-back ] [ drop ] if* ] [ nip (levelorder) ] } 3cleave ] if ; inline recursive   : levelorder ( node quot: ( data -- ) -- ) [ 1dlist ] dip (levelorder) ; inline   : levelorder2 ( node quot: ( data -- ) -- ) [ 1dlist ] dip [ dup deque-empty? not ] swap '[ dup pop-front [ data>> @ ] [ left>> [ over push-back ] when* ] [ right>> [ over push-back ] when* ] tri ] while drop ; inline   : main ( -- ) example-tree [ number>string write " " write ] { [ "preorder: " write preorder nl ] [ "inorder: " write inorder nl ] [ "postorder: " write postorder nl ] [ "levelorder: " write levelorder nl ] [ "levelorder2: " write levelorder2 nl ] } 2cleave ;
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: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Elena
Elena
import system'routines; import extensions;   public program() { var string := "Hello,How,Are,You,Today";   string.splitBy:",".forEach:(s) { console.print(s,".") } }
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: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Elixir
Elixir
  tokens = String.split("Hello,How,Are,You,Today", ",") IO.puts Enum.join(tokens, ".")  
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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function sumToLimit(limit As UInteger) As UInteger Dim sum As UInteger = 0 For i As UInteger = 1 To limit sum += i Next Return sum End Function   Dim As Double start = timer Dim limit As UInteger = 100000000 Dim result As UInteger = sumToLimit(limit) Dim ms As UInteger = Int(1000 * (timer - start) + 0.5) Print "sumToLimit("; Str(limit); ") = "; result Print "took "; ms; " milliseconds to calculate" Print Print "Press any key to quit" Sleep
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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#GAP
GAP
# Return the time passed in last function time;
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,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190
#Fortran
Fortran
DATA EMPLOYEE(1:3)/ 1 GRIST("Tyler Bennett","E10297",32000,"D101"), 2 GRIST("John Rappl","E21437",47000,"D050"), 3 GRIST("George Woltman","E00127",53500,"D101")/  
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.   Wikipedia tic-tac-toe.
#Erlang
Erlang
  -module(tic_tac_toe).   -export( [task/0] ).   task() -> io:fwrite( "Result: ~p.~n", [turn(player(random:uniform()), board())] ).       board() -> [{X, erlang:integer_to_list(X)} || X <- lists:seq(1, 9)].   board_tuples( Selections, Board ) -> [lists:keyfind(X, 1, Board) || X <- Selections].   computer_move( Player, Board ) -> [N | _T] = lists:flatten( [X(Player, Board) || X <- [fun computer_move_win/2, fun computer_move_block/2, fun computer_move_middle/2, fun computer_move_random/2]] ), N.   computer_move_block( Player, Board ) -> computer_move_two_same_player( player(false, Player), Board ).   computer_move_middle( _Player, Board ) -> {5, Y} = lists:keyfind( 5, 1, Board ), computer_move_middle( is_empty(Y) ).   computer_move_middle( true ) -> [5]; computer_move_middle( false ) -> [].   computer_move_random( _Player, Board ) -> Ns = [X || {X, Y} <- Board, is_empty(Y)], [lists:nth( random:uniform(erlang:length(Ns)), Ns )].   computer_move_two_same_player( Player, Board ) -> Selections = [X || X <- three_in_row_all(), is_two_same_player(Player, X, Board)], computer_move_two_same_player( Player, Board, Selections ).   computer_move_two_same_player( _Player, _Board, [] ) -> []; computer_move_two_same_player( _Player, Board, [Selection | _T] ) -> [X || {X, Y} <- board_tuples(Selection, Board), is_empty(Y)].   computer_move_win( Player, Board ) -> computer_move_two_same_player( Player, Board ).   is_empty( Square ) -> Square =< "9". % Do not use < "10".   is_finished( Board ) -> is_full( Board ) orelse is_three_in_row( Board ).   is_full( Board ) -> [] =:= [X || {X, Y} <- Board, is_empty(Y)].   is_three_in_row( Board ) -> Fun = fun(Selections) -> is_three_in_row_same_player( board_tuples(Selections, Board) ) end, lists:any( Fun, three_in_row_all() ).   is_three_in_row_same_player( Selected ) -> three_in_row_player( Selected ) =/= no_player.   is_two_same_player( Player, Selections, Board ) -> is_two_same_player( Player, [{X, Y} || {X, Y} <- board_tuples(Selections, Board), not is_empty(Y)] ).   is_two_same_player( Player, [{_X, Player}, {_Y, Player}] ) -> true; is_two_same_player( _Player, _Selected ) -> false.   player( Random ) when Random > 0.5 -> "O"; player( _Random ) -> "X".   player( true, _Player ) -> finished; player( false, "X" ) -> "O"; player( false, "O" ) -> "X".   result( Board ) -> result( is_full(Board), Board ).   result( true, _Board ) -> draw; result( false, Board ) -> [Winners] = [Selections || Selections <- three_in_row_all(), three_in_row_player(board_tuples(Selections, Board)) =/= no_player], "Winner is " ++ three_in_row_player( board_tuples(Winners, Board) ).   three_in_row_all() -> three_in_row_horisontal() ++ three_in_row_vertical() ++ three_in_row_diagonal(). three_in_row_diagonal() -> [[1,5,9], [3,5,7]]. three_in_row_horisontal() -> [[1,2,3], [4,5,6], [7,8,9]]. three_in_row_vertical() -> [[1,4,7], [2,5,8], [3,6,9]].   three_in_row_player( [{_X, Player}, {_Y, Player}, {_Z, Player}] ) -> three_in_row_player( not is_empty(Player), Player ); three_in_row_player( _Selected ) -> no_player.   three_in_row_player( true, Player ) -> Player; three_in_row_player( false, _Player ) -> no_player.   turn( finished, Board ) -> result( Board ); turn( "X"=Player, Board ) -> N = computer_move( Player, Board ), io:fwrite( "Computer, ~p, selected ~p~n", [Player, N] ), New_board = [{N, Player} | lists:keydelete(N, 1, Board)], turn( player(is_finished(New_board), Player), New_board ); turn( "O"=Player, Board ) -> [turn_board_write_horisontal(X, Board) || X <- three_in_row_horisontal()], Ns = [X || {X, Y} <- Board, is_empty(Y)], Prompt = lists:flatten( io_lib:format("Player, ~p, select one of ~p: ", [Player, Ns]) ), N = turn_next_move( Prompt, Ns ), New_board = [{N, Player} | lists:keydelete(N, 1, Board)], turn( player(is_finished(New_board), Player), New_board ).   turn_board_write_horisontal( Selections, Board ) -> Tuples = [lists:keyfind(X, 1, Board) || X <- Selections], [io:fwrite( "~p ", [Y]) || {_X, Y} <- Tuples], io:fwrite( "~n" ).   turn_next_move( Prompt, Ns ) -> {ok,[N]} = io:fread( Prompt, "~d" ), turn_next_move_ok( lists:member(N, Ns), Prompt, Ns, N ).   turn_next_move_ok( true, _Prompt, _Ns, N ) -> N; turn_next_move_ok( false, Prompt, Ns, _N ) -> turn_next_move( Prompt, Ns ).  
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#C.2B.2B
C++
void move(int n, int from, int to, int via) { if (n == 1) { std::cout << "Move disk from pole " << from << " to pole " << to << std::endl; } else { move(n - 1, from, via, to); move(1, from, to, via); move(n - 1, via, to, from); } }
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
#Phixmonti
Phixmonti
def inverte dup len for var i i get not i set endfor enddef   0 1 tolist 8 for . dup print nl nl inverte chain endfor
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
#PHP
PHP
<?php   function thueMorseSequence($length) { $sequence = ''; for ($digit = $n = 0 ; $n < $length ; $n++) { $x = $n ^ ($n - 1); if (($x ^ ($x >> 1)) & 0x55555555) { $digit = 1 - $digit; } $sequence .= $digit; } return $sequence; }   for ($n = 10 ; $n <= 100 ; $n += 10) { echo sprintf('%3d', $n), ' : ', thueMorseSequence($n), PHP_EOL; }
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 separated by the separators, become the elements of the output list. Empty fields should be preserved, even at the start and end. Rules for escaping: "Escaped" means preceded by an occurrence of the escape character that is not already escaped itself. When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special). Each occurrence of the escape character that was used to escape something, should not become part of the output. Test case Demonstrate that your function satisfies the following test-case: Input Output string: one^|uno||three^^^^|four^^^|^cuatro| separator character: | escape character: ^ one|uno three^^ four^|cuatro (Print the output list in any format you like, as long as it is it easy to see what the fields are.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Python
Python
def token_with_escape(a, escape = '^', separator = '|'): ''' Issue python -m doctest thisfile.py to run the doctests.   >>> print(token_with_escape('one^|uno||three^^^^|four^^^|^cuatro|')) ['one|uno', '', 'three^^', 'four^|cuatro', ''] ''' result = [] token = '' state = 0 for c in a: if state == 0: if c == escape: state = 1 elif c == separator: result.append(token) token = '' else: token += c elif state == 1: token += c state = 0 result.append(token) return result
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 separated by the separators, become the elements of the output list. Empty fields should be preserved, even at the start and end. Rules for escaping: "Escaped" means preceded by an occurrence of the escape character that is not already escaped itself. When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special). Each occurrence of the escape character that was used to escape something, should not become part of the output. Test case Demonstrate that your function satisfies the following test-case: Input Output string: one^|uno||three^^^^|four^^^|^cuatro| separator character: | escape character: ^ one|uno three^^ four^|cuatro (Print the output list in any format you like, as long as it is it easy to see what the fields are.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Racket
Racket
#lang racket/base (require racket/match)   ;; Returns a tokenising function based on sep and esc (define ((tokenise-with-escape sep esc) str) (define tsil->string (compose list->string reverse)) (define (inr rem l-acc acc) (match rem ['() (if (and (null? acc) (null? l-acc)) null (reverse (cons (tsil->string l-acc) acc)))] [(list (== sep) tl ...) (inr tl null (cons (tsil->string l-acc) acc))] [(list (== esc) c tl ...) (inr tl (cons c l-acc) acc)] [(list c tl ...) (inr tl (cons c l-acc) acc)])) (inr (string->list str) null null))   ;; This is the tokeniser that matches the parameters in the task (define task-tokeniser (tokenise-with-escape #\| #\^))   (define (report-input-output str) (printf "Input: ~s~%Output: ~s~%~%" str (task-tokeniser str)))   (report-input-output "one^|uno||three^^^^|four^^^|^cuatro|") (report-input-output "") (report-input-output "|") (report-input-output "^") (report-input-output ".")
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon. The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on. A tool exists that extracts library dependencies. Task Write a function that will return a valid compile order of VHDL libraries from their dependencies. Assume library names are single words. Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given. Any self dependencies should be ignored. Any un-orderable dependencies should be flagged. Use the following data as an example: LIBRARY LIBRARY DEPENDENCIES ======= ==================== des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee dw01 ieee dw01 dware gtech dw02 ieee dw02 dware dw03 std synopsys dware dw03 dw02 dw01 ieee gtech dw04 dw04 ieee dw01 dware gtech dw05 dw05 ieee dware dw06 dw06 ieee dware dw07 ieee dware dware ieee dware gtech ieee gtech ramlib std ieee std_cell_lib ieee std_cell_lib synopsys Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01. C.f.   Topological sort/Extracted top item. There are two popular algorithms for topological sorting:   Kahn's 1962 topological sort [1]   depth-first search [2] [3]
#M2000_Interpreter
M2000 Interpreter
Module testthis { \\ empty stack Flush inventory LL append LL, "des_system_lib":=(List:="std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee") REM append LL, "dw01":=(List:="dw04","ieee", "dw01", "dware", "gtech") append LL, "dw01":=(List:="ieee", "dw01", "dware", "gtech") append LL, "dw02":=(List:="ieee", "dw02", "dware") append LL, "dw03":=(List:="std", "synopsys", "dware", "dw03", "dw02", "dw01", "ieee", "gtech") append LL, "dw04":=(List:= "ieee", "dw01", "dware", "gtech") append LL, "dw05":=(List:="dw05", "ieee", "dware") append LL, "dw06":=(List:="dw06", "ieee", "dware") append LL, "dw07":=(List:="ieee", "dware") append LL, "dware":=(List:="ieee", "dware") append LL, "gtech":=(List:="ieee", "gtech") append LL, "ramlib":=(List:="std", "ieee") append LL, "std_cell_lib":=(List:="ieee", "std_cell_lib") append LL, "synopsys":=List \\ inventory itmes may have keys/items or keys. \\ here we have keys so keys return as item also \\ when we place an item in a key (an empty string) ... \\ we mark the item to not return the key but an empty string inventory final mm=each(LL) while mm k$=eval$(mm!) m=eval(mm) mmm=each(m) While mmm k1$=eval$(mmm!) if not exist(LL, k1$) then if not exist(final, k1$) then append final, k1$ return m, k1$:="" \\ mark that item else mmmm=Eval(LL) if len(mmmm)=0 then if not exist(final, k1$) then append final, k1$ return m, k1$:="" \\ mark that item end if end if end while end while mm=each(LL) while mm \\ using eval$(mm!) we read the key as string k$=eval$(mm!) if exist(final, k$) then continue m=eval(mm) mmm=each(m) While mmm \\ we read the item, if no item exist we get the key k1$=eval$(mmm) if k1$="" then continue if exist(final, k1$) then continue data k1$ \\ push to end to stack end while while not empty read k1$ if exist(final, k1$) then continue m=LL(k1$) mmm=each(m) delthis=0 While mmm k2$=eval$(mmm) if k2$="" then continue if k1$=k2$ then continue if exist(final, k2$) then continue push k2$ \\ push to top of stack return m, k2$:="" delthis++ end while if delthis=0 then if not exist(final, k1$) then mmm=each(m) While mmm k2$=eval$(mmm!) if k2$=k1$ then continue if exist(final, k2$) Else Print "unsorted:";k1$, k2$ end if end while append final, k1$ : Return LL, k1$:=List end if end if end while if not exist(final, k$) then append final, k$ end while document doc$ ret=each(final,1, -2) while ret doc$=eval$(ret)+" -> " end while doc$=final$(len(final)-1!) Report doc$ clipboard doc$ } testthis  
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 a machine capable of taking the definition of any other Turing machine and executing it. Of course, you will not have an infinite tape, but you should emulate this as much as is possible. The three permissible actions on the tape are "left", "right" and "stay". To test your universal Turing machine (and prove your programming language is Turing complete!), you should execute the following two Turing machines based on the following definitions. Simple incrementer States: q0, qf Initial state: q0 Terminating states: qf Permissible symbols: B, 1 Blank symbol: B Rules: (q0, 1, 1, right, q0) (q0, B, 1, stay, qf) The input for this machine should be a tape of 1 1 1 Three-state busy beaver States: a, b, c, halt Initial state: a Terminating states: halt Permissible symbols: 0, 1 Blank symbol: 0 Rules: (a, 0, 1, right, b) (a, 1, 1, left, c) (b, 0, 1, left, a) (b, 1, 1, right, b) (c, 0, 1, left, b) (c, 1, 1, stay, halt) The input for this machine should be an empty tape. Bonus: 5-state, 2-symbol probable Busy Beaver machine from Wikipedia States: A, B, C, D, E, H Initial state: A Terminating states: H Permissible symbols: 0, 1 Blank symbol: 0 Rules: (A, 0, 1, right, B) (A, 1, 1, left, C) (B, 0, 1, right, C) (B, 1, 1, right, B) (C, 0, 1, right, D) (C, 1, 0, left, E) (D, 0, 1, left, A) (D, 1, 1, left, D) (E, 0, 1, stay, H) (E, 1, 0, left, A) The input for this machine should be an empty tape. This machine runs for more than 47 millions steps.
#Racket
Racket
  #lang racket ;;;============================================================= ;;; Due to heavy use of pattern matching we define few macros ;;;=============================================================   (define-syntax-rule (define-m f m ...) (define f (match-lambda m ... (x x))))   (define-syntax-rule (define-m* f m ...) (define f (match-lambda** m ...)))   ;;;============================================================= ;;; The definition of a functional type Tape, ;;; representing infinite tape with O(1) operations: ;;; put, get, shift-right and shift-left. ;;;============================================================= (struct Tape (the-left-part  ; i-1 i-2 i-3 ... the-current-record ; i the-right-part))  ; i+1 i+2 i+3 ...   ;; the initial record on the tape (define-m initial-tape [(cons h t) (Tape '() h t)])   ;; shifts caret to the right (define (snoc a b) (cons b a)) (define-m shift-right [(Tape '() '() (cons h t)) (Tape '() h t)]  ; left end [(Tape l x '()) (Tape (snoc l x) '() '())]  ; right end [(Tape l x (cons h t)) (Tape (snoc l x) h t)]) ; general case   ;; shifts caret to the left (define-m flip-tape [(Tape l x r) (Tape r x l)])   (define shift-left (compose flip-tape shift-right flip-tape))   ;; returns the current record on the tape (define-m get [(Tape _ v _) v])   ;; writes to the current position on the tape (define-m* put [('() t) t] [(v (Tape l _ r)) (Tape l v r)])   ;; Shows the list representation of the tape (≤ O(n)). ;; A tape is shown as (... a b c (d) e f g ...) ;; where (d) marks the current position of the caret.   (define (revappend a b) (foldl cons b a))   (define-m show-tape [(Tape '() '() '()) '()] [(Tape l '() r) (revappend l (cons '() r))] [(Tape l v r) (revappend l (cons (list v) r))])   ;;;------------------------------------------------------------------- ;;; The Turing Machine interpreter ;;;   ;; interpretation of output triple for a given tape (define-m* interprete [((list v 'right S) tape) (list S (shift-right (put v tape)))] [((list v 'left S) tape) (list S (shift-left (put v tape)))] [((list v 'stay S) tape) (list S (put v tape))] [((list S _) tape) (list S tape)])   ;; Runs the program. ;; The initial state is set to start. ;; The initial tape is given as a list of records. ;; The initial position is the leftmost symbol of initial record. (define (run-turing prog t0 start) ((fixed-point (match-lambda [`(,S ,T) (begin (printf "~a\t~a\n" S (show-tape T)) (interprete (prog `(,S ,(get T))) T))])) (list start (initial-tape t0))))   ;; a general fixed point operator (define ((fixed-point f) x) (let F ([x x] [fx (f x)]) (if (equal? x fx) fx (F fx (f fx)))))   ;; A macro for definition of a Turing-Machines. ;; Transforms to a function which accepts a list of initial ;; tape records as input and returns the tape after stopping. (define-syntax-rule (Turing-Machine #:start start (a b c d e) ...) (λ (l) (displayln "STATE\tTAPE") ((match-lambda [(list _ t) (flatten (show-tape t))]) (run-turing (match-lambda ['(a b) '(c d e)] ... [x x]) l start))))  
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 positive integer   n   that are relatively prime to   n   counts the integers   k   in the range   1 ≤ k ≤ n   for which the greatest common divisor   gcd(n,k)   is equal to   1   counts numbers   ≤ n   and   prime to   n If the totient number   (for N)   is one less than   N,   then   N   is prime. Task Create a   totient   function and:   Find and display   (1 per line)   for the 1st   25   integers:   the integer   (the index)   the totient number for that integer   indicate if that integer is prime   Find and display the   count   of the primes up to          100   Find and display the   count   of the primes up to       1,000   Find and display the   count   of the primes up to     10,000   Find and display the   count   of the primes up to   100,000     (optional) Show all output here. Related task   Perfect totient numbers Also see   Wikipedia: Euler's totient function.   MathWorld: totient function.   OEIS: Euler totient function phi(n).
#REXX
REXX
/*REXX program calculates the totient numbers for a range of numbers, and count primes. */ parse arg N . /*obtain optional argument from the CL.*/ if N=='' | N=="," then N= 25 /*Not specified? Then use the default.*/ tell= N>0 /*N positive>? Then display them all. */ N= abs(N) /*use the absolute value of N for loop.*/ w= length(N) /*W: is used in aligning the output. */ primes= 0 /*the number of primes found (so far).*/ /*if N was negative, only count primes.*/ do j=1 for N; T= phi(j) /*obtain totient number for a number. */ prime= word('(prime)', 1 + (T \== j-1 ) ) /*determine if J is a prime number. */ if prime\=='' then primes= primes + 1 /*if a prime, then bump the prime count*/ if tell then say 'totient number for ' right(j, w) " ──► " right(T, w) ' ' prime end /*j*/ say say right(primes, w) ' primes detected for numbers up to and including ' N exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ gcd: parse arg x,y; do until y==0; parse value x//y y with y x end /*until*/; return x /*──────────────────────────────────────────────────────────────────────────────────────*/ phi: procedure; parse arg z; if z==1 then return 1 #= 1 do m=2 for z-2; if gcd(m, z)==1 then #= # + 1 end /*m*/; return #
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 is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle). For the inverse functions,   use the same number and convert its answer to radians and degrees. If your language does not have trigonometric functions available or only has some available,   write functions to calculate the functions based on any   known approximation or identity.
#JavaScript
JavaScript
var radians = Math.PI / 4, // Pi / 4 is 45 degrees. All answers should be the same. degrees = 45.0, sine = Math.sin(radians), cosine = Math.cos(radians), tangent = Math.tan(radians), arcsin = Math.asin(sine), arccos = Math.acos(cosine), arctan = Math.atan(tangent);   // sine window.alert(sine + " " + Math.sin(degrees * Math.PI / 180)); // cosine window.alert(cosine + " " + Math.cos(degrees * Math.PI / 180)); // tangent window.alert(tangent + " " + Math.tan(degrees * Math.PI / 180)); // arcsine window.alert(arcsin + " " + (arcsin * 180 / Math.PI)); // arccosine window.alert(arccos + " " + (arccos * 180 / Math.PI)); // arctangent window.alert(arctan + " " + (arctan * 180 / Math.PI));
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 the algorithm. From the wikipedia entry: ask for 11 numbers to be read into a sequence S reverse sequence S for each item in sequence S result := call a function to do an operation if result overflows alert user else print result The task is to implement the algorithm: Use the function:     f ( x ) = | x | 0.5 + 5 x 3 {\displaystyle f(x)=|x|^{0.5}+5x^{3}} The overflow condition is an answer of greater than 400. The 'user alert' should not stop processing of other items of the sequence. Print a prompt before accepting eleven, textual, numeric inputs. You may optionally print the item as well as its associated result, but the results must be in reverse order of input. The sequence   S   may be 'implied' and so not shown explicitly. Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#VBScript
VBScript
  Function tpk(s) arr = Split(s," ") For i = UBound(arr) To 0 Step -1 n = fx(CDbl(arr(i))) If n > 400 Then WScript.StdOut.WriteLine arr(i) & " = OVERFLOW" Else WScript.StdOut.WriteLine arr(i) & " = " & n End If Next End Function   Function fx(x) fx = Sqr(Abs(x))+5*x^3 End Function   'testing the function WScript.StdOut.Write "Please enter a series of numbers:" list = WScript.StdIn.ReadLine tpk(list)  
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, 739, 73, and 7 formed by removing digits from its right are also prime. No zeroes are allowed in truncatable primes. Task The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied). Related tasks Find largest left truncatable prime in a given base Sieve of Eratosthenes See also Truncatable Prime from MathWorld.]
#Rust
Rust
fn is_prime(n: u32) -> bool { if n < 2 { return false; } if n % 2 == 0 { return n == 2; } if n % 3 == 0 { return n == 3; } let mut p = 5; while p * p <= n { if n % p == 0 { return false; } p += 2; if n % p == 0 { return false; } p += 4; } true }   fn is_left_truncatable(p: u32) -> bool { let mut n = 10; let mut q = p; while p > n { if !is_prime(p % n) || q == p % n { return false; } q = p % n; n *= 10; } true }   fn is_right_truncatable(p: u32) -> bool { let mut q = p / 10; while q > 0 { if !is_prime(q) { return false; } q /= 10; } true }   fn main() { let limit = 1000000; let mut largest_left = 0; let mut largest_right = 0; let mut p = limit; while p >= 2 { if is_prime(p) && is_left_truncatable(p) { largest_left = p; break; } p -= 1; } println!("Largest left truncatable prime is {}", largest_left); p = limit; while p >= 2 { if is_prime(p) && is_right_truncatable(p) { largest_right = p; break; } p -= 1; } println!("Largest right truncatable prime is {}", largest_right); }
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 / / \ 7 8 9 The correct output should look like this: preorder: 1 2 4 7 5 3 6 8 9 inorder: 7 4 2 5 1 8 6 9 3 postorder: 7 4 5 2 8 9 6 3 1 level-order: 1 2 3 4 5 6 7 8 9 See also   Wikipedia article:   Tree traversal.
#Fantom
Fantom
  class Tree { readonly Int label readonly Tree? left readonly Tree? right   new make (Int label, Tree? left := null, Tree? right := null) { this.label = label this.left = left this.right = right }   Void preorder(|Int->Void| func) { func(label) left?.preorder(func) // ?. will not call method if 'left' is null right?.preorder(func) }   Void postorder(|Int->Void| func) { left?.postorder(func) right?.postorder(func) func(label) }   Void inorder(|Int->Void| func) { left?.inorder(func) func(label) right?.inorder(func) }   Void levelorder(|Int->Void| func) { Tree[] nodes := [this] while (nodes.size > 0) { Tree cur := nodes.removeAt(0) func(cur.label) if (cur.left != null) nodes.add (cur.left) if (cur.right != null) nodes.add (cur.right) } } }   class Main { public static Void main () { tree := Tree(1, Tree(2, Tree(4, Tree(7)), Tree(5)), Tree(3, Tree(6, Tree(8), Tree(9)))) List result := [,] collect := |Int a -> Void| { result.add(a) } tree.preorder(collect) echo ("preorder: " + result.join(" ")) result = [,] tree.inorder(collect) echo ("inorder: " + result.join(" ")) result = [,] tree.postorder(collect) echo ("postorder: " + result.join(" ")) result = [,] tree.levelorder(collect) echo ("levelorder: " + result.join(" ")) } }