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/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.
#E
E
def pi := (-1.0).acos()   def radians := pi / 4.0 def degrees := 45.0   def d2r := (pi/180).multiply def r2d := (180/pi).multiply   println(`$\ ${radians.sin()} ${d2r(degrees).sin()} ${radians.cos()} ${d2r(degrees).cos()} ${radians.tan()} ${d2r(degrees).tan()} ${def asin := radians.sin().asin()} ${r2d(asin)} ${def acos := radians.cos().acos()} ${r2d(acos)} ${def atan := radians.tan().atan()} ${r2d(atan)} `)
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).
#jq
jq
def f: def abs: if . < 0 then -. else . end; def power(x): (x * log) | exp; . as $x | abs | power(0.5) + (5 * (.*.*. ));   . as $in | split(" ") | map(tonumber) | if length == 11 then reverse | map(f | if . > 400 then "TOO LARGE" else . end) else error("The number of numbers was not 11.") end | .[] # print one result per line
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).
#Julia
Julia
f(x) = √abs(x) + 5x^3 for i in reverse(split(readline())) v = f(parse(Int, i)) println("$(i): ", v > 400 ? "TOO LARGE" : v) end
http://rosettacode.org/wiki/Twelve_statements
Twelve statements
This puzzle is borrowed from   math-frolic.blogspot. Given the following twelve statements, which of them are true? 1. This is a numbered list of twelve statements. 2. Exactly 3 of the last 6 statements are true. 3. Exactly 2 of the even-numbered statements are true. 4. If statement 5 is true, then statements 6 and 7 are both true. 5. The 3 preceding statements are all false. 6. Exactly 4 of the odd-numbered statements are true. 7. Either statement 2 or 3 is true, but not both. 8. If statement 7 is true, then 5 and 6 are both true. 9. Exactly 3 of the first 6 statements are true. 10. The next two statements are both true. 11. Exactly 1 of statements 7, 8 and 9 are true. 12. Exactly 4 of the preceding statements are true. Task When you get tired of trying to figure it out in your head, write a program to solve it, and print the correct answer or answers. Extra credit Print out a table of near misses, that is, solutions that are contradicted by only a single statement.
#Yabasic
Yabasic
sub s1() return len(s$)=12 end sub sub s2() local t, i : t=0 : for i=7 to 12 : t = t + (mid$(s$, i, 1) <> "0") : next : return t=3 end sub sub s3() local t, i : t=0 : for i=2 to 12 step 2 : t = t + (mid$(s$, i, 1) <> "0") : next : return t=2 end sub sub s4() return mid$(s$, 5, 1) = "0" or (mid$(s$, 6, 1) <> "0" and mid$(s$, 7, 1) <> "0") end sub sub s5() return mid$(s$, 2, 1) = "0" and mid$(s$, 3, 1) = "0" and mid$(s$, 4, 1) = "0" end sub sub s6() local t, i : t=0 : for i=1 to 12 step 2 : t = t + mid$(s$, i, 1) <> "0" : next : return t=4 end sub sub s7() return mid$(s$, 2, 1) <> mid$(s$, 3, 1) end sub sub s8() return mid$(s$, 7, 1) = "0" or (mid$(s$, 5, 1) <> "0" and mid$(s$, 6, 1) <> "0") end sub sub s9() local t, i : t=0 : for i=1 to 6 : t = t + mid$(s$, i, 1) <> "0" : next : return t=3 end sub sub s10() return mid$(s$, 11, 1) <> "0" and mid$(s$, 12, 1) <> "0" end sub sub s11() local t, i : t=0 : for i=7 to 9 : t = t + mid$(s$, i, 1) <> "0" : next : return t=1 end sub sub s12() local t, i : t=0 : for i=1 to 11 : t = t + mid$(s$, i, 1) <> "0" : next : return t=4 end sub   dim r$(12)   for b=1 to 12 r$(b) = "s"+str$(b) next for i=0 to 2^12-1 s$ = right$("000000000000" + bin$(i), 12) for b=1 to 12 if execute(r$(b)) <> (mid$(s$, b, 1) <> "0") break if b=12 print s$ next next
http://rosettacode.org/wiki/Twelve_statements
Twelve statements
This puzzle is borrowed from   math-frolic.blogspot. Given the following twelve statements, which of them are true? 1. This is a numbered list of twelve statements. 2. Exactly 3 of the last 6 statements are true. 3. Exactly 2 of the even-numbered statements are true. 4. If statement 5 is true, then statements 6 and 7 are both true. 5. The 3 preceding statements are all false. 6. Exactly 4 of the odd-numbered statements are true. 7. Either statement 2 or 3 is true, but not both. 8. If statement 7 is true, then 5 and 6 are both true. 9. Exactly 3 of the first 6 statements are true. 10. The next two statements are both true. 11. Exactly 1 of statements 7, 8 and 9 are true. 12. Exactly 4 of the preceding statements are true. Task When you get tired of trying to figure it out in your head, write a program to solve it, and print the correct answer or answers. Extra credit Print out a table of near misses, that is, solutions that are contradicted by only a single statement.
#zkl
zkl
var statements; // list of 13 Bools, statements[0] is garbage to make 1 based fcn s0 { False } // dummy for padding fcn s1 { True } fcn s2 { statements[-6,*].filter().len()==3 } fcn s3 { [2..12,2].apply(statements.get).filter().len()==2 } fcn s4 { if(statements[5]) statements[6]==statements[7]==True else True } fcn s5 { statements[2,3].filter().len()==0 } fcn s6 { [1..12,2].apply(statements.get).filter().len()==4 } fcn s7 { statements[2]!=statements[3] } fcn s8 { if(statements[7]) statements[5]==statements[6]==True else True } fcn s9 { statements[1,6].filter().len()==3 } fcn s10{ statements[11]==statements[12]==True } fcn s11{ statements[7,3].filter().len()==1 } fcn s12{ statements[1,11].filter().len()==4 }   filters:=T(s0,s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12); foreach n in ((2).pow(12)){ // 4k // 5-->"0000000000101"-->("0","0"..."1")-->(F,F,...T) statements="%013.2B".fmt(n).split("").apply('==("1")); r:=filters.run(True); // and return list of results if(r==statements) print("<<<<<<<<<<<<<<<<Solution"); else{ diff:=r.zipWith('!=,statements); if(diff.sum(0)==1) print("Diff @",diff.filter1n()); } } fcn print(msg){ (12).pump(List,'wrap(n){ statements[n] and n or Void.Skip }) .concat(",").println(" : ",vm.pasteArgs()); }
http://rosettacode.org/wiki/Truth_table
Truth table
A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function. Task Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function. (One can assume that the user input is correct). Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function. Either reverse-polish or infix notation expressions are allowed. Related tasks   Boolean values   Ternary logic See also   Wolfram MathWorld entry on truth tables.   some "truth table" examples from Google.
#Raku
Raku
use MONKEY-SEE-NO-EVAL;   sub MAIN ($x) { my @n = $x.comb(/<ident>/); my &fun = EVAL "-> {('\\' «~« @n).join(',')} \{ [{ (|@n,"so $x").join(',') }] \}";   say (|@n,$x).join("\t"); .join("\t").say for map &fun, flat map { .fmt("\%0{+@n}b").comb».Int».so }, 0 ..^ 2**@n; say ''; }
http://rosettacode.org/wiki/Ulam_spiral_(for_primes)
Ulam spiral (for primes)
An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is shown with sequential integers,   starting at   1. In an Ulam spiral of primes, only the primes are shown (usually indicated by some glyph such as a dot or asterisk),   and all non-primes as shown as a blank   (or some other whitespace). Of course, the grid and border are not to be displayed (but they are displayed here when using these Wiki HTML tables). Normally, the spiral starts in the "center",   and the   2nd   number is to the viewer's right and the number spiral starts from there in a counter-clockwise direction. There are other geometric shapes that are used as well, including clock-wise spirals. Also, some spirals (for the   2nd   number)   is viewed upwards from the   1st   number instead of to the right, but that is just a matter of orientation. Sometimes, the starting number can be specified to show more visual striking patterns (of prime densities). [A larger than necessary grid (numbers wise) is shown here to illustrate the pattern of numbers on the diagonals   (which may be used by the method to orientate the direction of spiral-construction algorithm within the example computer programs)]. Then, in the next phase in the transformation of the Ulam prime spiral,   the non-primes are translated to blanks. In the orange grid below,   the primes are left intact,   and all non-primes are changed to blanks. Then, in the final transformation of the Ulam spiral (the yellow grid),   translate the primes to a glyph such as a   •   or some other suitable glyph. 65 64 63 62 61 60 59 58 57 66 37 36 35 34 33 32 31 56 67 38 17 16 15 14 13 30 55 68 39 18 5 4 3 12 29 54 69 40 19 6 1 2 11 28 53 70 41 20 7 8 9 10 27 52 71 42 21 22 23 24 25 26 51 72 43 44 45 46 47 48 49 50 73 74 75 76 77 78 79 80 81 61 59 37 31 67 17 13 5 3 29 19 2 11 53 41 7 71 23 43 47 73 79 • • • • • • • • • • • • • • • • • • • • • • The Ulam spiral becomes more visually obvious as the grid increases in size. Task For any sized   N × N   grid,   construct and show an Ulam spiral (counter-clockwise) of primes starting at some specified initial number   (the default would be 1),   with some suitably   dotty   (glyph) representation to indicate primes,   and the absence of dots to indicate non-primes. You should demonstrate the generator by showing at Ulam prime spiral large enough to (almost) fill your terminal screen. Related tasks   Spiral matrix   Zig-zag matrix   Identity matrix   Sequence of primes by Trial Division See also Wikipedia entry:   Ulam spiral MathWorld™ entry:   Prime Spiral
#Ruby
Ruby
require 'prime'   def cell(n, x, y, start=1) y, x = y - n/2, x - (n - 1)/2 l = 2 * [x.abs, y.abs].max d = y >= x ? l*3 + x + y : l - x - y (l - 1)**2 + d + start - 1 end   def show_spiral(n, symbol=nil, start=1) puts "\nN : #{n}" format = "%#{(start + n*n - 1).to_s.size}s " n.times do |y| n.times do |x| i = cell(n,x,y,start) if symbol print i.prime? ? symbol[0] : symbol[1] else print format % (i.prime? ? i : '') end end puts end end   show_spiral(9) show_spiral(25) show_spiral(25, "# ")
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.]
#Maple
Maple
  MaxTruncatablePrime := proc({left::truefalse:=FAIL, right::truefalse:=FAIL}, $) local i, j, c, p, b, n, sdprimes, dir; local tprimes := table(); if left = true and right = true then error "invalid input"; elif right = true then dir := "right"; else dir := "left"; end if; b := 10; n := 6; sdprimes := select(isprime, [seq(1..b-1)]); for p in sdprimes do if assigned(tprimes[p]) then next; end if; i := ilog[b](p)+1; j := 1; while p < b^n do if dir = "left" then c := j*b^i + p; else c := p*b + j; end if; if j >= b or c > b^n then # we have tried all 1 digit extensions of p, add p to tprimes and move back 1 digit tprimes[p] := p; if i = 1 then # if we are at the first digit, go to the next 1 digit prime break; end if; i := i - 1; j := 1; if dir = "left" then p := p - iquo(p, b^i)*b^i; else p := iquo(p, b); end if; elif assigned(tprimes[c]) then j := j + 1; elif isprime(c) then p := c; i := i + 1; j := 1; else j := j+1; end if; end do; end do; return max(indices(tprimes, 'nolist')); end proc;
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.]
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
LeftTruncatablePrimeQ[n_] := Times @@ IntegerDigits[n] > 0 && And @@ PrimeQ /@ ToExpression /@ StringJoin /@ Rest[Most[NestList[Rest, #, Length[#]] &[Characters[ToString[n]]]]] RightTruncatablePrimeQ[n_] := Times @@ IntegerDigits[n] > 0 && And @@ PrimeQ /@ ToExpression /@ StringJoin /@ Rest[Most[NestList[Most, #, Length[#]] &[Characters[ToString[n]]]]]
http://rosettacode.org/wiki/Tree_traversal
Tree traversal
Task Implement a binary tree where each node carries an integer,   and implement:   pre-order,   in-order,   post-order,     and   level-order   traversal. Use those traversals to output the following tree: 1 / \ / \ / \ 2 3 / \ / 4 5 6 / / \ 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.
#C.2B.2B
C++
#include <boost/scoped_ptr.hpp> #include <iostream> #include <queue>   template<typename T> class TreeNode { public: TreeNode(const T& n, TreeNode* left = NULL, TreeNode* right = NULL) : mValue(n), mLeft(left), mRight(right) {}   T getValue() const { return mValue; }   TreeNode* left() const { return mLeft.get(); }   TreeNode* right() const { return mRight.get(); }   void preorderTraverse() const { std::cout << " " << getValue(); if(mLeft) { mLeft->preorderTraverse(); } if(mRight) { mRight->preorderTraverse(); } }   void inorderTraverse() const { if(mLeft) { mLeft->inorderTraverse(); } std::cout << " " << getValue(); if(mRight) { mRight->inorderTraverse(); } }   void postorderTraverse() const { if(mLeft) { mLeft->postorderTraverse(); } if(mRight) { mRight->postorderTraverse(); } std::cout << " " << getValue(); }   void levelorderTraverse() const { std::queue<const TreeNode*> q; q.push(this);   while(!q.empty()) { const TreeNode* n = q.front(); q.pop(); std::cout << " " << n->getValue();   if(n->left()) { q.push(n->left()); } if(n->right()) { q.push(n->right()); } } }   protected: T mValue; boost::scoped_ptr<TreeNode> mLeft; boost::scoped_ptr<TreeNode> mRight;   private: TreeNode(); };   int main() { TreeNode<int> root(1, new TreeNode<int>(2, new TreeNode<int>(4, new TreeNode<int>(7)), new TreeNode<int>(5)), new TreeNode<int>(3, new TreeNode<int>(6, new TreeNode<int>(8), new TreeNode<int>(9))));   std::cout << "preorder: "; root.preorderTraverse(); std::cout << std::endl;   std::cout << "inorder: "; root.inorderTraverse(); std::cout << std::endl;   std::cout << "postorder: "; root.postorderTraverse(); std::cout << std::endl;   std::cout << "level-order:"; root.levelorderTraverse(); std::cout << std::endl;   return 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
#ALGOL_68
ALGOL 68
main:(   OP +:= = (REF FLEX[]STRING in out, STRING item)VOID:( [LWB in out: UPB in out+1]STRING new; new[LWB in out: UPB in out]:=in out; new[UPB new]:=item; in out := new );   PROC string split = (REF STRING beetles, STRING substr)[]STRING:( """ Split beetles where substr is found """; FLEX[1:0]STRING out; INT start := 1, pos; WHILE string in string(substr, pos, beetles[start:]) DO out +:= STRING(beetles[start:start+pos-2]); start +:= pos + UPB substr - 1 OD; IF start > LWB beetles THEN out +:= STRING(beetles[start:]) FI; out );   PROC char split = (REF STRING beetles, STRING chars)[]STRING: ( """ Split beetles where character is found in chars """; FLEX[1:0]STRING out; FILE beetlef; associate(beetlef, beetles); # associate a FILE handle with a STRING # make term(beetlef, chars); # make term: assign CSV string terminator #   PROC raise logical file end = (REF FILE f)BOOL: except logical file end; on logical file end(beetlef, raise logical file end);   STRING solo; DO getf(beetlef, ($g$, solo)); out+:=solo; getf(beetlef, ($x$)) # skip CHAR separator # OD; except logical file end: SKIP; out );   STRING beetles := "John Lennon, Paul McCartney, George Harrison, Ringo Starr";   printf(($g"."$, string split(beetles, ", "),$l$)); printf(($g"."$, char split(beetles, ", "),$l$)) )
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.
#11l
11l
F do_work(x) V n = x L(i) 10000000 n += i R n   F time_func(f) V start = time:perf_counter() f() R time:perf_counter() - start   print(time_func(() -> do_work(100)))
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
#Bracmat
Bracmat
(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)  : ?employees & ( toprank = employees N n P "Employee Name" "Employee ID" SalaryDepartment .  !arg:(?employees.?N) & 1:?P & whl ' (  !employees  : (?"Employee Name",?"Employee ID",?Salary,?Department)  ?employees & !Department^(!Salary.!"Employee Name".!"Employee ID")*!P:?P ) & out$(Top !N "salaries per department.") & whl ' ( !P:%?Department^?employees*?P & out$(str$("Department " !Department ":")) & !N:?n & whl ' ( !n+-1:~<0:?n &  !employees  : ?employees+(?Salary.?"Employee Name".?"Employee ID") & out $ (str$(" " !"Employee Name" " (" !"Employee ID" "):" !Salary)) ) ) ) & toprank$(!employees.3) & ;
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#AppleScript
AppleScript
--------------------- TOWERS OF HANOI --------------------   -- hanoi :: Int -> (String, String, String) -> [(String, String)] on hanoi(n, abc) script go on |λ|(n, {x, y, z}) if n > 0 then set m to n - 1   |λ|(m, {x, z, y}) & ¬ {{x, y}} & |λ|(m, {z, y, x}) else {} end if end |λ| end script   go's |λ|(n, abc) end hanoi     --------------------------- TEST ------------------------- on run unlines(map(intercalate(" -> "), ¬ hanoi(3, {"left", "right", "mid"}))) end run     -------------------- GENERIC FUNCTIONS -------------------   -- intercalate :: String -> [String] -> String on intercalate(delim) script on |λ|(xs) set {dlm, my text item delimiters} to ¬ {my text item delimiters, delim} set s to xs as text set my text item delimiters to dlm s end |λ| end script end intercalate     -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: First-class m => (a -> b) -> m (a -> b) on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn     -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map     -- unlines :: [String] -> String on unlines(xs) set {dlm, my text item delimiters} to ¬ {my text item delimiters, linefeed} set str to xs as text set my text item delimiters to dlm str end unlines
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
#CLU
CLU
% Yields an infinite Thue-Morse sequence, digit by digit tm = iter () yields (char) n: int := 1 s: string := "0" while true do while n <= string$size(s) do yield(s[n]) n := n + 1 end s2: array[char] := array[char]$[] for c: char in string$chars(s) do if c='0' then array[char]$addh(s2, '1') else array[char]$addh(s2, '0') end end s := s || string$ac2s(s2) end end tm   % Print the first 64 characters start_up = proc () AMOUNT = 64 po: stream := stream$primary_output() n: int := 0 for c: char in tm() do stream$putc(po, c) n := n + 1 if n = AMOUNT then break end end end start_up
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
#Common_Lisp
Common Lisp
(defun bit-complement (bit-vector) (loop with result = (make-array (length bit-vector) :element-type 'bit) for b across bit-vector for i from 0 do (setf (aref result i) (- 1 b)) finally (return result)))   (defun next (bit-vector) (concatenate 'bit-vector bit-vector (bit-complement bit-vector)))   (defun print-bit-vector (bit-vector) (loop for b across bit-vector do (princ b) finally (terpri)))   (defun thue-morse (max) (loop repeat (1+ max) for value = #*0 then (next value) do (print-bit-vector value)))   (thue-morse 6)
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm
Tonelli-Shanks algorithm
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computational number theory, the Tonelli–Shanks algorithm is a technique for solving for x in a congruence of the form: x2 ≡ n (mod p) where n is an integer which is a quadratic residue (mod p), p is an odd prime, and x,n ∈ Fp where Fp = {0, 1, ..., p - 1}. It is used in cryptography techniques. To apply the algorithm, we need the Legendre symbol: The Legendre symbol (a | p) denotes the value of a(p-1)/2 (mod p). (a | p) ≡ 1    if a is a square (mod p) (a | p) ≡ -1    if a is not a square (mod p) (a | p) ≡ 0    if a ≡ 0 (mod p) Algorithm pseudo-code All ≡ are taken to mean (mod p) unless stated otherwise. Input: p an odd prime, and an integer n . Step 0: Check that n is indeed a square: (n | p) must be ≡ 1 . Step 1: By factoring out powers of 2 from p - 1, find q and s such that p - 1 = q2s with q odd . If p ≡ 3 (mod 4) (i.e. s = 1), output the two solutions r ≡ ± n(p+1)/4 . Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq . Step 3: Set r ≡ n(q+1)/2, t ≡ nq, m = s . Step 4: Loop the following: If t ≡ 1, output r and p - r . Otherwise find, by repeated squaring, the lowest i, 0 < i < m , such that t2i ≡ 1 . Let b ≡ c2(m - i - 1), and set r ≡ rb, t ≡ tb2, c ≡ b2 and m = i . Task Implement the above algorithm. Find solutions (if any) for n = 10 p = 13 n = 56 p = 101 n = 1030 p = 10009 n = 1032 p = 10009 n = 44402 p = 100049 Extra credit n = 665820697 p = 1000000009 n = 881398088036 p = 1000000000039 n = 41660815127637347468140745042827704103445750172002 p = 10^50 + 577 See also Modular exponentiation Cipolla's algorithm
#J
J
leg=: dyad define x (y&|)@^ (y-1)%2 )   tosh=:dyad define assert. 1=1 p: y [ 'y must be prime' assert. 1=x leg y [ 'x must be square mod y' pow=. y&|@^ if. 1=m=. {.1 q: y-1 do. r=. x pow (y+1)%4 else. z=. 1x while. 1>: z leg y do. z=.z+1 end. c=. z pow q=. (y-1)%2^m r=. x pow (q+1)%2 t=. x pow q while. t~:1 do. n=. t i=. 0 whilst. 1~:n do. n=. n pow 2 i=. i+1 end. r=. y|r*b=. c pow 2^m-i+1 m=. i t=. y|t*c=. b pow 2 end. end. y|(,-)r )
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
#D
D
import std.stdio;   void main() { string sample = "one^|uno||three^^^^|four^^^|^cuatro|";   writeln(sample); writeln(tokenizeString(sample, '|', '^')); }   auto tokenizeString(string source, char seperator, char escape) { import std.array : appender; import std.exception : enforce;   auto output = appender!(string[]); auto token = appender!(char[]);   bool inEsc; foreach(ch; source) { if (inEsc) { inEsc = false; } else if (ch == escape) { inEsc = true; continue; } else if (ch == seperator) { output.put(token.data.idup); token.clear(); continue; } token.put(ch); } enforce(!inEsc, "Invalid terminal escape");   output.put(token.data.idup); return output.data; }
http://rosettacode.org/wiki/Total_circles_area
Total circles area
Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal digits of precision. The area covered by two or more disks needs to be counted only once. One point of this Task is also to compare and discuss the relative merits of various solution strategies, their performance, precision and simplicity. This means keeping both slower and faster solutions for a language (like C) is welcome. To allow a better comparison of the different implementations, solve the problem with this standard dataset, each line contains the x and y coordinates of the centers of the disks and their radii   (11 disks are fully contained inside other disks): xc yc radius 1.6417233788 1.6121789534 0.0848270516 -1.4944608174 1.2077959613 1.1039549836 0.6110294452 -0.6907087527 0.9089162485 0.3844862411 0.2923344616 0.2375743054 -0.2495892950 -0.3832854473 1.0845181219 1.7813504266 1.6178237031 0.8162655711 -0.1985249206 -0.8343333301 0.0538864941 -1.7011985145 -0.1263820964 0.4776976918 -0.4319462812 1.4104420482 0.7886291537 0.2178372997 -0.9499557344 0.0357871187 -0.6294854565 -1.3078893852 0.7653357688 1.7952608455 0.6281269104 0.2727652452 1.4168575317 1.0683357171 1.1016025378 1.4637371396 0.9463877418 1.1846214562 -0.5263668798 1.7315156631 1.4428514068 -1.2197352481 0.9144146579 1.0727263474 -0.1389358881 0.1092805780 0.7350208828 1.5293954595 0.0030278255 1.2472867347 -0.5258728625 1.3782633069 1.3495508831 -0.1403562064 0.2437382535 1.3804956588 0.8055826339 -0.0482092025 0.3327165165 -0.6311979224 0.7184578971 0.2491045282 1.4685857879 -0.8347049536 1.3670667538 -0.6855727502 1.6465021616 1.0593087096 0.0152957411 0.0638919221 0.9771215985 The result is   21.56503660... . Related task   Circles of given radius through two points. See also http://www.reddit.com/r/dailyprogrammer/comments/zff9o/9062012_challenge_96_difficult_water_droplets/ http://stackoverflow.com/a/1667789/10562
#Phix
Phix
with javascript_semantics constant circles = {{ 1.6417233788, 1.6121789534, 0.0848270516}, {-1.4944608174, 1.2077959613, 1.1039549836}, { 0.6110294452, -0.6907087527, 0.9089162485}, { 0.3844862411, 0.2923344616, 0.2375743054}, {-0.2495892950, -0.3832854473, 1.0845181219}, { 1.7813504266, 1.6178237031, 0.8162655711}, {-0.1985249206, -0.8343333301, 0.0538864941}, {-1.7011985145, -0.1263820964, 0.4776976918}, {-0.4319462812, 1.4104420482, 0.7886291537}, { 0.2178372997, -0.9499557344, 0.0357871187}, {-0.6294854565, -1.3078893852, 0.7653357688}, { 1.7952608455, 0.6281269104, 0.2727652452}, { 1.4168575317, 1.0683357171, 1.1016025378}, { 1.4637371396, 0.9463877418, 1.1846214562}, {-0.5263668798, 1.7315156631, 1.4428514068}, {-1.2197352481, 0.9144146579, 1.0727263474}, {-0.1389358881, 0.1092805780, 0.7350208828}, { 1.5293954595, 0.0030278255, 1.2472867347}, {-0.5258728625, 1.3782633069, 1.3495508831}, {-0.1403562064, 0.2437382535, 1.3804956588}, { 0.8055826339, -0.0482092025, 0.3327165165}, {-0.6311979224, 0.7184578971, 0.2491045282}, { 1.4685857879, -0.8347049536, 1.3670667538}, {-0.6855727502, 1.6465021616, 1.0593087096}, { 0.0152957411, 0.0638919221, 0.9771215985}}, {x,y,r} = columnize(circles), r2 = sq_power(r,2) atom xMin = min(sq_sub(x,r)), xMax = max(sq_add(x,r)), yMin = min(sq_sub(y,r)), yMax = max(sq_add(y,r)), boxSide = 500, dx = (xMax - xMin) / boxSide, dy = (yMax - yMin) / boxSide, count = 0 sequence cxs = {} for s=1 to boxSide do atom py = yMin + s * dy sequence cy = sq_power(sq_sub(py,y),2) for c=1 to boxSide do if s=1 then atom px = xMin + c * dx cxs = append(cxs,sq_power(sq_sub(px,x),2)) end if sequence cx = cxs[c] for i=1 to length(circles) do if cx[i]+cy[i]<=r2[i] then count+=1 exit end if end for end for end for printf(1,"Approximate area = %.9f\n",{count * dx * dy})
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]
#E
E
def makeQueue := <elib:vat.makeQueue>   def topoSort(data :Map[any, Set[any]]) { # Tables of nodes and edges def forwardEdges := [].asMap().diverge() def reverseCount := [].asMap().diverge()   def init(node) { reverseCount[node] := 0 forwardEdges[node] := [].asSet().diverge() } for node => deps in data { init(node) for dep in deps { init(dep) } }   # 'data' holds the dependencies. Compute the other direction. for node => deps in data { for dep ? (dep != node) in deps { forwardEdges[dep].addElement(node) reverseCount[node] += 1 } }   # Queue containing all elements that have no (initial or remaining) incoming edges def ready := makeQueue() for node => ==0 in reverseCount { ready.enqueue(node) }   var result := []   while (ready.optDequeue() =~ node :notNull) { result with= node for next in forwardEdges[node] { # Decrease count of incoming edges and enqueue if none if ((reverseCount[next] -= 1).isZero()) { ready.enqueue(next) } } forwardEdges.removeKey(node) }   if (forwardEdges.size().aboveZero()) { throw(`Topological sort failed: $forwardEdges remains`) }   return result }
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.
#JavaScript
JavaScript
function tm(d,s,e,i,b,t,... r) { document.write(d, '<br>') if (i<0||i>=t.length) return var re=new RegExp(b,'g') write('*',s,i,t=t.split('')) var p={}; r.forEach(e=>((s,r,w,m,n)=>{p[s+'.'+r]={w,n,m:[0,1,-1][1+'RL'.indexOf(m)]}})(... e.split(/[ .:,]+/))) for (var n=1; s!=e; n+=1) { with (p[s+'.'+t[i]]) t[i]=w,s=n,i+=m if (i==-1) i=0,t.unshift(b) else if (i==t.length) t[i]=b write(n,s,i,t) } document.write('<br>') function write(n, s, i, t) { t = t.join('') t = t.substring(0,i) + '<u>' + t.charAt(i) + '</u>' + t.substr(i+1) document.write((' '+n).slice(-3).replace(/ /g,'&nbsp;'), ': ', s, ' [', t.replace(re,'&nbsp;'), ']', '<br>') } }   tm( 'Unary incrementer', // s e i b t 'a', 'h', 0, 'B', '111', // s.r: w, m, n 'a.1: 1, L, a', 'a.B: 1, S, h' )   tm( 'Unary adder', 1, 0, 0, '0', '1110111', '1.1: 0, R, 2', // write 0 rigth goto 2 '2.1: 1, R, 2', // while (1) rigth '2.0: 1, S, 0' // write 1 stay halt )   tm( 'Three-state busy beaver', 1, 0, 0, '0', '0', '1.0: 1, R, 2', '1.1: 1, R, 0', '2.0: 0, R, 3', '2.1: 1, R, 2', '3.0: 1, L, 3', '3.1: 1, L, 1' )
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).
#Haskell
Haskell
{-# LANGUAGE BangPatterns #-}   import Control.Monad (when) import Data.Bool (bool)   totient :: (Integral a) => a -> a totient n | n == 0 = 1 -- by definition phi(0) = 1 | n < 0 = totient (-n) -- phi(-n) is taken to be equal to phi(n) | otherwise = loop n n 2 -- where loop !m !tot !i | i * i > m = bool tot (tot - (tot `div` m)) (1 < m) | m `mod` i == 0 = loop m_ tot_ i_ | otherwise = loop m tot i_ where i_ | i == 2 = 3 | otherwise = 2 + i m_ = nextM m tot_ = tot - (tot `div` i) nextM !x | x `mod` i == 0 = nextM $ x `div` i | otherwise = x   main :: IO () main = do putStrLn "n\tphi\tprime\n---------------------" let loop !i !count | i >= 10 ^ 6 = return () | otherwise = do let i_ = succ i tot = totient i_ isPrime = tot == pred i_ count_ | isPrime = succ count | otherwise = count when (25 >= i_) $ putStrLn $ show i_ ++ "\t" ++ show tot ++ "\t" ++ show isPrime when (i_ `elem` 25 : [ 10 ^ k | k <- [2 .. 6] ]) $ putStrLn $ "Number of primes up to " ++ show i_ ++ " = " ++ show count_ loop (i + 1) count_ loop 0 0
http://rosettacode.org/wiki/Topswops
Topswops
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is composed of reversing the first   m   cards where   m   is the value of the topmost card. Rounds are repeated until the topmost card is the number   1   and the number of swaps is recorded. For our example the swaps produce: [2, 4, 1, 3] # Initial shuffle [4, 2, 1, 3] [3, 1, 2, 4] [2, 1, 3, 4] [1, 2, 3, 4] For a total of four swaps from the initial ordering to produce the terminating case where   1   is on top. For a particular number   n   of cards,   topswops(n)   is the maximum swaps needed for any starting permutation of the   n   cards. Task The task is to generate and show here a table of   n   vs   topswops(n)   for   n   in the range   1..10   inclusive. Note Topswops   is also known as   Fannkuch   from the German word   Pfannkuchen   meaning   pancake. Related tasks   Number reversal game   Sorting algorithms/Pancake sort
#Picat
Picat
go ?=> member(N,1..10), Perm = 1..N, Rev = Perm.reverse(), Max = 0, while(Perm != Rev) next_permutation(Perm), C = topswops(Perm), if C > Max then Max := C end end, printf("%2d: %2d\n",N,Max), fail, nl. go => true.   topswops([]) = 0 => true. topswops([1]) = 0 => true. topswops([1|_]) = 0 => true. topswops(P) = Count => Len = P.length, Count = 0, while (P[1] > 1) Pos = P[1], P := [P[I] : I in 1..Pos].reverse() ++ [P[I] : I in Pos+1..Len], Count := Count + 1 end.   % Inline next_permutation(Perm) => N = Perm.length, K = N - 1, while (Perm[K] > Perm[K+1], K >= 0) K := K - 1 end, if K > 0 then J = N, while (Perm[K] > Perm[J]) J := J - 1 end, Tmp := Perm[K], Perm[K] := Perm[J], Perm[J] := Tmp, R = N, S = K + 1, while (R > S) Tmp := Perm[R], Perm[R] := Perm[S], Perm[S] := Tmp, R := R - 1, S := S + 1 end end.
http://rosettacode.org/wiki/Topswops
Topswops
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is composed of reversing the first   m   cards where   m   is the value of the topmost card. Rounds are repeated until the topmost card is the number   1   and the number of swaps is recorded. For our example the swaps produce: [2, 4, 1, 3] # Initial shuffle [4, 2, 1, 3] [3, 1, 2, 4] [2, 1, 3, 4] [1, 2, 3, 4] For a total of four swaps from the initial ordering to produce the terminating case where   1   is on top. For a particular number   n   of cards,   topswops(n)   is the maximum swaps needed for any starting permutation of the   n   cards. Task The task is to generate and show here a table of   n   vs   topswops(n)   for   n   in the range   1..10   inclusive. Note Topswops   is also known as   Fannkuch   from the German word   Pfannkuchen   meaning   pancake. Related tasks   Number reversal game   Sorting algorithms/Pancake sort
#PicoLisp
PicoLisp
(de fannkuch (N) (let (Lst (range 1 N) L Lst Max) (recur (L) # Permute (if (cdr L) (do (length L) (recurse (cdr L)) (rot L) ) (zero N) # For each permutation (for (P (copy Lst) (> (car P) 1) (flip P (car P))) (inc 'N) ) (setq Max (max N Max)) ) ) Max ) )   (for I 10 (println I (fannkuch I)) )
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.
#Elena
Elena
import system'math; import extensions;   public program() { console.printLine("Radians:"); console.printLine("sin(π/3) = ",(Pi_value/3).sin()); console.printLine("cos(π/3) = ",(Pi_value/3).cos()); console.printLine("tan(π/3) = ",(Pi_value/3).tan()); console.printLine("arcsin(1/2) = ",0.5r.arcsin()); console.printLine("arccos(1/2) = ",0.5r.arccos()); console.printLine("arctan(1/2) = ",0.5r.arctan()); console.printLine();   console.printLine("Degrees:"); console.printLine("sin(60º) = ",60.0r.Radian.sin()); console.printLine("cos(60º) = ",60.0r.Radian.cos()); console.printLine("tan(60º) = ",60.0r.Radian.tan()); console.printLine("arcsin(1/2) = ",0.5r.arcsin().Degree,"º"); console.printLine("arccos(1/2) = ",0.5r.arccos().Degree,"º"); console.printLine("arctan(1/2) = ",0.5r.arctan().Degree,"º");   console.readChar() }
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).
#Kotlin
Kotlin
// version 1.1.2   fun f(x: Double) = Math.sqrt(Math.abs(x)) + 5.0 * x * x * x   fun main(args: Array<String>) { val da = DoubleArray(11) println("Please enter 11 numbers:") var i = 0 while (i < 11) { print(" ${"%2d".format(i + 1)}: ") val d = readLine()!!.toDoubleOrNull() if (d == null) println("Not a valid number, try again") else da[i++] = d } println("\nThe sequence you just entered in reverse is:") da.reverse() println(da.contentToString()) println("\nProcessing this sequence...") for (j in 0..10) { val v = f(da[j]) print(" ${"%2d".format(j + 1)}: ") if (v > 400.0) println("Overflow!") else println(v) } }
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).
#Ksh
Ksh
  #!/bin/ksh   # Trabb Pardo–Knuth algorithm   # # Variables: # integer NUM_ELE=11 typeset -F FUNC_LIMIT=400   # # Functions: # # # Function _input(_arr) - Ask for user input, build array # function _input { typeset _arr ; nameref _arr="$1" typeset _i ; integer _i   clear ; print "Please input 11 numbers..." for ((_i=1 ; _i<=NUM_ELE ; _i++)); do read REPLY?"${_i}: " [[ $REPLY != {,1}(-)+(\d){,1}(.)*(\d) ]] && ((_i--)) && continue _arr+=( $REPLY ) done }   # # Function _function() - Apply |x|^0.5 + 5x^3 # # note: >400 creates an overflow situation # function _function { typeset _x ; _x=$1   (( _result = sqrt(abs(${_x})) + 5 * _x * _x * _x )) (( _result <= $FUNC_LIMIT )) && echo ${_result} && return 0 return 1 }   ###### # main # ######   typeset -a inputarr _input inputarr integer i printf "%s\n\n" "Evaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :" for (( i=NUM_ELE-1; i>=0; i-- )); do result=$(_function ${inputarr[i]}) if (( $? )); then printf "%s\n" "Overflow" else printf "%s\n" "${result}" fi done
http://rosettacode.org/wiki/Truth_table
Truth table
A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function. Task Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function. (One can assume that the user input is correct). Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function. Either reverse-polish or infix notation expressions are allowed. Related tasks   Boolean values   Ternary logic See also   Wolfram MathWorld entry on truth tables.   some "truth table" examples from Google.
#REXX
REXX
/*REXX program displays a truth table of variables and an expression. Infix notation */ /*─────────────── is supported with one character propositional constants; variables */ /*─────────────── (propositional constants) that are allowed: A──►Z, a──►z except u.*/ /*─────────────── All propositional constants are case insensitive (except lowercase u).*/   parse arg userText /*get optional expression from the CL. */ if userText\='' then do /*Got one? Then show user's stuff. */ call truthTable userText /*display truth table for the userText.*/ exit /*we're finished with the user's text. */ end   call truthTable "G ^ H ; XOR" /*text after ; is echoed to the output.*/ call truthTable "i | j ; OR" call truthTable "G nxor H ; NXOR" call truthTable "k ! t ; NOR" call truthTable "p & q ; AND" call truthTable "e ¡ f ; NAND" call truthTable "S | (T ^ U)" call truthTable "(p=>q) v (q=>r)" call truthTable "A ^ (B ^ (C ^ D))" exit /*quit while we're ahead, by golly. */   /* ↓↓↓ no way, Jose. ↓↓↓ */ /* [↓] shows a 32,768 line truth table*/ call truthTable "A^ (B^ (C^ (D^ (E^ (F^ (G^ (H^ (I^ (J^ (L^ (L^ (M^ (N^O) ))))))))))))" exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ truthTable: procedure; parse arg $ ';' comm 1 $o; $o= strip($o); hdrPCs= $= translate(strip($), '|', "v"); $u= $; upper $u $u= translate($u, '()()()', "[]{}«»"); $$.= 0; PCs= @abc= 'abcdefghijklmnopqrstuvwxyz'; @abcU= @abc; upper @abcU   /* ╔═════════════════════╦════════════════════════════════════════════════════════════╗ ║ ║ bool(bitsA, bitsB, BF) ║ ║ ╟────────────────────────────────────────────────────────────╢ ║ ║ performs the boolean function BF ┌──────┬─────────┐ ║ ║ ║ on the A bitstring │ BF │ common │ ║ ║ ║ with the B bitstring. │ value│ name │ ║ ║ ║ ├──────┼─────────┤ ║ ║ ║ BF must be a one to four bit │ 0000 │boolfalse│ ║ ║ ║ value (from 0000 ──► 1111), │ 0001 │ and │ ║ ║ This boxed table ║ leading zeroes can be omitted. │ 0010 │ NaIMPb │ ║ ║ was re─constructed ║ │ 0011 │ boolB │ ║ ║ from an old IBM ║ BF may have multiple values (one │ 0100 │ NbIMPa │ ║ ║ publicastion: ║ for each pair of bitstrings): │ 0101 │ boolA │ ║ ║ ║ │ 0110 │ xor │ ║ ║ "PL/I Language ║ ┌──────┬──────┬───────────────┐ │ 0111 │ or │ ║ ║ Specifications" ║ │ Abit │ Bbit │ returns │ │ 1000 │ nor │ ║ ║ ║ ├──────┼──────┼───────────────┤ │ 1001 │ nxor │ ║ ║ ║ │ 0 │ 0 │ 1st bit in BF │ │ 1010 │ notB │ ║ ║ ║ │ 0 │ 1 │ 2nd bit in BF │ │ 1011 │ bIMPa │ ║ ║ ─── March 1969. ║ │ 1 │ 0 │ 3rd bit in BF │ │ 1100 │ notA │ ║ ║ ║ │ 1 │ 1 │ 4th bit in BF │ │ 1101 │ aIMPb │ ║ ║ ║ └──────┴──────┴───────────────┘ │ 1110 │ nand │ ║ ║ ║ │ 1111 │booltrue │ ║ ║ ║ ┌──┴──────┴─────────┤ ║ ║ ║ │ A 0101 │ ║ ║ ║ │ B 0011 │ ║ ║ ║ └───────────────────┘ ║ ╚═════════════════════╩════════════════════════════════════════════════════════════╝ */   @= 'ff'x /* [↓] ───── infix operators (0──►15) */ op.= /*Note: a single quote (') wasn't */ /* implemented for negation.*/ op.0 = 'false boolFALSE' /*unconditionally FALSE */ op.1 = '& and *' /* AND, conjunction */ op.2 = 'naimpb NaIMPb' /*not A implies B */ op.3 = 'boolb boolB' /*B (value of) */ op.4 = 'nbimpa NbIMPa' /*not B implies A */ op.5 = 'boola boolA' /*A (value of) */ op.6 = '&& xor % ^' /* XOR, exclusive OR */ op.7 = '| or + v' /* OR, disjunction */ op.8 = 'nor nor ! ↓' /* NOR, not OR, Pierce operator */ op.9 = 'xnor xnor nxor' /*NXOR, not exclusive OR, not XOR */ op.10= 'notb notB' /*not B (value of) */ op.11= 'bimpa bIMPa' /* B implies A */ op.12= 'nota notA' /*not A (value of) */ op.13= 'aimpb aIMPb' /* A implies B */ op.14= 'nand nand ¡ ↑' /*NAND, not AND, Sheffer operator */ op.15= 'true boolTRUE' /*unconditionally TRUE */ /*alphabetic names that need changing. */ op.16= '\ NOT ~ ─ . ¬' /* NOT, negation */ op.17= '> GT' /*conditional */ op.18= '>= GE ─> => ──> ==>' "1a"x /*conditional; (see note below.)──┐*/ op.19= '< LT' /*conditional │*/ op.20= '<= LE <─ <= <── <==' /*conditional │*/ op.21= '\= NE ~= ─= .= ¬=' /*conditional │*/ op.22= '= EQ EQUAL EQUALS =' "1b"x /*bi─conditional; (see note below.)┐ │*/ op.23= '0 boolTRUE' /*TRUEness │ │*/ op.24= '1 boolFALSE' /*FALSEness ↓ ↓*/ /* [↑] glphys '1a'x and "1b"x can't*/ /* displayed under most DOS' & such*/ do jj=0 while op.jj\=='' | jj<16 /*change opers ──► into what REXX likes*/ new= word(op.jj, 1) /*obtain the 1st token of infex table.*/ /* [↓] process the rest of the tokens.*/ do kk=2 to words(op.jj) /*handle each of the tokens separately.*/ _=word(op.jj, kk); upper _ /*obtain another token from infix table*/ if wordpos(_, $u)==0 then iterate /*no such animal in this string. */ if datatype(new, 'm') then new!= @ /*it needs to be transcribed*/ else new!= new /*it doesn't need " " " */ $u= changestr(_, $u, new!) /*transcribe the function (maybe). */ if new!==@ then $u= changeFunc($u,@,new) /*use the internal boolean name. */ end /*kk*/ end /*jj*/   $u=translate($u, '()', "{}") /*finish cleaning up the transcribing. */   do jj=1 for length(@abcU) /*see what variables are being used. */ _= substr(@abcU, jj, 1) /*use the available upercase aLphabet. */ if pos(_,$u) == 0 then iterate /*Found one? No, then keep looking. */ $$.jj= 1 /*found: set upper bound for it. */ PCs= PCs _ /*also, add to propositional constants.*/ hdrPCs=hdrPCS center(_,length('false')) /*build a PC header for transcribing. */ end /*jj*/   ptr= '_────►_' /*a (text) pointer for the truth table.*/ $u= PCs '('$u")" /*separate the PCs from expression. */ hdrPCs= substr(hdrPCs, 2) /*create a header for the PCs. */ say hdrPCs left('', length(ptr) - 1) $o /*display PC header and expression. */ say copies('───── ', words(PCs)) left('', length(ptr) -2) copies('─', length($o)) /*Note: "true"s: are right─justified.*/ do a=0 to $$.1 do b=0 to $$.2 do c=0 to $$.3 do d=0 to $$.4 do e=0 to $$.5 do f=0 to $$.6 do g=0 to $$.7 do h=0 to $$.8 do i=0 to $$.9 do j=0 to $$.10 do k=0 to $$.11 do l=0 to $$.12 do m=0 to $$.13 do n=0 to $$.14 do o=0 to $$.15 do p=0 to $$.16 do q=0 to $$.17 do r=0 to $$.18 do s=0 to $$.19 do t=0 to $$.20 do u=0 to $$.21 do !=0 to $$.22 do w=0 to $$.23 do x=0 to $$.24 do y=0 to $$.25 do z=0 to $$.26; interpret '_=' $u /*evaluate truth T.*/ _= changestr(1, _, '_true') /*convert 1──►_true*/ _= changestr(0, _, 'false') /*convert 0──►false*/ _= insert(ptr, _, wordindex(_, words(_) ) - 1) say translate(_, , '_') /*display truth tab*/ end /*z*/ end /*y*/ end /*x*/ end /*w*/ end /*v*/ end /*u*/ end /*t*/ end /*s*/ end /*r*/ end /*q*/ end /*p*/ end /*o*/ end /*n*/ end /*m*/ end /*l*/ end /*k*/ end /*j*/ end /*i*/ end /*h*/ end /*g*/ end /*f*/ end /*e*/ end /*d*/ end /*c*/ end /*b*/ end /*a*/ say; say return /*──────────────────────────────────────────────────────────────────────────────────────*/ scan: procedure; parse arg x,at; L= length(x); t=L; Lp=0; apost=0; quote=0 if at<0 then do; t=1; x= translate(x, '()', ")(") end /* [↓] get 1 or 2 chars at location J*/   do j=abs(at) to t by sign(at); _=substr(x, j ,1); __=substr(x, j, 2) if quote then do; if _\=='"' then iterate if __=='""' then do; j= j+1; iterate; end quote=0; iterate end if apost then do; if _\=="'" then iterate if __=="''" then do; j= j+1; iterate; end apost=0; iterate end if _== '"' then do; quote=1; iterate; end if _== "'" then do; apost=1; iterate; end if _== ' ' then iterate if _== '(' then do; Lp= Lp+1; iterate; end if Lp\==0 then do; if _==')' then Lp= Lp-1; iterate; end if datatype(_, 'U') then return j - (at<0) if at<0 then return j + 1 /*is _ uppercase ? */ end /*j*/   return min(j, L) /*──────────────────────────────────────────────────────────────────────────────────────*/ changeFunc: procedure; parse arg z, fC, newF ; funcPos= 0   do forever funcPos= pos(fC, z, funcPos + 1); if funcPos==0 then return z origPos= funcPos z= changestr(fC, z, ",'"newF"',") /*arg 3 ≡ ",'" || newF || "-'," */ funcPos= funcPos + length(newF) + 4 where= scan(z, funcPos)  ; z= insert( '}', z, where) where= scan(z, 1 - origPos)  ; z= insert('bool{', z, where) end /*forever*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ bool: procedure; arg a,?,b /* ◄─── ARG uppercases all args.*/   select /*SELECT chooses which function.*/ /*0*/ when ? == 'FALSE' then return 0 /*1*/ when ? == 'AND' then return a & b /*2*/ when ? == 'NAIMPB' then return \ (\a & \b) /*3*/ when ? == 'BOOLB' then return b /*4*/ when ? == 'NBIMPA' then return \ (\b & \a) /*5*/ when ? == 'BOOLA' then return a /*6*/ when ? == 'XOR' then return a && b /*7*/ when ? == 'OR' then return a | b /*8*/ when ? == 'NOR' then return \ (a | b) /*9*/ when ? == 'XNOR' then return \ (a && b) /*a*/ when ? == 'NOTB' then return \ b /*b*/ when ? == 'BIMPA' then return \ (b & \a) /*c*/ when ? == 'NOTA' then return \ a /*d*/ when ? == 'AIMPB' then return \ (a & \b) /*e*/ when ? == 'NAND' then return \ (a & b) /*f*/ when ? == 'TRUE' then return 1 otherwise return -13 end /*select*/ /* [↑] error, unknown function.*/
http://rosettacode.org/wiki/Ulam_spiral_(for_primes)
Ulam spiral (for primes)
An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is shown with sequential integers,   starting at   1. In an Ulam spiral of primes, only the primes are shown (usually indicated by some glyph such as a dot or asterisk),   and all non-primes as shown as a blank   (or some other whitespace). Of course, the grid and border are not to be displayed (but they are displayed here when using these Wiki HTML tables). Normally, the spiral starts in the "center",   and the   2nd   number is to the viewer's right and the number spiral starts from there in a counter-clockwise direction. There are other geometric shapes that are used as well, including clock-wise spirals. Also, some spirals (for the   2nd   number)   is viewed upwards from the   1st   number instead of to the right, but that is just a matter of orientation. Sometimes, the starting number can be specified to show more visual striking patterns (of prime densities). [A larger than necessary grid (numbers wise) is shown here to illustrate the pattern of numbers on the diagonals   (which may be used by the method to orientate the direction of spiral-construction algorithm within the example computer programs)]. Then, in the next phase in the transformation of the Ulam prime spiral,   the non-primes are translated to blanks. In the orange grid below,   the primes are left intact,   and all non-primes are changed to blanks. Then, in the final transformation of the Ulam spiral (the yellow grid),   translate the primes to a glyph such as a   •   or some other suitable glyph. 65 64 63 62 61 60 59 58 57 66 37 36 35 34 33 32 31 56 67 38 17 16 15 14 13 30 55 68 39 18 5 4 3 12 29 54 69 40 19 6 1 2 11 28 53 70 41 20 7 8 9 10 27 52 71 42 21 22 23 24 25 26 51 72 43 44 45 46 47 48 49 50 73 74 75 76 77 78 79 80 81 61 59 37 31 67 17 13 5 3 29 19 2 11 53 41 7 71 23 43 47 73 79 • • • • • • • • • • • • • • • • • • • • • • The Ulam spiral becomes more visually obvious as the grid increases in size. Task For any sized   N × N   grid,   construct and show an Ulam spiral (counter-clockwise) of primes starting at some specified initial number   (the default would be 1),   with some suitably   dotty   (glyph) representation to indicate primes,   and the absence of dots to indicate non-primes. You should demonstrate the generator by showing at Ulam prime spiral large enough to (almost) fill your terminal screen. Related tasks   Spiral matrix   Zig-zag matrix   Identity matrix   Sequence of primes by Trial Division See also Wikipedia entry:   Ulam spiral MathWorld™ entry:   Prime Spiral
#Rust
Rust
use std::fmt;   enum Direction { RIGHT, UP, LEFT, DOWN } use ulam::Direction::*;   /// Indicates whether an integer is a prime number or not. fn is_prime(a: u32) -> bool { match a { 2 => true, x if x <= 1 || x % 2 == 0 => false, _ => { let max = f64::sqrt(a as f64) as u32; let mut x = 3; while x <= max { if a % x == 0 { return false; } x += 2; } true } } }   pub struct Ulam { u : Vec<Vec<String>> }   impl Ulam { /// Generates one `Ulam` object. pub fn new(n: u32, s: u32, c: char) -> Ulam { let mut spiral = vec![vec![String::new(); n as usize]; n as usize]; let mut dir = RIGHT; let mut y = (n / 2) as usize; let mut x = if n % 2 == 0 { y - 1 } else { y }; // shift left for even n's for j in s..n * n + s { spiral[y][x] = if is_prime(j) { if c == '\0' { format!("{:4}", j) } else { format!(" {} ", c) } } else { String::from(" ---") };   match dir { RIGHT => if x as u32 <= n - 1 && spiral[y - 1][x].is_empty() && j > s { dir = UP; }, UP => if spiral[y][x - 1].is_empty() { dir = LEFT; }, LEFT => if x == 0 || spiral[y + 1][x].is_empty() { dir = DOWN; }, DOWN => if spiral[y][x + 1].is_empty() { dir = RIGHT; } };   match dir { RIGHT => x += 1, UP => y -= 1, LEFT => x -= 1, DOWN => y += 1 }; } Ulam { u: spiral } } }   impl fmt::Display for Ulam { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for row in &self.u { writeln!(f, "{}", format!("{:?}", row).replace("\"", "").replace(", ", "")); }; writeln!(f, "") } }
http://rosettacode.org/wiki/Ulam_spiral_(for_primes)
Ulam spiral (for primes)
An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is shown with sequential integers,   starting at   1. In an Ulam spiral of primes, only the primes are shown (usually indicated by some glyph such as a dot or asterisk),   and all non-primes as shown as a blank   (or some other whitespace). Of course, the grid and border are not to be displayed (but they are displayed here when using these Wiki HTML tables). Normally, the spiral starts in the "center",   and the   2nd   number is to the viewer's right and the number spiral starts from there in a counter-clockwise direction. There are other geometric shapes that are used as well, including clock-wise spirals. Also, some spirals (for the   2nd   number)   is viewed upwards from the   1st   number instead of to the right, but that is just a matter of orientation. Sometimes, the starting number can be specified to show more visual striking patterns (of prime densities). [A larger than necessary grid (numbers wise) is shown here to illustrate the pattern of numbers on the diagonals   (which may be used by the method to orientate the direction of spiral-construction algorithm within the example computer programs)]. Then, in the next phase in the transformation of the Ulam prime spiral,   the non-primes are translated to blanks. In the orange grid below,   the primes are left intact,   and all non-primes are changed to blanks. Then, in the final transformation of the Ulam spiral (the yellow grid),   translate the primes to a glyph such as a   •   or some other suitable glyph. 65 64 63 62 61 60 59 58 57 66 37 36 35 34 33 32 31 56 67 38 17 16 15 14 13 30 55 68 39 18 5 4 3 12 29 54 69 40 19 6 1 2 11 28 53 70 41 20 7 8 9 10 27 52 71 42 21 22 23 24 25 26 51 72 43 44 45 46 47 48 49 50 73 74 75 76 77 78 79 80 81 61 59 37 31 67 17 13 5 3 29 19 2 11 53 41 7 71 23 43 47 73 79 • • • • • • • • • • • • • • • • • • • • • • The Ulam spiral becomes more visually obvious as the grid increases in size. Task For any sized   N × N   grid,   construct and show an Ulam spiral (counter-clockwise) of primes starting at some specified initial number   (the default would be 1),   with some suitably   dotty   (glyph) representation to indicate primes,   and the absence of dots to indicate non-primes. You should demonstrate the generator by showing at Ulam prime spiral large enough to (almost) fill your terminal screen. Related tasks   Spiral matrix   Zig-zag matrix   Identity matrix   Sequence of primes by Trial Division See also Wikipedia entry:   Ulam spiral MathWorld™ entry:   Prime Spiral
#Scala
Scala
object Ulam extends App { generate(9)() generate(9)('*')   private object Direction extends Enumeration { val RIGHT, UP, LEFT, DOWN = Value }   private def generate(n: Int, i: Int = 1)(c: Char = 0) { assert(n > 1, "n > 1") val s = new Array[Array[String]](n).transform {_ => new Array[String](n) }   import Direction._ var dir = RIGHT var y = n / 2 var x = if (n % 2 == 0) y - 1 else y // shift left for even n's for (j <- i to n * n - 1 + i) { s(y)(x) = if (isPrime(j)) if (c == 0) "%4d".format(j) else s" $c " else " ---"   dir match { case RIGHT => if (x <= n - 1 && s(y - 1)(x) == null && j > i) dir = UP case UP => if (s(y)(x - 1) == null) dir = LEFT case LEFT => if (x == 0 || s(y + 1)(x) == null) dir = DOWN case DOWN => if (s(y)(x + 1) == null) dir = RIGHT }   dir match { case RIGHT => x += 1 case UP => y -= 1 case LEFT => x -= 1 case DOWN => y += 1 } } println("[" + s.map(_.mkString("")).reduceLeft(_ + "]\n[" + _) + "]\n") }   private def isPrime(a: Int): Boolean = { if (a == 2) return true if (a <= 1 || a % 2 == 0) return false val max = Math.sqrt(a.toDouble).toInt for (n <- 3 to max by 2) if (a % n == 0) return false true } }
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.]
#MATLAB
MATLAB
function largestTruncatablePrimes(boundary)   %Helper function for checking if a prime is left of right truncatable function [leftTruncatable,rightTruncatable] = isTruncatable(prime,checkLeftTruncatable,checkRightTruncatable)   numDigits = ceil(log10(prime)); %calculate the number of digits in the prime less one powersOfTen = 10.^(0:numDigits); %cache the needed powers of ten   leftTruncated = mod(prime,powersOfTen); %generate a list of numbers by repeatedly left truncating the prime   %leading zeros will cause duplicate entries thus it is possible to %detect leading zeros if we rotate the list to the left or right %and check for any equivalences with the original list hasLeadingZeros = any( circshift(leftTruncated,[0 1]) == leftTruncated );   if( hasLeadingZeros || not(checkLeftTruncatable) ) leftTruncatable = false; else %check if all of the left truncated numbers are prime leftTruncatable = all(isprime(leftTruncated(2:end))); end   if( checkRightTruncatable ) rightTruncated = (prime - leftTruncated) ./ powersOfTen; %generate a list of right truncated numbers rightTruncatable = all(isprime(rightTruncated(1:end-1))); %check if all the right truncated numbers are prime else rightTruncatable = false; end   end %isTruncatable()   nums = primes(boundary); %generate all primes <= boundary   %Flags that indicate if the largest left or right truncatable prime has not %been found leftTruncateNotFound = true; rightTruncateNotFound = true;   for prime = nums(end:-1:1) %Search through primes in reverse order   %Get if the prime is left and/or right truncatable, ignoring %checking for right truncatable if it has already been found [leftTruncatable,rightTruncatable] = isTruncatable(prime,leftTruncateNotFound,rightTruncateNotFound);   if( leftTruncateNotFound && leftTruncatable ) %print out largest left truncatable prime display([num2str(prime) ' is the largest left truncatable prime <= ' num2str(boundary) '.']); leftTruncateNotFound = false; end   if( rightTruncateNotFound && rightTruncatable ) %print out largest right truncatable prime display([num2str(prime) ' is the largest right truncatable prime <= ' num2str(boundary) '.']); rightTruncateNotFound = false; end   %Terminate loop when the largest left and right truncatable primes have %been found if( not(leftTruncateNotFound || rightTruncateNotFound) ) break; end end end  
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.
#Ceylon
Ceylon
import ceylon.collection { ArrayList }   shared void run() {   class Node(label, left = null, right = null) { shared Integer label; shared Node? left; shared Node? right; string => label.string; }   void preorder(Node node) { process.write(node.string + " "); if(exists left = node.left) { preorder(left); } if(exists right = node.right) { preorder(right); } }   void inorder(Node node) { if(exists left = node.left) { inorder(left); } process.write(node.string + " "); if(exists right = node.right) { inorder(right); } }   void postorder(Node node) { if(exists left = node.left) { postorder(left); } if(exists right = node.right) { postorder(right); } process.write(node.string + " "); }   void levelOrder(Node node) { value nodes = ArrayList<Node> {node}; while(exists current = nodes.accept()) { process.write(current.string + " "); if(exists left = current.left) { nodes.offer(left); } if(exists right = current.right) { nodes.offer(right); } } }   value tree = Node { label = 1; left = Node { label = 2; left = Node { label = 4; left = Node { label = 7; }; }; right = Node { label = 5; }; }; right = Node { label = 3; left = Node { label = 6; left = Node { label = 8; }; right = Node { label = 9; }; }; }; };   process.write("preorder: "); preorder(tree); print(""); process.write("inorder: "); inorder(tree); print(""); process.write("postorder: "); postorder(tree); print(""); process.write("levelorder: "); levelOrder(tree); print(""); }
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
#Amazing_Hopper
Amazing Hopper
  #include <hopper.h>   #proto splitdate(_DATETIME_) #proto splitnumber(_N_) #proto split(_S_,_T_)   main:   s="this string will be separated into parts with space token separator"   aS=0,let( aS :=_split(s," "))   {","}toksep // set a new token separator {"String: ",s} {"\nArray:\n",aS}, {"\nSize="}size(aS),println // "size" return an array: {dims,#rows,#cols,#pages}   {"\nOriginal number: ",-125.489922},println w=0,let(w:=_split number(-125.489922) ) {"Integer part: "}[1]get(w) // get first element from array "w" {"\nDecimal part: "}[2]get(w),println // get second element from array "w"   {"\nDate by DATENOW(TODAY) macro: "},print dt=0, let( dt :=_splitdate(datenow(TODAY);!puts)) // "!" keep first element from stack {"\nDate: "}[1]get(dt) {"\nTime: "}[2]get(dt),println   exit(0)   .locals splitdate(_DATETIME_) _SEP_=0,gettoksep,mov(_SEP_) // "gettoksep" return actual token separator {","}toksep, // set a new token separator _NEWARRAY_={} {1},$( _DATETIME_ ), {2},$( _DATETIME_ ),pushall(_NEWARRAY_) {_SEP_}toksep // restore ols token separator {_NEWARRAY_} back   splitnumber(_X_) part_int=0,part_dec=0, {_X_},!trunc,mov(part_int), minus(part_int), !sign,mul xtostr,mov(part_dec), part_dec+=2, // "part_dec+=2", delete "0." from "part_dec" {part_dec}xtonum,mov(part_dec) _NEWARRAY_={},{part_int,part_dec},pushall(_NEWARRAY_) {_NEWARRAY_} back   split(_S_,_T_) _NEWARRAY_={},_VAR1_=0,_SEP_=0,gettoksep,mov(_SEP_) {_T_}toksep,totaltoken(_S_), mov(_VAR1_), // for total tokens _VAR2_=1, // for real position of tokens into the string ___SPLIT_ITER: {_VAR2_}$( _S_ ),push(_NEWARRAY_) ++_VAR2_,--_VAR1_ { _VAR1_ },jnz(___SPLIT_ITER) // jump to "___SPLIT_ITER" if "_VAR1_" is not zero. clear(_VAR2_),clear(_VAR1_) {_SEP_}toksep {_NEWARRAY_} back    
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
#APL
APL
'.',⍨¨ ','(≠⊆⊢)'abc,123,X' ⍝ [1] Do the split: ','(≠⊆⊢)'abc,123,X'; [2] append the periods: '.',⍨¨ abc. 123. X. ⍝ 3 strings (char vectors), each with a period at the end.  
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.
#8051_Assembly
8051 Assembly
TC EQU 8 ; number of counter registers TSTART EQU 08h ; first register of timer counter TEND EQU TSTART + TC - 1 ; end register of timer counter ; Note: The multi-byte value is stored in Big-endian   ; Some timer reloads _6H EQU 085h ; 6MHz _6L EQU 0edh _12H EQU 00bh ; 12MHz _12L EQU 0dbh _110592H EQU 01eh ; 11.0592MHz _110592L EQU 0ffh   ; How to calculate timer reload (e.g. for 11.0592MHz): ; Note: 1 machine cycle takes 12 oscillator periods ; 11.0592MHz / 12 * 0.0625 seconds = 57,600 cycles = e100h ; ffffh - e100h = NOT e100h = 1effh   ; assuming a 11.0592MHz crystal TIMERH EQU _110592H TIMERL EQU _110592L   ;; some timer macros (using timer0) start_timer macro setb tr0 endm stop_timer macro clr tr0 endm reset_timer macro mov tl0, #TIMERL mov th0, #TIMERH endm   increment_counter macro ;; increment counter (multi-byte increment) push psw push acc push 0 ; r0 mov r0, #TEND+1 setb c inc_reg: dec r0 clr a addc a, @r0 mov @r0, a jnc inc_reg_ ; end prematurally if the higher bytes are unchanged cjne r0, #TSTART, inc_reg inc_reg_: ; if the carry is set here then the multi byte value has overflowed pop 0 pop acc pop psw endm   ORG RESET jmp init ORG TIMER0 jmp timer_0   timer_0: ; interrupt every 6.25ms stop_timer ; we only want to time the function reset_timer increment_counter start_timer reti   init: mov sp, #TEND setb ea ; enable interrupts setb et0 ; enable timer0 interrupt mov tmod, #01h ; timer0 16-bit mode reset_timer   ; reset timer counter registers clr a mov r0, #TSTART clear: mov @r0, a inc r0 cjne r0, #TEND, clear   start_timer call function ; the function to time stop_timer   ; at this point the registers from TSTART ; through TEND indicate the current time ; multiplying the 8/16/24/etc length value by 0.0625 (2^-4) gives ; the elapsed number of seconds ; e.g. if the three registers were 02a0f2h then the elapsed time is: ; 02a0f2h = 172,274 and 172,274 * 0.0625 = 10,767.125 seconds ; ; Or alternatively: ; (high byte) 02h = 2 and 2 * 2^(16-4) = 8192 ; (mid byte) a0h = 160 and 160 * 2^(8-4) = 2560 ; (low byte) f2h = 242 and 242 * 2^(0-4) = 15.125 ; 8192 + 2560 + 15.125 = 10,767.125 seconds   jmp $   function: ; do whatever here ret   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
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   typedef struct { const char *name, *id, *dept; int sal; } person;   person ppl[] = { {"Tyler Bennett", "E10297", "D101", 32000}, {"John Rappl", "E21437", "D050", 47000}, {"George Woltman", "E00127", "D101", 53500}, {"Adam Smith", "E63535", "D202", 18000}, {"Claire Buckman", "E39876", "D202", 27800}, {"David McClellan", "E04242", "D101", 41500}, {"Rich Holcomb", "E01234", "D202", 49500}, {"Nathan Adams", "E41298", "D050", 21900}, {"Richard Potter", "E43128", "D101", 15900}, {"David Motsinger", "E27002", "D202", 19250}, {"Tim Sampair", "E03033", "D101", 27000}, {"Kim Arlich", "E10001", "D190", 57000}, {"Timothy Grove", "E16398", "D190", 29900}, };   int pcmp(const void *a, const void *b) { const person *aa = a, *bb = b; int x = strcmp(aa->dept, bb->dept); if (x) return x; return aa->sal > bb->sal ? -1 : aa->sal < bb->sal; }   #define N sizeof(ppl)/sizeof(person) void top(int n) { int i, rank; qsort(ppl, N, sizeof(person), pcmp);   for (i = rank = 0; i < N; i++) { if (i && strcmp(ppl[i].dept, ppl[i - 1].dept)) { rank = 0; printf("\n"); }   if (rank++ < n) printf("%s %d: %s\n", ppl[i].dept, ppl[i].sal, ppl[i].name); } }   int main() { top(2); return 0; }
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.
#11l
11l
UInt32 seed = 0 F nonrandom_choice(lst)  :seed = 1664525 * :seed + 1013904223 R lst[:seed % UInt32(lst.len)]   V board = Array(‘123456789’) V 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])   F printboard() print([0, 3, 6].map(x -> (:board[x .+ 3]).join(‘ ’)).join("\n"))   F score(board = board) -> (Char, [Int])? L(w) :wins V b = board[w[0]] I b C ‘XO’ & all(w.map(i -> @board[i] == @b)) R (b, w.map(i -> i + 1)) R N   F finished() R all(:board.map(b -> b C ‘XO’))   F space(board = board) R board.filter(b -> b !C ‘XO’)   F my_turn(xo, &board) V options = space() V choice = nonrandom_choice(options) board[Int(choice) - 1] = xo R choice   F my_better_turn(xo, &board) ‘Will return a next winning move or block your winning move if possible’ V ox = I xo == ‘X’ {Char(‘O’)} E Char(‘X’) Int? oneblock V options = space(board).map(s -> Int(s) - 1) Int choice L(chc) options V brd = copy(board) brd[chc] = xo I score(brd) != N choice = chc L.break I oneblock == N brd[chc] = ox I score(brd) != N oneblock = chc L.was_no_break choice = oneblock ? nonrandom_choice(options) board[choice] = xo R choice + 1   F your_turn(xo, &board) V options = space() L V choice = input("\nPut your #. in any of these positions: #. ".format(xo, options.join(‘’))).trim((‘ ’, "\t", "\r", "\n")) I choice C options board[Int(choice) - 1] = xo R choice print(‘Whoops I don't understand the input’)   F me(xo = Char(‘X’)) printboard() print("\nI go at "my_better_turn(xo, &:board)) R score()   F you(xo = Char(‘O’)) printboard() print("\nYou went at "my_turn(xo, &:board)) R score()   L !finished() (Char, [Int])? s = me(Char(‘X’)) I s != N printboard() print("\n#. wins along #.".format(s[0], s[1])) L.break I !finished() s = you(Char(‘O’)) I s != N printboard() print("\n#. wins along #.".format(s[0], s[1])) L.break L.was_no_break print("\nA draw")
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#ARM_Assembly
ARM Assembly
.text .global _start _start: mov r0,#4 @ 4 disks, mov r1,#1 @ from pole 1, mov r2,#2 @ via pole 2, mov r3,#3 @ to pole 3. bl move mov r0,#0 @ Exit to Linux afterwards mov r7,#1 swi #0 @@@ Move r0 disks from r1 via r2 to r3 move: subs r0,r0,#1 @ One fewer disk in next iteration beq show @ If last disk, just print move push {r0-r3,lr} @ Save all the registers incl. link register eor r2,r2,r3 @ Swap the 'to' and 'via' registers eor r3,r2,r3 eor r2,r2,r3 bl move @ Recursive call pop {r0-r3} @ Restore all the registers except LR bl show @ Show current move eor r1,r1,r3 @ Swap the 'to' and 'via' registers eor r3,r1,r3 eor r1,r1,r3 pop {lr} @ Restore link register b move @ Tail call @@@ Show move show: push {r0-r3,lr} @ Save all the registers add r1,r1,#'0 @ Write the source pole ldr lr,=spole strb r1,[lr] add r3,r3,#'0 @ Write the destination pole ldr lr,=dpole strb r3,[lr] mov r0,#1 @ 1 = stdout ldr r1,=moves @ Pointer to string ldr r2,=mlen @ Length of string mov r7,#4 @ 4 = Linux write syscall swi #0 @ Print the move pop {r0-r3,pc} @ Restore all the registers and return .data moves: .ascii "Move disk from pole " spole: .ascii "* to pole " dpole: .ascii "*\n" mlen = . - moves
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
#Cowgol
Cowgol
include "cowgol.coh";   # Find the N'th digit in the Thue-Morse sequence sub tm(n: uint32): (d: uint8) is var n2 := n; while n2 != 0 loop n2 := n2 >> 1; n := n ^ n2; end loop; d := (n & 1) as uint8; end sub;   # Print the first 64 digits var i: uint32 := 0; while i < 64 loop print_char('0' + tm(i)); i := i + 1; end loop; print_nl();
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
#Crystal
Crystal
steps = 6   tmp = "" s1 = "0" s2 = "1"   steps.times { tmp = s1 s1 += s2 s2 += tmp }   puts s1
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm
Tonelli-Shanks algorithm
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computational number theory, the Tonelli–Shanks algorithm is a technique for solving for x in a congruence of the form: x2 ≡ n (mod p) where n is an integer which is a quadratic residue (mod p), p is an odd prime, and x,n ∈ Fp where Fp = {0, 1, ..., p - 1}. It is used in cryptography techniques. To apply the algorithm, we need the Legendre symbol: The Legendre symbol (a | p) denotes the value of a(p-1)/2 (mod p). (a | p) ≡ 1    if a is a square (mod p) (a | p) ≡ -1    if a is not a square (mod p) (a | p) ≡ 0    if a ≡ 0 (mod p) Algorithm pseudo-code All ≡ are taken to mean (mod p) unless stated otherwise. Input: p an odd prime, and an integer n . Step 0: Check that n is indeed a square: (n | p) must be ≡ 1 . Step 1: By factoring out powers of 2 from p - 1, find q and s such that p - 1 = q2s with q odd . If p ≡ 3 (mod 4) (i.e. s = 1), output the two solutions r ≡ ± n(p+1)/4 . Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq . Step 3: Set r ≡ n(q+1)/2, t ≡ nq, m = s . Step 4: Loop the following: If t ≡ 1, output r and p - r . Otherwise find, by repeated squaring, the lowest i, 0 < i < m , such that t2i ≡ 1 . Let b ≡ c2(m - i - 1), and set r ≡ rb, t ≡ tb2, c ≡ b2 and m = i . Task Implement the above algorithm. Find solutions (if any) for n = 10 p = 13 n = 56 p = 101 n = 1030 p = 10009 n = 1032 p = 10009 n = 44402 p = 100049 Extra credit n = 665820697 p = 1000000009 n = 881398088036 p = 1000000000039 n = 41660815127637347468140745042827704103445750172002 p = 10^50 + 577 See also Modular exponentiation Cipolla's algorithm
#Java
Java
import java.math.BigInteger; import java.util.List; import java.util.Map; import java.util.function.BiFunction; import java.util.function.Function;   public class TonelliShanks { private static final BigInteger ZERO = BigInteger.ZERO; private static final BigInteger ONE = BigInteger.ONE; private static final BigInteger TEN = BigInteger.TEN; private static final BigInteger TWO = BigInteger.valueOf(2); private static final BigInteger FOUR = BigInteger.valueOf(4);   private static class Solution { private BigInteger root1; private BigInteger root2; private boolean exists;   Solution(BigInteger root1, BigInteger root2, boolean exists) { this.root1 = root1; this.root2 = root2; this.exists = exists; } }   private static Solution ts(Long n, Long p) { return ts(BigInteger.valueOf(n), BigInteger.valueOf(p)); }   private static Solution ts(BigInteger n, BigInteger p) { BiFunction<BigInteger, BigInteger, BigInteger> powModP = (BigInteger a, BigInteger e) -> a.modPow(e, p); Function<BigInteger, BigInteger> ls = (BigInteger a) -> powModP.apply(a, p.subtract(ONE).divide(TWO));   if (!ls.apply(n).equals(ONE)) return new Solution(ZERO, ZERO, false);   BigInteger q = p.subtract(ONE); BigInteger ss = ZERO; while (q.and(ONE).equals(ZERO)) { ss = ss.add(ONE); q = q.shiftRight(1); }   if (ss.equals(ONE)) { BigInteger r1 = powModP.apply(n, p.add(ONE).divide(FOUR)); return new Solution(r1, p.subtract(r1), true); }   BigInteger z = TWO; while (!ls.apply(z).equals(p.subtract(ONE))) z = z.add(ONE); BigInteger c = powModP.apply(z, q); BigInteger r = powModP.apply(n, q.add(ONE).divide(TWO)); BigInteger t = powModP.apply(n, q); BigInteger m = ss;   while (true) { if (t.equals(ONE)) return new Solution(r, p.subtract(r), true); BigInteger i = ZERO; BigInteger zz = t; while (!zz.equals(BigInteger.ONE) && i.compareTo(m.subtract(ONE)) < 0) { zz = zz.multiply(zz).mod(p); i = i.add(ONE); } BigInteger b = c; BigInteger e = m.subtract(i).subtract(ONE); while (e.compareTo(ZERO) > 0) { b = b.multiply(b).mod(p); e = e.subtract(ONE); } r = r.multiply(b).mod(p); c = b.multiply(b).mod(p); t = t.multiply(c).mod(p); m = i; } }   public static void main(String[] args) { List<Map.Entry<Long, Long>> pairs = List.of( Map.entry(10L, 13L), Map.entry(56L, 101L), Map.entry(1030L, 10009L), Map.entry(1032L, 10009L), Map.entry(44402L, 100049L), Map.entry(665820697L, 1000000009L), Map.entry(881398088036L, 1000000000039L) );   for (Map.Entry<Long, Long> pair : pairs) { Solution sol = ts(pair.getKey(), pair.getValue()); System.out.printf("n = %s\n", pair.getKey()); System.out.printf("p = %s\n", pair.getValue()); if (sol.exists) { System.out.printf("root1 = %s\n", sol.root1); System.out.printf("root2 = %s\n", sol.root2); } else { System.out.println("No solution exists"); } System.out.println(); }   BigInteger bn = new BigInteger("41660815127637347468140745042827704103445750172002"); BigInteger bp = TEN.pow(50).add(BigInteger.valueOf(577)); Solution sol = ts(bn, bp); System.out.printf("n = %s\n", bn); System.out.printf("p = %s\n", bp); if (sol.exists) { System.out.printf("root1 = %s\n", sol.root1); System.out.printf("root2 = %s\n", sol.root2); } else { System.out.println("No solution exists"); } } }
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
#Dyalect
Dyalect
func String.Tokenize(separator, escape) { var buffer = [] var escaping = false for c in this { if escaping { buffer.Add(c) escaping = false } else if c == escape { escaping = true } else if c == separator { yield buffer.Flush(); } else { buffer.Add(c); } }   if buffer.Length() > 0 || this[this.Length() - 1] == separator { yield buffer.Flush() } }   func Array.Flush() { var str = String.Concat(values: this) this.Clear() str }   let testcase = "one^|uno||three^^^^|four^^^|^cuatro|"; for token in testcase.Tokenize(separator: '|', escape: '^') { print(": \(token)") }
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were 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
#Elena
Elena
import extensions; import extensions'routines; import system'collections; import system'routines; import system'text;   extension op : String { tokenize(separator,escape) { auto buffer := new TextBuilder(); auto list := new ArrayList();   bool escaping := false; self.forEach:(ch) { if (escaping) { buffer.write:ch; escaping := false } else if (ch == escape) { escaping := true } else if (ch == separator) { list.append(buffer.Value); buffer.clear() } else { buffer.write:ch } };   ^ list } }   const string testcase = "one^|uno||three^^^^|four^^^|^cuatro|";   public program() { testcase.tokenize("|", "^").forEach:printingLn }
http://rosettacode.org/wiki/Total_circles_area
Total circles area
Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal digits of precision. The area covered by two or more disks needs to be counted only once. One point of this Task is also to compare and discuss the relative merits of various solution strategies, their performance, precision and simplicity. This means keeping both slower and faster solutions for a language (like C) is welcome. To allow a better comparison of the different implementations, solve the problem with this standard dataset, each line contains the x and y coordinates of the centers of the disks and their radii   (11 disks are fully contained inside other disks): xc yc radius 1.6417233788 1.6121789534 0.0848270516 -1.4944608174 1.2077959613 1.1039549836 0.6110294452 -0.6907087527 0.9089162485 0.3844862411 0.2923344616 0.2375743054 -0.2495892950 -0.3832854473 1.0845181219 1.7813504266 1.6178237031 0.8162655711 -0.1985249206 -0.8343333301 0.0538864941 -1.7011985145 -0.1263820964 0.4776976918 -0.4319462812 1.4104420482 0.7886291537 0.2178372997 -0.9499557344 0.0357871187 -0.6294854565 -1.3078893852 0.7653357688 1.7952608455 0.6281269104 0.2727652452 1.4168575317 1.0683357171 1.1016025378 1.4637371396 0.9463877418 1.1846214562 -0.5263668798 1.7315156631 1.4428514068 -1.2197352481 0.9144146579 1.0727263474 -0.1389358881 0.1092805780 0.7350208828 1.5293954595 0.0030278255 1.2472867347 -0.5258728625 1.3782633069 1.3495508831 -0.1403562064 0.2437382535 1.3804956588 0.8055826339 -0.0482092025 0.3327165165 -0.6311979224 0.7184578971 0.2491045282 1.4685857879 -0.8347049536 1.3670667538 -0.6855727502 1.6465021616 1.0593087096 0.0152957411 0.0638919221 0.9771215985 The result is   21.56503660... . Related task   Circles of given radius through two points. See also http://www.reddit.com/r/dailyprogrammer/comments/zff9o/9062012_challenge_96_difficult_water_droplets/ http://stackoverflow.com/a/1667789/10562
#Python
Python
from collections import namedtuple   Circle = namedtuple("Circle", "x y r")   circles = [ Circle( 1.6417233788, 1.6121789534, 0.0848270516), Circle(-1.4944608174, 1.2077959613, 1.1039549836), Circle( 0.6110294452, -0.6907087527, 0.9089162485), Circle( 0.3844862411, 0.2923344616, 0.2375743054), Circle(-0.2495892950, -0.3832854473, 1.0845181219), Circle( 1.7813504266, 1.6178237031, 0.8162655711), Circle(-0.1985249206, -0.8343333301, 0.0538864941), Circle(-1.7011985145, -0.1263820964, 0.4776976918), Circle(-0.4319462812, 1.4104420482, 0.7886291537), Circle( 0.2178372997, -0.9499557344, 0.0357871187), Circle(-0.6294854565, -1.3078893852, 0.7653357688), Circle( 1.7952608455, 0.6281269104, 0.2727652452), Circle( 1.4168575317, 1.0683357171, 1.1016025378), Circle( 1.4637371396, 0.9463877418, 1.1846214562), Circle(-0.5263668798, 1.7315156631, 1.4428514068), Circle(-1.2197352481, 0.9144146579, 1.0727263474), Circle(-0.1389358881, 0.1092805780, 0.7350208828), Circle( 1.5293954595, 0.0030278255, 1.2472867347), Circle(-0.5258728625, 1.3782633069, 1.3495508831), Circle(-0.1403562064, 0.2437382535, 1.3804956588), Circle( 0.8055826339, -0.0482092025, 0.3327165165), Circle(-0.6311979224, 0.7184578971, 0.2491045282), Circle( 1.4685857879, -0.8347049536, 1.3670667538), Circle(-0.6855727502, 1.6465021616, 1.0593087096), Circle( 0.0152957411, 0.0638919221, 0.9771215985)]   def main(): # compute the bounding box of the circles x_min = min(c.x - c.r for c in circles) x_max = max(c.x + c.r for c in circles) y_min = min(c.y - c.r for c in circles) y_max = max(c.y + c.r for c in circles)   box_side = 500   dx = (x_max - x_min) / box_side dy = (y_max - y_min) / box_side   count = 0   for r in xrange(box_side): y = y_min + r * dy for c in xrange(box_side): x = x_min + c * dx if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2) for circle in circles): count += 1   print "Approximated area:", count * dx * dy   main()
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]
#EchoLisp
EchoLisp
  (define dependencies '((des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee) (dw01 ieee dw01 dware gtech) ;; bad graph add dw04 (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 )))     ;; build dependency graph ;; a depends on b ;; add arc (arrow) a --> b (lib 'graph.lib) (define (a->b g a b) (unless (equal? a b) (graph-make-arc g (graph-make-vertex g a) (graph-make-vertex g b))))   (define (add-dependencies g dep-list) (for* ((dep dep-list) (b (rest dep))) (a->b g b (first dep))))  
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.
#Julia
Julia
import Base.show   @enum Move Left=1 Stay Right   mutable struct MachineState state::String tape::Dict{Int, String} headpos::Int end   struct Rule instate::String s1::String s2::String move::Move outstate::String end   struct Program title::String initial::String final::String blank::String rules::Vector{Rule} end   const testprograms = [ (Program("Simple incrementer", "q0", "qf", "B", [Rule("q0", "1", "1", Right, "q0"), Rule("q0", "B", "1", Stay, "qf")]), Dict(1 =>"1", 2 => "1", 3 => "1"), true), (Program("Three-state busy beaver", "a", "halt", "0", [Rule("a", "0", "1", Right, "b"), Rule("a", "1", "1", Left, "c"), Rule("b", "0", "1", Left, "a"), Rule("b", "1", "1", Right, "b"), Rule("c", "0", "1", Left, "b"), Rule("c", "1", "1", Stay, "halt")]), Dict(), true), (Program("Five-state busy beaver", "A", "H", "0", [Rule("A", "0", "1", Right, "B"), Rule("A", "1", "1", Left, "C"), Rule("B", "0", "1", Right, "C"), Rule("B", "1", "1", Right, "B"), Rule("C", "0", "1", Right, "D"), Rule("C", "1", "0", Left, "E"), Rule("D", "0", "1", Left, "A"), Rule("D", "1", "1", Left, "D"), Rule("E", "0", "1", Stay, "H"), Rule("E", "1", "0", Left, "A")]), Dict(), false)]   function show(io::IO, mstate::MachineState) ibracket(i, curpos, val) = (i == curpos) ? "[$val]" : " $val " print(io, rpad("($(mstate.state))", 12)) for i in sort(collect(keys(mstate.tape))) print(io, " $(ibracket(i, mstate.headpos, mstate.tape[i]))") end end   function turing(program, tape, verbose) println("\n$(program.title)") verbose && println(" State \tTape [head]\n--------------------------------------------------") mstate = MachineState(program.initial, tape, 1) stepcount = 0 while true if !haskey(mstate.tape, mstate.headpos) mstate.tape[mstate.headpos] = program.blank end verbose && println(mstate) for rule in program.rules if rule.instate == mstate.state && rule.s1 == mstate.tape[mstate.headpos] mstate.tape[mstate.headpos] = rule.s2 if rule.move == Left mstate.headpos -= 1 elseif rule.move == Right mstate.headpos += 1 end mstate.state = rule.outstate break end end stepcount += 1 if mstate.state == program.final break end end verbose && println(mstate) println("Total steps: $stepcount") end   for (prog, tape, verbose) in testprograms turing(prog, tape, verbose) end  
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).
#J
J
  nth_prime =: p: NB. 2 is the zeroth prime totient =: 5&p: primeQ =: 1&p:   NB. first row contains the integer NB. second row totient NB. third 1 iff prime (, totient ,: primeQ) >: i. 25 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 1 1 2 2 4 2 6 4 6 4 10 4 12 6 8 8 16 6 18 8 12 10 22 8 20 0 1 1 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 0     NB. primes first exceeding the limits [&.:(p:inv) 10 ^ 2 + i. 4 101 1009 10007 100003   p:inv 101 1009 10007 100003 25 168 1229 9592   NB. limit and prime count (,. p:inv) 10 ^ 2 + i. 5 100 25 1000 168 10000 1229 100000 9592 1e6 78498  
http://rosettacode.org/wiki/Topswops
Topswops
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is composed of reversing the first   m   cards where   m   is the value of the topmost card. Rounds are repeated until the topmost card is the number   1   and the number of swaps is recorded. For our example the swaps produce: [2, 4, 1, 3] # Initial shuffle [4, 2, 1, 3] [3, 1, 2, 4] [2, 1, 3, 4] [1, 2, 3, 4] For a total of four swaps from the initial ordering to produce the terminating case where   1   is on top. For a particular number   n   of cards,   topswops(n)   is the maximum swaps needed for any starting permutation of the   n   cards. Task The task is to generate and show here a table of   n   vs   topswops(n)   for   n   in the range   1..10   inclusive. Note Topswops   is also known as   Fannkuch   from the German word   Pfannkuchen   meaning   pancake. Related tasks   Number reversal game   Sorting algorithms/Pancake sort
#PL.2FI
PL/I
  (subscriptrange): topswap: procedure options (main); /* 12 November 2013 */ declare cards(*) fixed (2) controlled, t fixed (2); declare dealt(*) bit(1) controlled; declare (count, i, m, n, c1, c2) fixed binary; declare random builtin;   do n = 1 to 10; allocate cards(n), dealt(n); /* Take the n cards, in order ... */ do i = 1 to n; cards(i) = i; end; /* ... and shuffle them. */ do i = 1 to n; c1 = random*n+1; c2 = random*n+1; t = cards(c1); cards(c1) = cards(c2); cards(c2) = t; end; /* If '1' is the first card, game is trivial; swap it with another. */ if cards(1) = 1 & n > 1 then do; t = cards(1); cards(1) = cards(2); cards(2) = t; end;   count = 0; do until (cards(1) = 1); /* take the value of the first card, M, and reverse the first M cards. */ m = cards(1); do i = 1 to m/2; t = cards(i); cards(i) = cards(m-i+1); cards(m-i+1) = t; end; count = count + 1; end; put skip edit (n, ':', count) (f(2), a, f(4)); end; end topswap;  
http://rosettacode.org/wiki/Topswops
Topswops
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is composed of reversing the first   m   cards where   m   is the value of the topmost card. Rounds are repeated until the topmost card is the number   1   and the number of swaps is recorded. For our example the swaps produce: [2, 4, 1, 3] # Initial shuffle [4, 2, 1, 3] [3, 1, 2, 4] [2, 1, 3, 4] [1, 2, 3, 4] For a total of four swaps from the initial ordering to produce the terminating case where   1   is on top. For a particular number   n   of cards,   topswops(n)   is the maximum swaps needed for any starting permutation of the   n   cards. Task The task is to generate and show here a table of   n   vs   topswops(n)   for   n   in the range   1..10   inclusive. Note Topswops   is also known as   Fannkuch   from the German word   Pfannkuchen   meaning   pancake. Related tasks   Number reversal game   Sorting algorithms/Pancake sort
#Potion
Potion
range = (a, b): i = 0, l = list(b-a+1) while (a + i <= b): l (i) = a + i++. l.   fannkuch = (n): flips = 0, maxf = 0, k = 0, m = n - 1, r = n perml = range(0, n), count = list(n), perm = list(n)   loop: while (r != 1): count (r-1) = r r--.   if (perml (0) != 0 and perml (m) != m): flips = 0, i = 1 while (i < n): perm (i) = perml (i) i++. k = perml (0) loop: i = 1, j = k - 1 while (i < j): t = perm (i), perm (i) = perm (j), perm (j) = t i++, j--. flips++ j = perm (k), perm (k) = k, k = j if (k == 0): break. . if (flips > maxf): maxf = flips. .   loop: if (r == n): (n, maxf) say return (maxf).   i = 0, j = perml (0) while (i < r): k = i + 1 perml (i) = perml (k) i = k. perml (r) = j   j = count (r) - 1 count (r) = j if (j > 0): break. r++ _ n   n = argv(1) number if (n<1): n=10. fannkuch(n)  
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that 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.
#Elixir
Elixir
iex(61)> deg = 45 45 iex(62)> rad = :math.pi / 4 0.7853981633974483 iex(63)> :math.sin(deg * :math.pi / 180) == :math.sin(rad) true iex(64)> :math.cos(deg * :math.pi / 180) == :math.cos(rad) true iex(65)> :math.tan(deg * :math.pi / 180) == :math.tan(rad) true iex(66)> temp = :math.acos(:math.cos(rad)) 0.7853981633974483 iex(67)> temp * 180 / :math.pi == deg true iex(68)> temp = :math.atan(:math.tan(rad)) 0.7853981633974483 iex(69)> temp * 180 / :math.pi == deg true
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).
#Liberty_BASIC
Liberty BASIC
  ' Trabb Pardo-Knuth algorithm ' Used "magic numbers" because of strict specification of the algorithm. dim s(10) print "Enter 11 numbers." for i = 0 to 10 print i + 1; input " => "; s(i) next i print ' Reverse for i = 0 to 10 / 2 tmp = s(i) s(i) = s(10 - i) s(10 - i) = tmp next i 'Results for i = 0 to 10 print "f("; s(i); ") = "; r = f(s(i)) if r > 400 then print "overflow" else print r end if next i end   function f(n) f = sqr(abs(n)) + 5 * n * n * n end function  
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).
#Lua
Lua
function f (x) return math.abs(x)^0.5 + 5*x^3 end   function reverse (t) local rev = {} for i, v in ipairs(t) do rev[#t - (i-1)] = v end return rev end   local sequence, result = {} print("Enter 11 numbers...") for n = 1, 11 do io.write(n .. ": ") sequence[n] = io.read() end for _, x in ipairs(reverse(sequence)) do result = f(x) if result > 400 then print("Overflow!") else print(result) end end
http://rosettacode.org/wiki/Truth_table
Truth table
A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function. Task Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function. (One can assume that the user input is correct). Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function. Either reverse-polish or infix notation expressions are allowed. Related tasks   Boolean values   Ternary logic See also   Wolfram MathWorld entry on truth tables.   some "truth table" examples from Google.
#Ruby
Ruby
loop do print "\ninput a boolean expression (e.g. 'a & b'): " expr = gets.strip.downcase break if expr.empty?   vars = expr.scan(/\p{Alpha}+/) if vars.empty? puts "no variables detected in your boolean expression" next end   vars.each {|v| print "#{v}\t"} puts "| #{expr}"   prefix = [] suffix = [] vars.each do |v| prefix << "[false, true].each do |#{v}|" suffix << "end" end   body = vars.inject("puts ") {|str, v| str + "#{v}.to_s + '\t' + "} body += '"| " + eval(expr).to_s'   eval (prefix + [body] + suffix).join("\n") end
http://rosettacode.org/wiki/Ulam_spiral_(for_primes)
Ulam spiral (for primes)
An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is shown with sequential integers,   starting at   1. In an Ulam spiral of primes, only the primes are shown (usually indicated by some glyph such as a dot or asterisk),   and all non-primes as shown as a blank   (or some other whitespace). Of course, the grid and border are not to be displayed (but they are displayed here when using these Wiki HTML tables). Normally, the spiral starts in the "center",   and the   2nd   number is to the viewer's right and the number spiral starts from there in a counter-clockwise direction. There are other geometric shapes that are used as well, including clock-wise spirals. Also, some spirals (for the   2nd   number)   is viewed upwards from the   1st   number instead of to the right, but that is just a matter of orientation. Sometimes, the starting number can be specified to show more visual striking patterns (of prime densities). [A larger than necessary grid (numbers wise) is shown here to illustrate the pattern of numbers on the diagonals   (which may be used by the method to orientate the direction of spiral-construction algorithm within the example computer programs)]. Then, in the next phase in the transformation of the Ulam prime spiral,   the non-primes are translated to blanks. In the orange grid below,   the primes are left intact,   and all non-primes are changed to blanks. Then, in the final transformation of the Ulam spiral (the yellow grid),   translate the primes to a glyph such as a   •   or some other suitable glyph. 65 64 63 62 61 60 59 58 57 66 37 36 35 34 33 32 31 56 67 38 17 16 15 14 13 30 55 68 39 18 5 4 3 12 29 54 69 40 19 6 1 2 11 28 53 70 41 20 7 8 9 10 27 52 71 42 21 22 23 24 25 26 51 72 43 44 45 46 47 48 49 50 73 74 75 76 77 78 79 80 81 61 59 37 31 67 17 13 5 3 29 19 2 11 53 41 7 71 23 43 47 73 79 • • • • • • • • • • • • • • • • • • • • • • The Ulam spiral becomes more visually obvious as the grid increases in size. Task For any sized   N × N   grid,   construct and show an Ulam spiral (counter-clockwise) of primes starting at some specified initial number   (the default would be 1),   with some suitably   dotty   (glyph) representation to indicate primes,   and the absence of dots to indicate non-primes. You should demonstrate the generator by showing at Ulam prime spiral large enough to (almost) fill your terminal screen. Related tasks   Spiral matrix   Zig-zag matrix   Identity matrix   Sequence of primes by Trial Division See also Wikipedia entry:   Ulam spiral MathWorld™ entry:   Prime Spiral
#Sidef
Sidef
require('Imager')   var (n=512, start=1, file='ulam.png')   ARGV.getopt( 'n=i' => \n, 's=i' => \start, 'f=s' => \file, )   func cell(n, x, y, start) { y -= (n >> 1) x -= (n-1 >> 1) var l = 2*(x.abs > y.abs ? x.abs : y.abs) var d = (y > x ? (l*3 + x + y) : (l - x - y)) (l-1)**2 + d + start - 1 }   var black = %O<Imager::Color>.new('#000000') var white = %O<Imager::Color>.new('#FFFFFF')   var img = %O<Imager>.new(xsize => n, ysize => n, channels => 1) img.box(filled => 1, color => white)   for y=(^n), x=(^n) { if (cell(n, x, y, start).is_prime) { img.setpixel(x => x, y => y, color => black) } }   img.write(file => file)
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.]
#Nim
Nim
import sets, strutils, algorithm   proc primes(n: int64): seq[int64] = var multiples: HashSet[int64] for i in 2..n: if i notin multiples: result.add i for j in countup(i*i, n, i.int): multiples.incl j   proc truncatablePrime(n: int64): tuple[left, right: int64] = var primelist: seq[string] for x in primes(n): primelist.add($x) reverse primelist var primeset = primelist.toHashSet for n in primelist: var alltruncs: HashSet[string] for i in 0..n.high: alltruncs.incl n[i..n.high] if alltruncs <= primeset: result.left = parseInt(n) break for n in primelist: var alltruncs: HashSet[string] for i in 0..n.high: alltruncs.incl n[0..i] if alltruncs <= primeset: result.right = parseInt(n) break   echo truncatablePrime(1000000i64)
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.
#Clojure
Clojure
(defn walk [node f order] (when node (doseq [o order] (if (= o :visit) (f (:val node)) (walk (node o) f order)))))   (defn preorder [node f] (walk node f [:visit :left :right]))   (defn inorder [node f] (walk node f [:left :visit :right]))   (defn postorder [node f] (walk node f [:left :right :visit]))   (defn queue [& xs] (when (seq xs) (apply conj clojure.lang.PersistentQueue/EMPTY xs)))   (defn level-order [root f] (loop [q (queue root)] (when-not (empty? q) (if-let [node (first q)] (do (f (:val node)) (recur (conj (pop q) (:left node) (:right node)))) (recur (pop q))))))   (defn vec-to-tree [t] (if (vector? t) (let [[val left right] t] {:val val  :left (vec-to-tree left)  :right (vec-to-tree right)}) t))   (let [tree (vec-to-tree [1 [2 [4 [7]] [5]] [3 [6 [8] [9]]]]) fs '[preorder inorder postorder level-order] pr-node #(print (format "%2d" %))] (doseq [f fs] (print (format "%-12s" (str f ":"))) ((resolve f) tree pr-node) (println)))
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
#AppleScript
AppleScript
on run intercalate(".", splitOn(",", "Hello,How,Are,You,Today")) end run     -- splitOn :: String -> String -> [String] on splitOn(strDelim, strMain) set {dlm, my text item delimiters} to {my text item delimiters, strDelim} set lstParts to text items of strMain set my text item delimiters to dlm return lstParts end splitOn   -- intercalate :: String -> [String] -> String on intercalate(strText, lstText) set {dlm, my text item delimiters} to {my text item delimiters, strText} set strJoined to lstText as text set my text item delimiters to dlm return strJoined end intercalate
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.
#ACL2
ACL2
(time$ (nthcdr 9999999 (take 10000000 nil)))
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.
#Action.21
Action!
BYTE RTCLOK1=$13 BYTE RTCLOK2=$14 BYTE PALNTSC=$D014   PROC Count(CARD max) CARD i   FOR i=1 TO max DO OD RETURN   CARD FUNC GetFrame() CARD res BYTE lsb=res,msb=res+1   lsb=RTCLOK2 msb=RTCLOK1 RETURN (res)   CARD FUNC FramesToMs(CARD frames) CARD res   IF PALNTSC=15 THEN res=frames*60 ELSE res=frames*50 FI RETURN (res)   PROC Main() CARD ARRAY c=[1000 2000 5000 10000 20000 50000] CARD beg,end,diff,diffMs BYTE i   FOR i=0 TO 5 DO PrintF("Count to %U takes ",c(i)) beg=GetFrame() Count(c(i)) end=GetFrame() diff=end-beg diffMs=FramesToMs(diff) PrintF("%U ms%E",diffMs) OD RETURN
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
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   public class Program { class Employee { public Employee(string name, string id, int salary, string department) { Name = name; Id = id; Salary = salary; Department = department; }   public string Name { get; private set; } public string Id { get; private set; } public int Salary { get; private set; } public string Department { get; private set; }   public override string ToString() { return String.Format("{0, -25}\t{1}\t{2}", Name, Id, Salary); } }   private static void Main(string[] args) { var employees = new List<Employee> { new Employee("Tyler Bennett", "E10297", 32000, "D101"), new Employee("John Rappl", "E21437", 47000, "D050"), new Employee("George Woltman", "E21437", 53500, "D101"), new Employee("Adam Smith", "E21437", 18000, "D202"), new Employee("Claire Buckman", "E39876", 27800, "D202"), new Employee("David McClellan", "E04242", 41500, "D101"), new Employee("Rich Holcomb", "E01234", 49500, "D202"), new Employee("Nathan Adams", "E41298", 21900, "D050"), new Employee("Richard Potter", "E43128", 15900, "D101"), new Employee("David Motsinger", "E27002", 19250, "D202"), new Employee("Tim Sampair", "E03033", 27000, "D101"), new Employee("Kim Arlich", "E10001", 57000, "D190"), new Employee("Timothy Grove", "E16398", 29900, "D190") };   DisplayTopNPerDepartment(employees, 2); }   static void DisplayTopNPerDepartment(IEnumerable<Employee> employees, int n) { var topSalariesByDepartment = from employee in employees group employee by employee.Department into g select new { Department = g.Key, TopEmployeesBySalary = g.OrderByDescending(e => e.Salary).Take(n) };   foreach (var x in topSalariesByDepartment) { Console.WriteLine("Department: " + x.Department); foreach (var employee in x.TopEmployeesBySalary) Console.WriteLine(employee); Console.WriteLine("----------------------------"); } } }
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.
#Ada
Ada
with Ada.Text_IO, Ada.Numerics.Discrete_Random; -- can play human-human, human-computer, computer-human or computer-computer -- the computer isn't very clever: it just chooses a legal random move   procedure Tic_Tac_Toe is   type The_Range is range 1 .. 3; type Board_Type is array (The_Range, The_Range) of Character;   package Rand is new Ada.Numerics.Discrete_Random(The_Range); Gen: Rand.Generator; -- required for the random moves   procedure Show_Board(Board: Board_Type) is use Ada.Text_IO; begin for Row in The_Range loop for Column in The_Range loop Put(Board(Row, Column)); end loop; Put_Line(""); end loop; Put_Line(""); end Show_Board;   function Find_Winner(Board: Board_Type) return Character is -- if 'x' or 'o' wins, it returns that, else it returns ' '   function Three_Equal(A,B,C: Character) return Boolean is begin return (A=B) and (A=C); end Three_Equal;   begin -- Find_Winner for I in The_Range loop if Three_Equal(Board(I,1), Board(I,2), Board(I,3)) then return Board(I,1); elsif Three_Equal(Board(1,I), Board(2,I), Board(3,I)) then return Board(1,I); end if; end loop; if Three_Equal(Board(1,1), Board(2,2), Board (3,3)) or Three_Equal(Board(3,1), Board(2,2), Board (1,3)) then return Board(2,2); end if; return ' '; end Find_Winner;   procedure Do_Move(Board: in out Board_Type; New_Char: Character; Computer_Move: Boolean) is Done: Boolean := False; C: Character; use Ada.Text_IO;   procedure Do_C_Move(Board: in out Board_Type; New_Char: Character) is Found: Boolean := False; X,Y: The_Range; begin while not Found loop X := Rand.Random(Gen); Y := Rand.Random(Gen); if (Board(X,Y) /= 'x') and (Board(X,Y) /= 'o') then Found := True; Board(X,Y) := New_Char; end if; end loop; end Do_C_Move;   begin if Computer_Move then Do_C_Move(Board, New_Char); else -- read move; Put_Line("Choose your move, " & New_Char); while not Done loop Get(C); for Row in The_Range loop for Col in The_Range loop if Board(Row, Col) = C then Board(Row, Col) := New_Char; Done := True; end if; end loop; end loop; end loop; end if; end Do_Move;   The_Board : Board_Type := (('1','2','3'), ('4','5','6'), ('7','8','9')); Cnt_Moves: Natural := 0; Players: array(0 .. 1) of Character := ('x', 'o'); -- 'x' begins C_Player: array(0 .. 1) of Boolean := (False, False); Reply: Character;   begin -- Tic_Tac_Toe   -- firstly, ask whether the computer shall take over either player for I in Players'Range loop Ada.Text_IO.Put_Line("Shall " & Players(I) & " be run by the computer? (y=yes)"); Ada.Text_IO.Get(Reply); if Reply='y' or Reply='Y' then C_Player(I) := True; Ada.Text_IO.Put_Line("Yes!"); else Ada.Text_IO.Put_Line("No!"); end if; end loop; Rand.Reset(Gen); -- to initalize the random generator   -- now run the game while (Find_Winner(The_Board) = ' ') and (Cnt_Moves < 9) loop Show_Board(The_Board); Do_Move(The_Board, Players(Cnt_Moves mod 2), C_Player(Cnt_Moves mod 2)); Cnt_Moves := Cnt_Moves + 1; end loop; Ada.Text_IO.Put_Line("This is the end!");   -- finally, output the outcome Show_Board (The_Board); if Find_Winner(The_Board) = ' ' then Ada.Text_IO.Put_Line("Draw"); else Ada.Text_IO.Put_Line("The winner is: " & Find_Winner(The_Board)); end if; end Tic_Tac_Toe;
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Arturo
Arturo
hanoi: function [n f dir via][ if n>0 [ hanoi n-1 f via dir print ["Move disk" n "from" f "to" dir] hanoi n-1 via dir f ] ]   hanoi 3 'L 'M 'R
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
#D
D
import std.range; import std.stdio;   struct TM { private char[] sequence = ['0']; private char[] inverse = ['1']; private char[] buffer;   enum empty = false;   auto front() { return sequence; }   auto popFront() { buffer = sequence; sequence ~= inverse; inverse ~= buffer; } }   void main() { TM sequence;   foreach (step; sequence.take(8)) { writeln(step); } }  
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
#Delphi
Delphi
/* Find the N'th digit in the Thue-Morse sequence */ proc nonrec tm(word n) byte: word n2; n2 := n; while n2 ~= 0 do n2 := n2 >> 1; n := n >< n2 od; n & 1 corp   /* Print the first 64 digits */ proc nonrec main() void: byte i; for i from 0 upto 63 do write(tm(i):1) od corp
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm
Tonelli-Shanks algorithm
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computational number theory, the Tonelli–Shanks algorithm is a technique for solving for x in a congruence of the form: x2 ≡ n (mod p) where n is an integer which is a quadratic residue (mod p), p is an odd prime, and x,n ∈ Fp where Fp = {0, 1, ..., p - 1}. It is used in cryptography techniques. To apply the algorithm, we need the Legendre symbol: The Legendre symbol (a | p) denotes the value of a(p-1)/2 (mod p). (a | p) ≡ 1    if a is a square (mod p) (a | p) ≡ -1    if a is not a square (mod p) (a | p) ≡ 0    if a ≡ 0 (mod p) Algorithm pseudo-code All ≡ are taken to mean (mod p) unless stated otherwise. Input: p an odd prime, and an integer n . Step 0: Check that n is indeed a square: (n | p) must be ≡ 1 . Step 1: By factoring out powers of 2 from p - 1, find q and s such that p - 1 = q2s with q odd . If p ≡ 3 (mod 4) (i.e. s = 1), output the two solutions r ≡ ± n(p+1)/4 . Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq . Step 3: Set r ≡ n(q+1)/2, t ≡ nq, m = s . Step 4: Loop the following: If t ≡ 1, output r and p - r . Otherwise find, by repeated squaring, the lowest i, 0 < i < m , such that t2i ≡ 1 . Let b ≡ c2(m - i - 1), and set r ≡ rb, t ≡ tb2, c ≡ b2 and m = i . Task Implement the above algorithm. Find solutions (if any) for n = 10 p = 13 n = 56 p = 101 n = 1030 p = 10009 n = 1032 p = 10009 n = 44402 p = 100049 Extra credit n = 665820697 p = 1000000009 n = 881398088036 p = 1000000000039 n = 41660815127637347468140745042827704103445750172002 p = 10^50 + 577 See also Modular exponentiation Cipolla's algorithm
#Julia
Julia
module TonelliShanks   legendre(a, p) = powermod(a, (p - 1) ÷ 2, p)   function solve(n::T, p::T) where T <: Union{Int, Int128, BigInt} legendre(n, p) != 1 && throw(ArgumentError("$n not a square (mod $p)")) local q::T = p - one(p) local s::T = 0 while iszero(q % 2) q ÷= 2 s += one(s) end if s == one(s) r = powermod(n, (p + 1) >> 2, p) return r, p - r end local z::T for z in 2:(p - 1) p - 1 == legendre(z, p) && break end local c::T = powermod(z, q, p) local r::T = powermod(n, (q + 1) >> 1, p) local t::T = powermod(n, q, p) local m::T = s local t2::T = zero(p) while !iszero((t - 1) % p) t2 = (t * t) % p local i::T for i in Base.OneTo(m) iszero((t2 - 1) % p) && break t2 = (t2 * t2) % p end b = powermod(c, 1 << (m - i - 1), p) r = (r * b) % p c = (b * b) % p t = (t * c) % p m = i end return r, p - r end   end # module TonelliShanks
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm
Tonelli-Shanks algorithm
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computational number theory, the Tonelli–Shanks algorithm is a technique for solving for x in a congruence of the form: x2 ≡ n (mod p) where n is an integer which is a quadratic residue (mod p), p is an odd prime, and x,n ∈ Fp where Fp = {0, 1, ..., p - 1}. It is used in cryptography techniques. To apply the algorithm, we need the Legendre symbol: The Legendre symbol (a | p) denotes the value of a(p-1)/2 (mod p). (a | p) ≡ 1    if a is a square (mod p) (a | p) ≡ -1    if a is not a square (mod p) (a | p) ≡ 0    if a ≡ 0 (mod p) Algorithm pseudo-code All ≡ are taken to mean (mod p) unless stated otherwise. Input: p an odd prime, and an integer n . Step 0: Check that n is indeed a square: (n | p) must be ≡ 1 . Step 1: By factoring out powers of 2 from p - 1, find q and s such that p - 1 = q2s with q odd . If p ≡ 3 (mod 4) (i.e. s = 1), output the two solutions r ≡ ± n(p+1)/4 . Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq . Step 3: Set r ≡ n(q+1)/2, t ≡ nq, m = s . Step 4: Loop the following: If t ≡ 1, output r and p - r . Otherwise find, by repeated squaring, the lowest i, 0 < i < m , such that t2i ≡ 1 . Let b ≡ c2(m - i - 1), and set r ≡ rb, t ≡ tb2, c ≡ b2 and m = i . Task Implement the above algorithm. Find solutions (if any) for n = 10 p = 13 n = 56 p = 101 n = 1030 p = 10009 n = 1032 p = 10009 n = 44402 p = 100049 Extra credit n = 665820697 p = 1000000009 n = 881398088036 p = 1000000000039 n = 41660815127637347468140745042827704103445750172002 p = 10^50 + 577 See also Modular exponentiation Cipolla's algorithm
#Kotlin
Kotlin
// version 1.1.3   import java.math.BigInteger   data class Solution(val root1: BigInteger, val root2: BigInteger, val exists: Boolean)   val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bigTwo = BigInteger.valueOf(2L) val bigFour = BigInteger.valueOf(4L) val bigTen = BigInteger.TEN   fun ts(n: Long, p: Long) = ts(BigInteger.valueOf(n), BigInteger.valueOf(p))   fun ts(n: BigInteger, p: BigInteger): Solution {   fun powModP(a: BigInteger, e: BigInteger) = a.modPow(e, p)   fun ls(a: BigInteger) = powModP(a, (p - bigOne) / bigTwo)   if (ls(n) != bigOne) return Solution(bigZero, bigZero, false) var q = p - bigOne var ss = bigZero while (q.and(bigOne) == bigZero) { ss = ss + bigOne q = q.shiftRight(1) }   if (ss == bigOne) { val r1 = powModP(n, (p + bigOne) / bigFour) return Solution(r1, p - r1, true) }   var z = bigTwo while (ls(z) != p - bigOne) z = z + bigOne var c = powModP(z, q) var r = powModP(n, (q + bigOne) / bigTwo) var t = powModP(n, q) var m = ss   while (true) { if (t == bigOne) return Solution(r, p - r, true) var i = bigZero var zz = t while (zz != bigOne && i < m - bigOne) { zz = zz * zz % p i = i + bigOne } var b = c var e = m - i - bigOne while (e > bigZero) { b = b * b % p e = e - bigOne } r = r * b % p c = b * b % p t = t * c % p m = i } }   fun main(args: Array<String>) { val pairs = listOf<Pair<Long, Long>>( 10L to 13L, 56L to 101L, 1030L to 10009L, 1032L to 10009L, 44402L to 100049L, 665820697L to 1000000009L, 881398088036L to 1000000000039L )   for (pair in pairs) { val (n, p) = pair val (root1, root2, exists) = ts(n, p) println("n = $n") println("p = $p") if (exists) { println("root1 = $root1") println("root2 = $root2") } else println("No solution exists") println() }   val bn = BigInteger("41660815127637347468140745042827704103445750172002") val bp = bigTen.pow(50) + BigInteger.valueOf(577L) val (broot1, broot2, bexists) = ts(bn, bp) println("n = $bn") println("p = $bp") if (bexists) { println("root1 = $broot1") println("root2 = $broot2") } else println("No solution exists") }
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
#F.23
F#
open System open System.Text.RegularExpressions   (* .NET regexes have unlimited look-behind, so we can look for separators which are preceeded by an even number of (or no) escape characters *) let split esc sep s = Regex.Split ( s, String.Format("(?<=(?:\b|[^{0}])(?:{0}{0})*){1}", Regex.Escape(esc), Regex.Escape(sep)) )   let unescape esc s = Regex.Replace( s, Regex.Escape(esc) + "(.)", "$1" )   [<EntryPoint>] let main argv = let (esc, sep) = ("^", "|") "one^|uno||three^^^^|four^^^|^cuatro|" |> split esc sep |> Seq.map (unescape esc) |> Seq.iter (fun s -> printfn "'%s'" s) 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
#Factor
Factor
USING: accessors kernel lists literals namespaces parser-combinators prettyprint sequences strings ;   SYMBOLS: esc sep ;   : set-chars ( m n -- ) [ sep set ] [ esc set ] bi* ; : escape ( -- parser ) esc get 1token ; : escaped ( -- parser ) escape any-char-parser &> ; : separator ( -- parser ) sep get 1token ;   : character ( -- parser ) ${ esc get sep get } [ member? not ] curry satisfy ;   : my-token ( -- parser ) escaped character <|> <*> ;   : token-list ( -- parser ) my-token separator list-of [ [ >string ] map ] <@ ;   : tokenize ( str sep-char esc-char -- seq ) set-chars token-list parse car parsed>> ;   "one^|uno||three^^^^|four^^^|^cuatro|" CHAR: | CHAR: ^ tokenize .
http://rosettacode.org/wiki/Total_circles_area
Total circles area
Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal digits of precision. The area covered by two or more disks needs to be counted only once. One point of this Task is also to compare and discuss the relative merits of various solution strategies, their performance, precision and simplicity. This means keeping both slower and faster solutions for a language (like C) is welcome. To allow a better comparison of the different implementations, solve the problem with this standard dataset, each line contains the x and y coordinates of the centers of the disks and their radii   (11 disks are fully contained inside other disks): xc yc radius 1.6417233788 1.6121789534 0.0848270516 -1.4944608174 1.2077959613 1.1039549836 0.6110294452 -0.6907087527 0.9089162485 0.3844862411 0.2923344616 0.2375743054 -0.2495892950 -0.3832854473 1.0845181219 1.7813504266 1.6178237031 0.8162655711 -0.1985249206 -0.8343333301 0.0538864941 -1.7011985145 -0.1263820964 0.4776976918 -0.4319462812 1.4104420482 0.7886291537 0.2178372997 -0.9499557344 0.0357871187 -0.6294854565 -1.3078893852 0.7653357688 1.7952608455 0.6281269104 0.2727652452 1.4168575317 1.0683357171 1.1016025378 1.4637371396 0.9463877418 1.1846214562 -0.5263668798 1.7315156631 1.4428514068 -1.2197352481 0.9144146579 1.0727263474 -0.1389358881 0.1092805780 0.7350208828 1.5293954595 0.0030278255 1.2472867347 -0.5258728625 1.3782633069 1.3495508831 -0.1403562064 0.2437382535 1.3804956588 0.8055826339 -0.0482092025 0.3327165165 -0.6311979224 0.7184578971 0.2491045282 1.4685857879 -0.8347049536 1.3670667538 -0.6855727502 1.6465021616 1.0593087096 0.0152957411 0.0638919221 0.9771215985 The result is   21.56503660... . Related task   Circles of given radius through two points. See also http://www.reddit.com/r/dailyprogrammer/comments/zff9o/9062012_challenge_96_difficult_water_droplets/ http://stackoverflow.com/a/1667789/10562
#Racket
Racket
class Point { has Real $.x; has Real $.y; has Int $!cbits; # bitmap of circle membership   method cbits { $!cbits //= set_cbits(self) } method gist { $!x ~ "\t" ~ $!y } }   multi infix:<to>(Point $p1, Point $p2) { sqrt ($p1.x - $p2.x) ** 2 + ($p1.y - $p2.y) ** 2; }   multi infix:<mid>(Point $p1, Point $p2) { Point.new(x => ($p1.x + $p2.x) / 2, y => ($p1.y + $p2.y) / 2); }   class Circle { has Point $.center; has Real $.radius;   has Point $.north = Point.new(x => $!center.x, y => $!center.y + $!radius); has Point $.west = Point.new(x => $!center.x - $!radius, y => $!center.y); has Point $.south = Point.new(x => $!center.x, y => $!center.y - $!radius); has Point $.east = Point.new(x => $!center.x + $!radius, y => $!center.y);   multi method contains(Circle $c) { $!center to $c.center <= $!radius - $c.radius } multi method contains(Point $p) { $!center to $p <= $!radius } method gist { $!center.gist ~ "\t" ~ $.radius } }   class Rect { has Point $.nw; has Point $.ne; has Point $.sw; has Point $.se;   method diag { $!ne to $!se } method area { ($!ne.x - $!nw.x) * ($!nw.y - $!sw.y) } method contains(Point $p) { $!nw.x < $p.x < $!ne.x and $!sw.y < $p.y < $!nw.y; } }   my @rawcircles = sort -*.radius, map -> $x, $y, $radius { Circle.new(:center(Point.new(:$x, :$y)), :$radius) }, < 1.6417233788 1.6121789534 0.0848270516 -1.4944608174 1.2077959613 1.1039549836 0.6110294452 -0.6907087527 0.9089162485 0.3844862411 0.2923344616 0.2375743054 -0.2495892950 -0.3832854473 1.0845181219 1.7813504266 1.6178237031 0.8162655711 -0.1985249206 -0.8343333301 0.0538864941 -1.7011985145 -0.1263820964 0.4776976918 -0.4319462812 1.4104420482 0.7886291537 0.2178372997 -0.9499557344 0.0357871187 -0.6294854565 -1.3078893852 0.7653357688 1.7952608455 0.6281269104 0.2727652452 1.4168575317 1.0683357171 1.1016025378 1.4637371396 0.9463877418 1.1846214562 -0.5263668798 1.7315156631 1.4428514068 -1.2197352481 0.9144146579 1.0727263474 -0.1389358881 0.1092805780 0.7350208828 1.5293954595 0.0030278255 1.2472867347 -0.5258728625 1.3782633069 1.3495508831 -0.1403562064 0.2437382535 1.3804956588 0.8055826339 -0.0482092025 0.3327165165 -0.6311979224 0.7184578971 0.2491045282 1.4685857879 -0.8347049536 1.3670667538 -0.6855727502 1.6465021616 1.0593087096 0.0152957411 0.0638919221 0.9771215985 >».Num;   # remove redundant circles my @circles; while @rawcircles { my $c = @rawcircles.shift; next if @circles.any.contains($c); push @circles, $c; }   sub set_cbits(Point $p) { my $cbits = 0; for @circles Z (1,2,4...*) -> ($c, $b) { $cbits += $b if $c.contains($p); } $cbits; }   my $xmin = min @circles.map: { .center.x - .radius } my $xmax = max @circles.map: { .center.x + .radius } my $ymin = min @circles.map: { .center.y - .radius } my $ymax = max @circles.map: { .center.y + .radius }   my $min-radius = @circles[*-1].radius;   my $outer-rect = Rect.new: nw => Point.new(x => $xmin, y => $ymax), ne => Point.new(x => $xmax, y => $ymax), sw => Point.new(x => $xmin, y => $ymin), se => Point.new(x => $xmax, y => $ymin);   my $outer-area = $outer-rect.area;   my @unknowns = $outer-rect; my $known-dry = 0e0; my $known-wet = 0e0; my $div = 1;   # divide current rects each into four rects, analyze each sub divide(@old) {   $div *= 2;   # rects too small to hold circle? my $smallish = @old[0].diag < $min-radius;   my @unk; for @old { my $center = .nw mid .se; my $north = .nw mid .ne; my $south = .sw mid .se; my $west = .nw mid .sw; my $east = .ne mid .se;   for Rect.new(nw => .nw, ne => $north, sw => $west, se => $center), Rect.new(nw => $north, ne => .ne, sw => $center, se => $east), Rect.new(nw => $west, ne => $center, sw => .sw, se => $south), Rect.new(nw => $center, ne => $east, sw => $south, se => .se) { my @bits = .nw.cbits, .ne.cbits, .sw.cbits, .se.cbits;   # if all 4 points wet by same circle, guaranteed wet if [+&] @bits { $known-wet += .area; next; }   # if all 4 corners are dry, must check further if not [+|] @bits and $smallish {   # check that no circle bulges into this rect my $ok = True; for @circles -> $c { if .contains($c.east) or .contains($c.west) or .contains($c.north) or .contains($c.south) { $ok = False; last; } } if $ok { $known-dry += .area; next; } } push @unk, $_; # dunno yet } } @unk; }   my $delta = 0.001; repeat until my $diff < $delta { @unknowns = divide(@unknowns);   $diff = $outer-area - $known-dry - $known-wet; say 'div: ', $div.fmt('%-5d'), ' unk: ', (+@unknowns).fmt('%-6d'), ' est: ', ($known-wet + $diff/2).fmt('%9.6f'), ' wet: ', $known-wet.fmt('%9.6f'), ' dry: ', ($outer-area - $known-dry).fmt('%9.6f'), ' diff: ', $diff.fmt('%9.6f'), ' error: ', ($diff - @unknowns * @unknowns[0].area).fmt('%e'); }
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]
#Elixir
Elixir
defmodule Topological do def sort(library) do g = :digraph.new Enum.each(library, fn {l,deps} ->  :digraph.add_vertex(g,l) # noop if library already added Enum.each(deps, fn d -> add_dependency(g,l,d) end) end) if t = :digraph_utils.topsort(g) do print_path(t) else IO.puts "Unsortable contains circular dependencies:" Enum.each(:digraph.vertices(g), fn v -> if vs = :digraph.get_short_cycle(g,v), do: print_path(vs) end) end end   defp print_path(l), do: IO.puts Enum.join(l, " -> ")   defp add_dependency(_g,l,l), do: :ok defp add_dependency(g,l,d) do  :digraph.add_vertex(g,d) # noop if dependency already added  :digraph.add_edge(g,d,l) # Dependencies represented as an edge d -> l end end   libraries = [ des_system_lib: ~w[std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee]a, dw01: ~w[ieee dw01 dware gtech]a, dw02: ~w[ieee dw02 dware]a, dw03: ~w[std synopsys dware dw03 dw02 dw01 ieee gtech]a, dw04: ~w[dw04 ieee dw01 dware gtech]a, dw05: ~w[dw05 ieee dware]a, dw06: ~w[dw06 ieee dware]a, dw07: ~w[ieee dware]a, dware: ~w[ieee dware]a, gtech: ~w[ieee gtech]a, ramlib: ~w[std ieee]a, std_cell_lib: ~w[ieee std_cell_lib]a, synopsys: [] ] Topological.sort(libraries)   IO.puts "" bad_libraries = Keyword.update!(libraries, :dw01, &[:dw04 | &1]) Topological.sort(bad_libraries)
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.
#Kotlin
Kotlin
// version 1.2.10   enum class Dir { LEFT, RIGHT, STAY }   class Rule( val state1: String, val symbol1: Char, val symbol2: Char, val dir: Dir, val state2: String )   class Tape( var symbol: Char, var left: Tape? = null, var right: Tape? = null )   class Turing( val states: List<String>, val finalStates: List<String>, val symbols: CharArray, val blank: Char, var state: String, tapeInput: CharArray, rules: List<Rule> ) { var tape: Tape? = null val transitions = Array(states.size) { arrayOfNulls<Rule>(symbols.size) }   init { for (i in 0 until tapeInput.size) { move(Dir.RIGHT) tape!!.symbol = tapeInput[i] } if (tapeInput.size == 0) move(Dir.RIGHT) while (tape!!.left != null) tape = tape!!.left for (i in 0 until rules.size) { val rule = rules[i] transitions[stateIndex(rule.state1)][symbolIndex(rule.symbol1)] = rule } }   private fun stateIndex(state: String): Int { val i = states.indexOf(state) return if (i >= 0) i else 0 }   private fun symbolIndex(symbol: Char): Int { val i = symbols.indexOf(symbol) return if (i >= 0) i else 0 }   private fun move(dir: Dir) { val orig = tape when (dir) { Dir.RIGHT -> { if (orig != null && orig.right != null) { tape = orig.right } else { tape = Tape(blank) if (orig != null) { tape!!.left = orig orig.right = tape } } }   Dir.LEFT -> { if (orig != null && orig.left != null) { tape = orig.left } else { tape = Tape(blank) if (orig != null) { tape!!.right = orig orig.left = tape } } }   Dir.STAY -> {} } }   fun printState() { print("%-10s ".format(state)) var t = tape while (t!!.left != null ) t = t.left while (t != null) { if (t == tape) print("[${t.symbol}]") else print(" ${t.symbol} ") t = t.right } println() }   fun run(maxLines: Int = 20) { var lines = 0 while (true) { printState() for (finalState in finalStates) { if (finalState == state) return } if (++lines == maxLines) { println("(Only the first $maxLines lines displayed)") return } val rule = transitions[stateIndex(state)][symbolIndex(tape!!.symbol)] tape!!.symbol = rule!!.symbol2 move(rule.dir) state = rule.state2 } } }   fun main(args: Array<String>) { println("Simple incrementer") Turing( states = listOf("q0", "qf"), finalStates = listOf("qf"), symbols = charArrayOf('B', '1'), blank = 'B', state = "q0", tapeInput = charArrayOf('1', '1', '1'), rules = listOf( Rule("q0", '1', '1', Dir.RIGHT, "q0"), Rule("q0", 'B', '1', Dir.STAY, "qf") ) ).run()   println("\nThree-state busy beaver") Turing( states = listOf("a", "b", "c", "halt"), finalStates = listOf("halt"), symbols = charArrayOf('0', '1'), blank = '0', state = "a", tapeInput = charArrayOf(), rules = listOf( Rule("a", '0', '1', Dir.RIGHT, "b"), Rule("a", '1', '1', Dir.LEFT, "c"), Rule("b", '0', '1', Dir.LEFT, "a"), Rule("b", '1', '1', Dir.RIGHT, "b"), Rule("c", '0', '1', Dir.LEFT, "b"), Rule("c", '1', '1', Dir.STAY, "halt") ) ).run()   println("\nFive-state two-symbol probable busy beaver") Turing( states = listOf("A", "B", "C", "D", "E", "H"), finalStates = listOf("H"), symbols = charArrayOf('0', '1'), blank = '0', state = "A", tapeInput = charArrayOf(), rules = listOf( Rule("A", '0', '1', Dir.RIGHT, "B"), Rule("A", '1', '1', Dir.LEFT, "C"), Rule("B", '0', '1', Dir.RIGHT, "C"), Rule("B", '1', '1', Dir.RIGHT, "B"), Rule("C", '0', '1', Dir.RIGHT, "D"), Rule("C", '1', '0', Dir.LEFT, "E"), Rule("D", '0', '1', Dir.LEFT, "A"), Rule("D", '1', '1', Dir.LEFT, "D"), Rule("E", '0', '1', Dir.STAY, "H"), Rule("E", '1', '0', Dir.LEFT, "A") ) ).run() }
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).
#Java
Java
  public class TotientFunction {   public static void main(String[] args) { computePhi(); System.out.println("Compute and display phi for the first 25 integers."); System.out.printf("n Phi IsPrime%n"); for ( int n = 1 ; n <= 25 ; n++ ) { System.out.printf("%2d  %2d  %b%n", n, phi[n], (phi[n] == n-1)); } for ( int i = 2 ; i < 8 ; i++ ) { int max = (int) Math.pow(10, i); System.out.printf("The count of the primes up to %,10d = %d%n", max, countPrimes(1, max)); } }   private static int countPrimes(int min, int max) { int count = 0; for ( int i = min ; i <= max ; i++ ) { if ( phi[i] == i-1 ) { count++; } } return count; }   private static final int max = 10000000; private static final int[] phi = new int[max+1];   private static final void computePhi() { for ( int i = 1 ; i <= max ; i++ ) { phi[i] = i; } for ( int i = 2 ; i <= max ; i++ ) { if (phi[i] < i) continue; for ( int j = i ; j <= max ; j += i ) { phi[j] -= phi[j] / i; } } }   }  
http://rosettacode.org/wiki/Topswops
Topswops
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is composed of reversing the first   m   cards where   m   is the value of the topmost card. Rounds are repeated until the topmost card is the number   1   and the number of swaps is recorded. For our example the swaps produce: [2, 4, 1, 3] # Initial shuffle [4, 2, 1, 3] [3, 1, 2, 4] [2, 1, 3, 4] [1, 2, 3, 4] For a total of four swaps from the initial ordering to produce the terminating case where   1   is on top. For a particular number   n   of cards,   topswops(n)   is the maximum swaps needed for any starting permutation of the   n   cards. Task The task is to generate and show here a table of   n   vs   topswops(n)   for   n   in the range   1..10   inclusive. Note Topswops   is also known as   Fannkuch   from the German word   Pfannkuchen   meaning   pancake. Related tasks   Number reversal game   Sorting algorithms/Pancake sort
#Python
Python
>>> from itertools import permutations >>> def f1(p): i = 0 while True: p0 = p[0] if p0 == 1: break p[:p0] = p[:p0][::-1] i += 1 return i   >>> def fannkuch(n): return max(f1(list(p)) for p in permutations(range(1, n+1)))   >>> for n in range(1, 11): print(n,fannkuch(n))   1 0 2 1 3 2 4 4 5 7 6 10 7 16 8 22 9 30 10 38 >>>
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.
#Erlang
Erlang
  Deg=45. Rad=math:pi()/4.   math:sin(Deg * math:pi() / 180)==math:sin(Rad).  
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).
#M2000_Interpreter
M2000 Interpreter
  Module Input11 { Flush ' empty stack For I=1 to 11 { Input "Give me a number ", a Data a ' add to bottom of stack, use: Push a to add to top, to get reverse order here } } Module Run { Print "Trabb Pardo–Knuth algorithm" Print "f(x)=Sqrt(Abs(x))+5*x^3" if not match("NNNNNNNNN") then Error "Need 11 numbers" Shiftback 1, -11 ' reverse order 11 elements of stack of values Def f(x)=Sqrt(Abs(x))+5*x^3 For i=1 to 11 { Read pop y=f(pop) if y>400 Then { Print format$("f({0}) = Overflow!", pop) } Else { Print format$("f({0}) = {1}", pop, y) } } } Run 10, -1, 1, 2, 3, 4, 4.3, 4.305, 4.303, 4.302, 4.301 Run 1, 2, 3, -4.55,5.1111, 6, -7, 8, 9, 10, 11 Input11 Run  
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).
#Maple
Maple
seqn := ListTools:-Reverse([parse(Maplets[Display](Maplets:-Elements:-Maplet(Maplets:-Elements:-InputDialog['ID1']("Enter a sequence of numbers separated by comma", 'onapprove' = Maplets:-Elements:-Shutdown(['ID1']), 'oncancel' = Maplets:-Elements:-Shutdown())))[1])]): f:= x -> abs(x)^0.5 + 5*x^3: for item in seqn do result := f(item): if (result > 400) then print("Alert: Overflow."): else print(result): end if: end do:
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).
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
numbers=RandomReal[{-2,6},11] tpk[numbers_,overflowVal_]:=Module[{revNumbers}, revNumbers=Reverse[numbers]; f[x_]:=Abs[x]^0.5+5 x^3; Do[ If[f[i]>overflowVal, Print["f[",i,"]= Overflow"] , Print["f[",i,"]= ",f[i]] ] , {i,revNumbers} ] ] tpk[numbers,400]
http://rosettacode.org/wiki/Truth_table
Truth table
A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function. Task Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function. (One can assume that the user input is correct). Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function. Either reverse-polish or infix notation expressions are allowed. Related tasks   Boolean values   Ternary logic See also   Wolfram MathWorld entry on truth tables.   some "truth table" examples from Google.
#Rust
Rust
use std::{ collections::HashMap, fmt::{Display, Formatter}, iter::FromIterator, };   // Generic expression evaluation automaton and expression formatting support   #[derive(Clone, Debug)] pub enum EvaluationError<T> { NoResults, TooManyResults, OperatorFailed(T), }   pub trait Operator<T> { type Err;   fn execute(&self, stack: &mut Vec<T>) -> Result<(), Self::Err>; }   #[derive(Clone, Copy, Debug)] enum Element<O> { Operator(O), Variable(usize), }   #[derive(Clone, Debug)] pub struct Expression<O> { elements: Vec<Element<O>>, symbols: Vec<String>, }   impl<O> Expression<O> { pub fn evaluate<T>( &self, mut bindings: impl FnMut(usize) -> T, ) -> Result<T, EvaluationError<O::Err>> where O: Operator<T>, { let mut stack = Vec::new();   for element in self.elements.iter() { match element { Element::Variable(index) => stack.push(bindings(*index)), Element::Operator(op) => op .execute(&mut stack) .map_err(EvaluationError::OperatorFailed)?, } }   match stack.pop() { Some(result) if stack.is_empty() => Ok(result), Some(_) => Err(EvaluationError::TooManyResults), None => Err(EvaluationError::NoResults), } }   pub fn symbols(&self) -> &[String] { &self.symbols }   pub fn formatted(&self) -> Result<String, EvaluationError<O::Err>> where O: Operator<Formatted>, { self.evaluate(|index| Formatted(self.symbols[index].clone())) .map(|formatted| formatted.0) } }   #[derive(Clone, Debug)] pub struct Formatted(pub String);   impl Display for Formatted { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } }   impl<O> Display for Expression<O> where O: Operator<Formatted>, { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self.formatted() { Ok(result) => write!(f, "{}", result), Err(_) => write!(f, "<malformed expression>"), } } }   // Generic parts of the parsing machinery   #[derive(Clone, Copy, Debug)] pub enum Token<'a, O> { LBrace, RBrace, Operator(O), Variable(&'a str), Malformed(&'a str), }   pub type Symbol<'a, O> = (&'a str, bool, Token<'a, O>);   #[derive(Debug)] pub struct Tokens<'a, O> { source: &'a str, symbols: &'a [Symbol<'a, O>], }   impl<'a, O> Tokens<'a, O> { pub fn new(source: &'a str, symbols: &'a [Symbol<'a, O>]) -> Self { Self { source, symbols } } }   impl<'a, O: Clone> Iterator for Tokens<'a, O> { type Item = Token<'a, O>;   fn next(&mut self) -> Option<Self::Item> { self.source = self.source.trim_start();   let symbol = self.symbols.iter().find_map(|(symbol, word, token)| { if self.source.starts_with(symbol) { let end = symbol.len();   if *word { match &self.source[end..].chars().next() { Some(c) if !c.is_whitespace() => return None, _ => (), } }   Some((token, end)) } else { None } });   if let Some((token, end)) = symbol { self.source = &self.source[end..]; Some(token.clone()) } else { match self.source.chars().next() { Some(c) if c.is_alphabetic() => { let end = self .source .char_indices() .find_map(|(i, c)| Some(i).filter(|_| !c.is_alphanumeric())) .unwrap_or_else(|| self.source.len());   let result = &self.source[0..end]; self.source = &self.source[end..]; Some(Token::Variable(result)) }   Some(c) => { let end = c.len_utf8(); let result = &self.source[0..end]; self.source = &self.source[end..]; Some(Token::Malformed(result)) }   None => None, } } } }   pub trait WithPriority { type Priority;   fn priority(&self) -> Self::Priority; }   impl<'a, O> FromIterator<Token<'a, O>> for Result<Expression<O>, Token<'a, O>> where O: WithPriority, O::Priority: Ord, { fn from_iter<T: IntoIterator<Item = Token<'a, O>>>(tokens: T) -> Self { let mut token_stack = Vec::new(); let mut indices = HashMap::new(); let mut symbols = Vec::new(); let mut elements = Vec::new();   'outer: for token in tokens { match token { Token::Malformed(_) => return Err(token), Token::LBrace => token_stack.push(token), Token::RBrace => { // Flush all operators to the matching LBrace while let Some(token) = token_stack.pop() { match token { Token::LBrace => continue 'outer, Token::Operator(op) => elements.push(Element::Operator(op)), _ => return Err(token), } } }   Token::Variable(name) => { let index = indices.len(); let symbol = name.to_string(); let index = *indices.entry(symbol.clone()).or_insert_with(|| { symbols.push(symbol); index });   elements.push(Element::Variable(index)); }   Token::Operator(ref op) => { while let Some(token) = token_stack.pop() { match token { Token::Operator(pop) if op.priority() < pop.priority() => { elements.push(Element::Operator(pop)); }   Token::Operator(pop) => { token_stack.push(Token::Operator(pop)); break; }   _ => { token_stack.push(token); break; } } }   token_stack.push(token); } } }   // Handle leftovers while let Some(token) = token_stack.pop() { match token { Token::Operator(op) => elements.push(Element::Operator(op)), _ => return Err(token), } }   Ok(Expression { elements, symbols }) } }   // Definition of Boolean operators   #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Boolean { Or, Xor, And, Not, }   impl Display for Boolean { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let s = match self { Self::Or => "∨", Self::And => "∧", Self::Not => "¬", Self::Xor => "⩛", };   write!(f, "{}", s) } }   impl WithPriority for Boolean { type Priority = u8;   fn priority(&self) -> u8 { match self { Self::Or => 0, Self::Xor => 1, Self::And => 2, Self::Not => 3, } } }   #[derive(Clone, Debug)] pub enum BooleanError { StackUnderflow, }   impl Operator<bool> for Boolean { type Err = BooleanError;   fn execute(&self, stack: &mut Vec<bool>) -> Result<(), Self::Err> { let mut pop = || stack.pop().ok_or(BooleanError::StackUnderflow);   let result = match self { Boolean::Or => pop()? | pop()?, Boolean::And => pop()? & pop()?, Boolean::Xor => pop()? ^ pop()?, Boolean::Not => !pop()?, };   stack.push(result); Ok(()) } }   impl Operator<Formatted> for Boolean { type Err = BooleanError;   fn execute(&self, stack: &mut Vec<Formatted>) -> Result<(), Self::Err> { let mut pop = || stack.pop().ok_or(BooleanError::StackUnderflow);   let result = match self { Boolean::Not => format!("{}{}", Boolean::Not, pop()?),   binary_operator => { // The stack orders the operands backwards, so to format them // properly, we have to count with the reversed popping order let b = pop()?; let a = pop()?; format!("({} {} {})", a, binary_operator, b) } };   stack.push(Formatted(result)); Ok(()) } }   impl Boolean { // It is important for the tokens to be ordered by their parsing priority (if // some operator was a prefix of another operator, the prefix must come later) const SYMBOLS: [Symbol<'static, Boolean>; 18] = [ ("(", false, Token::LBrace), (")", false, Token::RBrace), ("|", false, Token::Operator(Boolean::Or)), ("∨", false, Token::Operator(Boolean::Or)), ("or", true, Token::Operator(Boolean::Or)), ("OR", true, Token::Operator(Boolean::Or)), ("&", false, Token::Operator(Boolean::And)), ("∧", false, Token::Operator(Boolean::And)), ("and", true, Token::Operator(Boolean::And)), ("AND", true, Token::Operator(Boolean::And)), ("!", false, Token::Operator(Boolean::Not)), ("¬", false, Token::Operator(Boolean::Not)), ("not", true, Token::Operator(Boolean::Not)), ("NOT", true, Token::Operator(Boolean::Not)), ("^", false, Token::Operator(Boolean::Xor)), ("⩛", false, Token::Operator(Boolean::Xor)), ("xor", true, Token::Operator(Boolean::Xor)), ("XOR", true, Token::Operator(Boolean::Xor)), ];   pub fn tokenize(s: &str) -> Tokens<'_, Boolean> { Tokens::new(s, &Self::SYMBOLS) }   pub fn parse<'a>(s: &'a str) -> Result<Expression<Boolean>, Token<'a, Boolean>> { Self::tokenize(s).collect() } }   // Finally the table printing   fn print_truth_table(s: &str) -> Result<(), std::borrow::Cow<'_, str>> { let expression = Boolean::parse(s).map_err(|e| format!("Parsing failed at token {:?}", e))?;   let formatted = expression .formatted() .map_err(|_| "Malformed expression detected.")?;   let var_count = expression.symbols().len(); if var_count > 64 { return Err("Too many variables to list.".into()); }   let column_widths = { // Print header and compute the widths of columns let mut widths = Vec::with_capacity(var_count);   for symbol in expression.symbols() { print!("{} ", symbol); widths.push(symbol.chars().count() + 2); // Include spacing }   println!("{}", formatted); let width = widths.iter().sum::<usize>() + formatted.chars().count(); (0..width).for_each(|_| print!("-")); println!();   widths };   // Choose the bit extraction order for the more traditional table ordering let var_value = |input, index| (input >> (var_count - 1 - index)) & 1 ^ 1; // Use counter to enumerate all bit combinations for var_values in 0u64..(1 << var_count) { for (var_index, width) in column_widths.iter().enumerate() { let value = var_value(var_values, var_index); print!("{:<width$}", value, width = width); }   match expression.evaluate(|var_index| var_value(var_values, var_index) == 1) { Ok(result) => println!("{}", if result { "1" } else { "0" }), Err(e) => println!("{:?}", e), } }   println!(); Ok(()) }   fn main() { loop { let input = { println!("Enter the expression to parse (or nothing to quit):"); let mut input = String::new(); std::io::stdin().read_line(&mut input).unwrap(); println!(); input };   if input.trim().is_empty() { break; }   if let Err(e) = print_truth_table(&input) { eprintln!("{}\n", e); } } }
http://rosettacode.org/wiki/Ulam_spiral_(for_primes)
Ulam spiral (for primes)
An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is shown with sequential integers,   starting at   1. In an Ulam spiral of primes, only the primes are shown (usually indicated by some glyph such as a dot or asterisk),   and all non-primes as shown as a blank   (or some other whitespace). Of course, the grid and border are not to be displayed (but they are displayed here when using these Wiki HTML tables). Normally, the spiral starts in the "center",   and the   2nd   number is to the viewer's right and the number spiral starts from there in a counter-clockwise direction. There are other geometric shapes that are used as well, including clock-wise spirals. Also, some spirals (for the   2nd   number)   is viewed upwards from the   1st   number instead of to the right, but that is just a matter of orientation. Sometimes, the starting number can be specified to show more visual striking patterns (of prime densities). [A larger than necessary grid (numbers wise) is shown here to illustrate the pattern of numbers on the diagonals   (which may be used by the method to orientate the direction of spiral-construction algorithm within the example computer programs)]. Then, in the next phase in the transformation of the Ulam prime spiral,   the non-primes are translated to blanks. In the orange grid below,   the primes are left intact,   and all non-primes are changed to blanks. Then, in the final transformation of the Ulam spiral (the yellow grid),   translate the primes to a glyph such as a   •   or some other suitable glyph. 65 64 63 62 61 60 59 58 57 66 37 36 35 34 33 32 31 56 67 38 17 16 15 14 13 30 55 68 39 18 5 4 3 12 29 54 69 40 19 6 1 2 11 28 53 70 41 20 7 8 9 10 27 52 71 42 21 22 23 24 25 26 51 72 43 44 45 46 47 48 49 50 73 74 75 76 77 78 79 80 81 61 59 37 31 67 17 13 5 3 29 19 2 11 53 41 7 71 23 43 47 73 79 • • • • • • • • • • • • • • • • • • • • • • The Ulam spiral becomes more visually obvious as the grid increases in size. Task For any sized   N × N   grid,   construct and show an Ulam spiral (counter-clockwise) of primes starting at some specified initial number   (the default would be 1),   with some suitably   dotty   (glyph) representation to indicate primes,   and the absence of dots to indicate non-primes. You should demonstrate the generator by showing at Ulam prime spiral large enough to (almost) fill your terminal screen. Related tasks   Spiral matrix   Zig-zag matrix   Identity matrix   Sequence of primes by Trial Division See also Wikipedia entry:   Ulam spiral MathWorld™ entry:   Prime Spiral
#Tcl
Tcl
proc is_prime {n} { if {$n == 1} {return 0} if {$n in {2 3 5}} {return 1} for {set i 2} {$i*$i <= $n} {incr i} { if {$n % $i == 0} {return 0} } return 1 }   proc spiral {w h} { yield [info coroutine] set x [expr {$w / 2}] set y [expr {$h / 2}] set n 1 set dir 0 set steps 1 set step 1 while {1} { yield [list $x $y] switch $dir { 0 {incr x} 1 {incr y -1} 2 {incr x -1} 3 {incr y} } if {![incr step -1]} { set dir [expr {($dir+1)%4}] if {$dir % 2 == 0} { incr steps } set step $steps } } }   set radius 16 set side [expr {1 + 2 * $radius}] set n [expr {$side * $side}] set cells [lrepeat $side [lrepeat $side ""]] set i 1   coroutine spin spiral $side $side   while {$i < $n} { lassign [spin] y x set c [expr {[is_prime $i] ? "\u169b" : " "}] lset cells $x $y $c incr i }   puts [join [lmap row $cells {join $row " "}] \n]
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.]
#ooRexx
ooRexx
  -- find largest left- & right-truncatable primes < 1 million. -- an initial set of primes (not, at this time, we leave out 2 because -- we'll automatically skip the even numbers. No point in doing a needless -- test each time through primes = .array~of(3, 5, 7, 11)   -- check all of the odd numbers up to 1,000,000 loop j = 13 by 2 to 1000000 loop i = 1 to primes~size prime = primes[i] -- found an even prime divisor if j // prime == 0 then iterate j -- only check up to the square root if prime*prime > j then leave end -- we only get here if we don't find a divisor primes~append(j) end   -- get a set of the primes that we can test more efficiently primeSet = .set~of(2) primeSet~putall(primes)     say 'The last prime is' primes[primes~last] "("primeSet~items 'primes under one million).' say copies('-',66)   lastLeft = 0   -- we're going to use the array version to do these in order. We're still -- missing "2", but that's not going to be the largest loop prime over primes   -- values containing 0 can never work if prime~pos(0) \= 0 then iterate -- now start the truncations, checking against our set of -- known primes loop i = 1 for prime~length - 1 subprime = prime~right(i) -- not in our known set, this can't work if \primeset~hasIndex(subprime) then iterate prime end -- this, by definition, with be the largest left-trunc prime lastLeft = prime end -- now look for right-trunc primes lastRight = 0 loop prime over primes   -- values containing 0 can never work if prime~pos(0) \= 0 then iterate -- now start the truncations, checking against our set of -- known primes loop i = 1 for prime~length - 1 subprime = prime~left(i) -- not in our known set, this can't work if \primeset~hasIndex(subprime) then iterate prime end -- this, by definition, with be the largest left-trunc prime lastRight = prime end   say 'The largest left-truncatable prime is' lastLeft '(under one million).' say 'The largest right-truncatable prime is' lastRight '(under one million).'    
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.
#CLU
CLU
bintree = cluster [T: type] is leaf, node, pre_order, post_order, in_order, level_order branch = struct[left, right: bintree[T], val: T] rep = oneof[br: branch, leaf: null]   leaf = proc () returns (cvt) return(rep$make_leaf(nil)) end leaf   node = proc (val: T, l,r: cvt) returns (cvt) return(rep$make_br(branch${left:up(l), right:up(r), val:val})) end node   pre_order = iter (n: cvt) yields (T) tagcase n tag br (b: branch): yield(b.val) for v: T in pre_order(b.left) do yield(v) end for v: T in pre_order(b.right) do yield(v) end tag leaf: end end pre_order   in_order = iter (n: cvt) yields (T) tagcase n tag br (b: branch): for v: T in in_order(b.left) do yield(v) end yield(b.val) for v: T in in_order(b.right) do yield(v) end tag leaf: end end in_order   post_order = iter (n: cvt) yields (T) tagcase n tag br (b: branch): for v: T in post_order(b.left) do yield(v) end for v: T in post_order(b.right) do yield(v) end yield(b.val) tag leaf: end end post_order   level_order = iter (n: cvt) yields (T) bfs: array[rep] := array[rep]$[n] while ~array[rep]$empty(bfs) do cur: rep := array[rep]$reml(bfs) tagcase cur tag br (b: branch): yield(b.val) array[rep]$addh(bfs,down(b.left)) array[rep]$addh(bfs,down(b.right)) tag leaf: end end end level_order end bintree   start_up = proc () bt = bintree[int]   po: stream := stream$primary_output() tree: bt := bt$node(1, bt$node(2, bt$node(4, bt$node(7, bt$leaf(), bt$leaf()), bt$leaf()), bt$node(5, bt$leaf(), bt$leaf())), bt$node(3, bt$node(6, bt$node(8, bt$leaf(), bt$leaf()), bt$node(9, bt$leaf(), bt$leaf())), bt$leaf()))   stream$puts(po, "preorder: ") for i: int in bt$pre_order(tree) do stream$puts(po, " " || int$unparse(i)) end   stream$puts(po, "\ninorder: ") for i: int in bt$in_order(tree) do stream$puts(po, " " || int$unparse(i)) end   stream$puts(po, "\npostorder: ") for i: int in bt$post_order(tree) do stream$puts(po, " " || int$unparse(i)) end   stream$puts(po, "\nlevel-order:") for i: int in bt$level_order(tree) do stream$puts(po, " " || int$unparse(i)) end end start_up
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
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program strTokenize.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall   .equ NBPOSTESECLAT, 20   /* Initialized data */ .data szMessFinal: .asciz "Words are : \n"   szString: .asciz "Hello,How,Are,You,Today" szMessError: .asciz "Error tokenize !!\n" szCarriageReturn: .asciz "\n"   /* UnInitialized data */ .bss   /* code section */ .text .global main main: ldr r0,iAdrszString @ string address mov r1,#',' @ separator bl stTokenize cmp r0,#-1 @ error ? beq 99f mov r2,r0 @ table address ldr r0,iAdrszMessFinal @ display message bl affichageMess ldr r4,[r2] @ number of areas add r2,#4 @ first area mov r3,#0 @ loop counter 1: @ display loop ldr r0,[r2,r3, lsl #2] @ address area bl affichageMess ldr r0,iAdrszCarriageReturn @ display carriage return bl affichageMess add r3,#1 @ counter + 1 cmp r3,r4 @ end ? blt 1b @ no -> loop   b 100f 99: @ display error message ldr r0,iAdrszMessError bl affichageMess   100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc 0 @ perform the system call iAdrszString: .int szString iAdrszFinalString: .int szFinalString iAdrszMessFinal: .int szMessFinal iAdrszMessError: .int szMessError iAdrszCarriageReturn: .int szCarriageReturn /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {r0,r1,r2,r7,lr} @ save registers mov r2,#0 @ counter length */ 1: @ loop length calculation ldrb r1,[r0,r2] @ read octet start position + index cmp r1,#0 @ if 0 its over addne r2,r2,#1 @ else add 1 in the length bne 1b @ and loop @ so here r2 contains the length of the message mov r1,r0 @ address message in r1 mov r0,#STDOUT @ code to write to the standard output Linux mov r7, #WRITE @ code call system "write" svc #0 @ call systeme pop {r0,r1,r2,r7,lr} @ restaur des 2 registres bx lr @ return /*******************************************************************/ /* Separate string by separator into an array */ /* areas are store on the heap Linux */ /*******************************************************************/ /* r0 contains string address */ /* r1 contains separator character (, or . or : ) */ /* r0 returns table address with first item = number areas */ /* and other items contains pointer of each string */ stTokenize: push {r1-r8,lr} @ save des registres mov r6,r0 mov r8,r1 @ save separator bl strLength @ length string for place reservation on the heap mov r4,r0 ldr r5,iTailleTable add r5,r0 and r5,#0xFFFFFFFC add r5,#4 @ align word on the heap @ place reservation on the heap mov r0,#0 @ heap address mov r7, #0x2D @ call system linux 'brk' svc #0 @ call system cmp r0,#-1 @ error call system beq 100f mov r3,r0 @ save address heap begin add r0,r5 @ reserve r5 byte on the heap mov r7, #0x2D @ call system linux 'brk' svc #0 cmp r0,#-1 beq 100f @ string copy on the heap mov r0,r6 mov r1,r3 1: @ loop copy string ldrb r2,[r0],#1 @ read one byte and increment pointer one byte strb r2,[r1],#1 @ store one byte and increment pointer one byte cmp r2,#0 @ end of string ? bne 1b @ no -> loop   add r4,r3 @ r4 contains address table begin mov r0,#0 str r0,[r4] str r3,[r4,#4] mov r2,#1 @ areas counter 2: @ loop load string character ldrb r0,[r3] cmp r0,#0 beq 3f @ end string cmp r0,r8 @ separator ? addne r3,#1 @ no -> next location bne 2b @ and loop mov r0,#0 @ store zero final of string strb r0,[r3] add r3,#1 @ next character add r2,#1 @ areas counter + 1 str r3,[r4,r2, lsl #2] @ store address area in the table at index r2 b 2b @ and loop   3: str r2,[r4] @ returns number areas mov r0,r4 100: pop {r1-r8,lr} bx lr iTailleTable: .int 4 * NBPOSTESECLAT /***************************************************/ /* calcul size string */ /***************************************************/ /* r0 string address */ /* r0 returns size string */ strLength: push {r1,r2,lr} mov r1,#0 @ init counter 1: ldrb r2,[r0,r1] @ load byte of string index r1 cmp r2,#0 @ end string ? addne r1,#1 @ no -> +1 counter bne 1b @ and loop   100: mov r0,r1 pop {r1,r2,lr} bx lr    
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.
#Ada
Ada
with Ada.Calendar; use Ada.Calendar; with Ada.Text_Io; use Ada.Text_Io;   procedure Query_Performance is type Proc_Access is access procedure(X : in out Integer); function Time_It(Action : Proc_Access; Arg : Integer) return Duration is Start_Time : Time := Clock; Finis_Time : Time; Func_Arg : Integer := Arg; begin Action(Func_Arg); Finis_Time := Clock; return Finis_Time - Start_Time; end Time_It; procedure Identity(X : in out Integer) is begin X := X; end Identity; procedure Sum (Num : in out Integer) is begin for I in 1..1000 loop Num := Num + I; end loop; end Sum; Id_Access : Proc_Access := Identity'access; Sum_Access : Proc_Access := Sum'access;   begin Put_Line("Identity(4) takes" & Duration'Image(Time_It(Id_Access, 4)) & " seconds."); Put_Line("Sum(4) takes:" & Duration'Image(Time_It(Sum_Access, 4)) & " seconds."); end Query_Performance;
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.
#Aime
Aime
integer identity(integer x) { x; }     integer sum(integer c) { integer s;   s = 0; while (c) { s += c; c -= 1; }   s; }     real time_f(integer (*fp)(integer), integer fa) { date f, s; time t;   s.now;   fp(fa);   f.now;   t.ddiff(f, s);   t.microsecond / 1000000r; }     integer main(void) { o_real(6, time_f(identity, 1)); o_text(" seconds\n"); o_real(6, time_f(sum, 1000000)); o_text(" seconds\n");   0; }
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
#C.2B.2B
C++
#include <string> #include <set> #include <list> #include <map> #include <iostream>     struct Employee { std::string Name; std::string ID; unsigned long Salary; std::string Department; Employee(std::string _Name = "", std::string _ID = "", unsigned long _Salary = 0, std::string _Department = "") : Name(_Name), ID(_ID), Salary(_Salary), Department(_Department) { }   void display(std::ostream& out) const { out << Name << "\t" << ID << "\t" << Salary << "\t" << Department << std::endl; } };   // We'll tell std::set to use this to sort our employees. struct CompareEarners { bool operator()(const Employee& e1, const Employee& e2) { return (e1.Salary > e2.Salary); } };   // A few typedefs to make the code easier to type, read and maintain. typedef std::list<Employee> EMPLOYEELIST;   // Notice the CompareEarners; We're telling std::set to user our specified comparison mechanism // to sort its contents. typedef std::set<Employee, CompareEarners> DEPARTMENTPAYROLL;   typedef std::map<std::string, DEPARTMENTPAYROLL> DEPARTMENTLIST;   void initialize(EMPLOYEELIST& Employees) { // Initialize our employee list data source. Employees.push_back(Employee("Tyler Bennett", "E10297", 32000, "D101")); Employees.push_back(Employee("John Rappl", "E21437", 47000, "D050")); Employees.push_back(Employee("George Woltman", "E21437", 53500, "D101")); Employees.push_back(Employee("Adam Smith", "E21437", 18000, "D202")); Employees.push_back(Employee("Claire Buckman", "E39876", 27800, "D202")); Employees.push_back(Employee("David McClellan", "E04242", 41500, "D101")); Employees.push_back(Employee("Rich Holcomb", "E01234", 49500, "D202")); Employees.push_back(Employee("Nathan Adams", "E41298", 21900, "D050")); Employees.push_back(Employee("Richard Potter", "E43128", 15900, "D101")); Employees.push_back(Employee("David Motsinger", "E27002", 19250, "D202")); Employees.push_back(Employee("Tim Sampair", "E03033", 27000, "D101")); Employees.push_back(Employee("Kim Arlich", "E10001", 57000, "D190")); Employees.push_back(Employee("Timothy Grove", "E16398", 29900, "D190")); }   void group(EMPLOYEELIST& Employees, DEPARTMENTLIST& Departments) { // Loop through all of our employees. for( EMPLOYEELIST::iterator iEmployee = Employees.begin(); Employees.end() != iEmployee; ++iEmployee ) { DEPARTMENTPAYROLL& groupSet = Departments[iEmployee->Department];   // Add our employee to this group. groupSet.insert(*iEmployee); } }   void present(DEPARTMENTLIST& Departments, unsigned int N) { // Loop through all of our departments for( DEPARTMENTLIST::iterator iDepartment = Departments.begin(); Departments.end() != iDepartment; ++iDepartment ) { std::cout << "In department " << iDepartment->first << std::endl; std::cout << "Name\t\tID\tSalary\tDepartment" << std::endl; // Get the top three employees for each employee unsigned int rank = 1; for( DEPARTMENTPAYROLL::iterator iEmployee = iDepartment->second.begin(); ( iDepartment->second.end() != iEmployee) && (rank <= N); ++iEmployee, ++rank ) { iEmployee->display(std::cout); } std::cout << std::endl; } }   int main(int argc, char* argv[]) { // Our container for our list of employees. EMPLOYEELIST Employees;   // Fill our list of employees initialize(Employees);   // Our departments. DEPARTMENTLIST Departments;   // Sort our employees into their departments. // This will also rank them. group(Employees, Departments);   // Display the top 3 earners in each department. present(Departments, 3);   return 0; }
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.
#ALGOL_W
ALGOL W
begin   string(10) board;    % initialise the board  % procedure initBoard ; board := " 123456789";    % display the board  % procedure showBoard ; begin s_w := 0; write( board(1//1), "|", board(2//1), "|", board(3//1) ); write( "-+-+-" ); write( board(4//1), "|", board(5//1), "|", board(6//1) ); write( "-+-+-" ); write( board(7//1), "|", board(8//1), "|", board(9//1) ) end showBoard ;    % returns true if board pos is free, false otherwise  % logical procedure freeSpace( integer value pos ) ; ( board(pos//1) >= "1" and board(pos//1) <= "9" );    % check for game over  % logical procedure gameOver ; begin logical noMoves; noMoves := true; for i := 1 until 9 do if noMoves then noMoves := not freeSpace( i ); noMoves end gameOver ;    % makes the specified winning move or blocks it, if it will win  % logical procedure winOrBlock( integer value pos1, pos2, pos3  ; string(1) value searchCharacter  ; string(1) value playerCharacter ) ; if board(pos1//1) = searchCharacter and board(pos2//1) = searchCharacter and freeSpace( pos3 ) then begin board(pos3//1) := playerCharacter; true end else if board(pos1//1) = searchCharacter and freeSpace( pos2 ) and board(pos3//1) = searchCharacter then begin board(pos2//1) := playerCharacter; true end else if freeSpace( pos1 ) and board(pos2//1) = searchCharacter and board(pos3//1) = searchCharacter then begin board(pos1//1) := playerCharacter; true end else begin false end winOrBlock ;    % makes a winning move or blocks a winning move, if there is one  % logical procedure makeOrBlockWinningMove( string(1) value searchCharacter  ; string(1) value playerCharacter ) ; ( winOrBlock( 1, 2, 3, searchCharacter, playerCharacter ) or winOrBlock( 4, 5, 6, searchCharacter, playerCharacter ) or winOrBlock( 7, 8, 9, searchCharacter, playerCharacter ) or winOrBlock( 1, 4, 7, searchCharacter, playerCharacter ) or winOrBlock( 2, 5, 8, searchCharacter, playerCharacter ) or winOrBlock( 3, 6, 9, searchCharacter, playerCharacter ) or winOrBlock( 1, 5, 9, searchCharacter, playerCharacter ) or winOrBlock( 3, 5, 7, searchCharacter, playerCharacter ) ) ;    % makes a move when there isn't an obvious winning/blocking move  % procedure move ( string(1) value playerCharacter ) ; begin logical moved; moved := false;  % try for the centre, a corner or the midle of a line  % for pos := 5, 1, 3, 7, 9, 2, 4, 6, 8 do begin if not moved and freeSpace( pos ) then begin moved := true; board(pos//1) := playerCharacter end end end move ;    % gets a move from the user  % procedure userMove( string(1) value playerCharacter ) ; begin integer move; while begin write( "Please enter the move for ", playerCharacter, " " ); read( move ); ( move < 1 or move > 9 or not freeSpace( move ) ) end do begin write( "Invalid move" ) end; board(move//1) := playerCharacter end userMove ;    % returns true if the three board positions have the player character,  %  % false otherwise  % logical procedure same( integer value pos1, pos2, pos3  ; string(1) value playerCharacter ) ; ( board(pos1//1) = playerCharacter and board(pos2//1) = playerCharacter and board(pos3//1) = playerCharacter );    % returns true if the player has made a winning move, false otherwise  % logical procedure playerHasWon( string(1) value playerCharacter ) ; ( same( 1, 2, 3, playerCharacter ) or same( 4, 5, 6, playerCharacter ) or same( 7, 8, 9, playerCharacter ) or same( 1, 4, 7, playerCharacter ) or same( 2, 5, 8, playerCharacter ) or same( 3, 6, 9, playerCharacter ) or same( 1, 5, 9, playerCharacter ) or same( 3, 5, 7, playerCharacter ) ) ;    % takes a players turn - either automated or user input  % procedure turn ( string(1) value playerCharacter, otherCharacter  ; logical value playerIsUser ) ; begin if playerIsUser then userMove( playerCharacter ) else begin write( playerCharacter, " moves..." ); if not makeOrBlockWinningMove( playerCharacter, playerCharacter ) and not makeOrBlockWinningMove( otherCharacter, playerCharacter ) then move( playerCharacter ) end; showBoard end turn ;    % asks a question and returns true if the user inputs y/Y,  %  % false otherwise  % logical procedure yes( string(32) value question ) ; begin string(1) answer; write( question ); read( answer ); answer = "y" or answer = "Y" end yes ;    % play the game  % while begin string(1) again; string(32) gameResult; logical oIsUser, xIsUser;   oIsUser := yes( "Do you want to play O? " ); xIsUser := yes( "Do you want to play X? " );   gameResult := "it's a draw"; initBoard; showBoard; while not gameOver and not playerHasWon( "O" ) and not playerHasWon( "X" ) do begin turn( "O", "X", oIsUser ); if playerHasWon( "O" ) then gameResult := "O wins" else if not gameOver then begin turn( "X", "O", xIsUser ); if playerHasWon( "X" ) then gameResult := "X wins" end end ; write( gameResult );   yes( "Play again? " ) end do begin end   end.
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#AutoHotkey
AutoHotkey
move(n, from, to, via) ;n = # of disks, from = start pole, to = end pole, via = remaining pole { if (n = 1) { msgbox , 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) } } move(64, 1, 3, 2)
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
#Draco
Draco
/* Find the N'th digit in the Thue-Morse sequence */ proc nonrec tm(word n) byte: word n2; n2 := n; while n2 ~= 0 do n2 := n2 >> 1; n := n >< n2 od; n & 1 corp   /* Print the first 64 digits */ proc nonrec main() void: byte i; for i from 0 upto 63 do write(tm(i):1) od corp
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
#Elena
Elena
import extensions; import system'text;   sequence(int steps) { var sb1 := TextBuilder.load("0"); var sb2 := TextBuilder.load("1"); for(int i := 0, i < steps, i += 1) { var tmp := sb1.Value; sb1.write(sb2); sb2.write(tmp) }; console.printLine(sb1).readLine() }   public program() { sequence(6) }
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
#Elixir
Elixir
Enum.reduce(0..6, '0', fn _,s -> IO.puts s s ++ Enum.map(s, fn c -> if c==?0, do: ?1, else: ?0 end) end)   # or Stream.iterate('0', fn s -> s ++ Enum.map(s, fn c -> if c==?0, do: ?1, else: ?0 end) end) |> Enum.take(7) |> Enum.each(&IO.puts/1)
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm
Tonelli-Shanks algorithm
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computational number theory, the Tonelli–Shanks algorithm is a technique for solving for x in a congruence of the form: x2 ≡ n (mod p) where n is an integer which is a quadratic residue (mod p), p is an odd prime, and x,n ∈ Fp where Fp = {0, 1, ..., p - 1}. It is used in cryptography techniques. To apply the algorithm, we need the Legendre symbol: The Legendre symbol (a | p) denotes the value of a(p-1)/2 (mod p). (a | p) ≡ 1    if a is a square (mod p) (a | p) ≡ -1    if a is not a square (mod p) (a | p) ≡ 0    if a ≡ 0 (mod p) Algorithm pseudo-code All ≡ are taken to mean (mod p) unless stated otherwise. Input: p an odd prime, and an integer n . Step 0: Check that n is indeed a square: (n | p) must be ≡ 1 . Step 1: By factoring out powers of 2 from p - 1, find q and s such that p - 1 = q2s with q odd . If p ≡ 3 (mod 4) (i.e. s = 1), output the two solutions r ≡ ± n(p+1)/4 . Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq . Step 3: Set r ≡ n(q+1)/2, t ≡ nq, m = s . Step 4: Loop the following: If t ≡ 1, output r and p - r . Otherwise find, by repeated squaring, the lowest i, 0 < i < m , such that t2i ≡ 1 . Let b ≡ c2(m - i - 1), and set r ≡ rb, t ≡ tb2, c ≡ b2 and m = i . Task Implement the above algorithm. Find solutions (if any) for n = 10 p = 13 n = 56 p = 101 n = 1030 p = 10009 n = 1032 p = 10009 n = 44402 p = 100049 Extra credit n = 665820697 p = 1000000009 n = 881398088036 p = 1000000000039 n = 41660815127637347468140745042827704103445750172002 p = 10^50 + 577 See also Modular exponentiation Cipolla's algorithm
#Nim
Nim
proc pow*[T: SomeInteger](x, n, p: T): T = var t = x mod p var e = n result = 1 while e > 0: if (e and 1) == 1: result = result * t mod p t = t * t mod p e = e shr 1   proc legendre*[T: SomeInteger](a, p: T): T = pow(a, (p-1) shr 1, p)   proc tonelliShanks*[T: SomeInteger](n, p: T): T = # Check that n is indeed a square. if legendre(n, p) != 1: raise newException(ValueError, "Not a square")   # Factor out power of 2 from p-1. var q = p - 1 var s = 0 while (q and 1) == 0: s += 1 q = q shr 1   if s == 1: return pow(n, (p+1) shr 2, p)   # Select a non-square z such as (z | p) = -1. var z = 2 while legendre(z, p) != p - 1: z += 1   var c = pow(z, q, p) t = pow(n, q, p) m = s result = pow(n, (q+1) shr 1, p) while t != 1: var i = 1 z = t * t mod p while z != 1 and i < m-1: i += 1 z = z * z mod p   var b = pow(c, 1 shl (m-i-1), p) c = b * b mod p t = t * c mod p m = i result = result * b mod p   when isMainModule: proc run(n, p: SomeInteger) = try: let r = tonelliShanks(n, p) echo r, " ", p-r except ValueError: echo getCurrentExceptionMsg()   run(10, 13) run(56, 101) run(1030, 10009) run(1032, 10009) run(44402, 100049) run(665820697, 1000000009)
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm
Tonelli-Shanks algorithm
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computational number theory, the Tonelli–Shanks algorithm is a technique for solving for x in a congruence of the form: x2 ≡ n (mod p) where n is an integer which is a quadratic residue (mod p), p is an odd prime, and x,n ∈ Fp where Fp = {0, 1, ..., p - 1}. It is used in cryptography techniques. To apply the algorithm, we need the Legendre symbol: The Legendre symbol (a | p) denotes the value of a(p-1)/2 (mod p). (a | p) ≡ 1    if a is a square (mod p) (a | p) ≡ -1    if a is not a square (mod p) (a | p) ≡ 0    if a ≡ 0 (mod p) Algorithm pseudo-code All ≡ are taken to mean (mod p) unless stated otherwise. Input: p an odd prime, and an integer n . Step 0: Check that n is indeed a square: (n | p) must be ≡ 1 . Step 1: By factoring out powers of 2 from p - 1, find q and s such that p - 1 = q2s with q odd . If p ≡ 3 (mod 4) (i.e. s = 1), output the two solutions r ≡ ± n(p+1)/4 . Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq . Step 3: Set r ≡ n(q+1)/2, t ≡ nq, m = s . Step 4: Loop the following: If t ≡ 1, output r and p - r . Otherwise find, by repeated squaring, the lowest i, 0 < i < m , such that t2i ≡ 1 . Let b ≡ c2(m - i - 1), and set r ≡ rb, t ≡ tb2, c ≡ b2 and m = i . Task Implement the above algorithm. Find solutions (if any) for n = 10 p = 13 n = 56 p = 101 n = 1030 p = 10009 n = 1032 p = 10009 n = 44402 p = 100049 Extra credit n = 665820697 p = 1000000009 n = 881398088036 p = 1000000000039 n = 41660815127637347468140745042827704103445750172002 p = 10^50 + 577 See also Modular exponentiation Cipolla's algorithm
#OCaml
OCaml
let tonelli n p = let open Z in let two = ~$2 in let pp = pred p in let pph = pred p / two in let pow_mod_p a e = powm a e p in let legendre_p a = pow_mod_p a pph in   if legendre_p n <> one then None else let s = trailing_zeros pp in if s = 1 then let r = pow_mod_p n (succ p / ~$4) in Some (r, p - r) else let q = pp asr s in let z = let rec find_non_square z = if legendre_p z = pp then z else find_non_square (succ z) in find_non_square two in let rec loop c r t m = if t = one then (r, p - r) else let mp = pred m in let rec find_i n i = if n = one || i >= mp then i else find_i (n * n mod p) (succ i) in let rec exp_pow2 b e = if e <= zero then b else exp_pow2 (b * b mod p) (pred e) in let i = find_i t zero in let b = exp_pow2 c (mp - i) in let c = b * b mod p in loop c (r * b mod p) (t * c mod p) i in Some (loop (pow_mod_p z q) (pow_mod_p n (succ q / two)) (pow_mod_p n q) ~$s)   let () = let open Z in [ (~$9, ~$11); (~$10, ~$13); (~$56, ~$101); (~$1030, ~$10009); (~$1032, ~$10009); (~$44402, ~$100049); (~$665820697, ~$1000000009); (~$881398088036, ~$1000000000039); ( of_string "41660815127637347468140745042827704103445750172002", pow ~$10 50 + ~$577 ); ] |> List.iter (fun (n, p) -> Printf.printf "n = %s\np = %s\n%!" (to_string n) (to_string p); match tonelli n p with | Some (r1, r2) -> Printf.printf "root1 = %s\nroot2 = %s\n\n%!" (to_string r1) (to_string r2) | None -> print_endline "No solution exists\n")  
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
#Forth
Forth
variable 'src variable #src variable offset   : advance 1 offset +! ; : chr@ offset @ 'src @ + c@ ; : nextchr advance chr@ ; : bound offset @ #src @ u< ; : separator? dup [char] | = if drop cr else emit then ; : escape? dup [char] ^ = if drop nextchr emit else separator? then ; : tokenize 0 offset ! begin bound while nextchr escape? repeat ;   \ Test of function Here 'src ! ," one^|uno||three^^^^|four^^^|^cuatro|" here 'src @ - #src  ! page cr ." #### start ####" cr tokenize cr ." #### End ####" cr  
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
#Fortran
Fortran
SUBROUTINE SPLIT(TEXT,SEP,ESC) !Identifies and prints tokens from within a text. CHARACTER*(*) TEXT !To be scanned. CHARACTER*(1) SEP !The only separator for tokens. CHARACTER*(1) ESC !Miscegnator. CHARACTER*(LEN(TEXT)) TOKEN !Surely sufficient space. INTEGER N !Counts the tokens as they're found. INTEGER I !Steps through the text. INTEGER L !Length of the token so far accumulated. LOGICAL ESCAPING !Miscegnatory state. N = 0 !No tokens so far. L = 0 !Nor any text for the first. ESCAPING = .FALSE. !And the state is good. DO I = 1,LEN(TEXT) !Step through the text. IF (ESCAPING) THEN !Are we in a mess? L = L + 1 !Yes. An ESC character had been seen. TOKEN(L:L) = TEXT(I:I) !So, whatever follows is taken as itself. ESCAPING = .FALSE. !There are no specially-recognised names. ELSE !Otherwise, we're in text to inspect. IF (TEXT(I:I).EQ.ESC) THEN !So, is it a troublemaker? ESCAPING = .TRUE. !Yes! Trouble is to follow. ELSE IF (TEXT(I:I).EQ.SEP) THEN !If instead a separator, CALL SPLOT !Then the token up to it is complete. ELSE !Otherwise, a simple constituent character. L = L + 1 !So, count it in. TOKEN(L:L) = TEXT(I:I) !And copy it in. END IF !So much for grist. END IF !So much for that character. END DO !On to the next. Completes on end-of-text with L > 0, or, if the last character had been SEP, a null token is deemed to be following. CALL SPLOT !Tail end. CONTAINS !Save on having two copies of this code. SUBROUTINE SPLOT !Show the token and scrub. N = N + 1 !Another one. WRITE (6,1) N,TOKEN(1:L) !Reveal. 1 FORMAT ("Token ",I0," >",A,"<")!Fancy layout. L = 0 !Prepare for a fresh token. END SUBROUTINE SPLOT !A brief life. END SUBROUTINE SPLIT !And then oblivion.   PROGRAM POKE   CALL SPLIT("one^|uno||three^^^^|four^^^|^cuatro|","|","^")   END
http://rosettacode.org/wiki/Total_circles_area
Total circles area
Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal digits of precision. The area covered by two or more disks needs to be counted only once. One point of this Task is also to compare and discuss the relative merits of various solution strategies, their performance, precision and simplicity. This means keeping both slower and faster solutions for a language (like C) is welcome. To allow a better comparison of the different implementations, solve the problem with this standard dataset, each line contains the x and y coordinates of the centers of the disks and their radii   (11 disks are fully contained inside other disks): xc yc radius 1.6417233788 1.6121789534 0.0848270516 -1.4944608174 1.2077959613 1.1039549836 0.6110294452 -0.6907087527 0.9089162485 0.3844862411 0.2923344616 0.2375743054 -0.2495892950 -0.3832854473 1.0845181219 1.7813504266 1.6178237031 0.8162655711 -0.1985249206 -0.8343333301 0.0538864941 -1.7011985145 -0.1263820964 0.4776976918 -0.4319462812 1.4104420482 0.7886291537 0.2178372997 -0.9499557344 0.0357871187 -0.6294854565 -1.3078893852 0.7653357688 1.7952608455 0.6281269104 0.2727652452 1.4168575317 1.0683357171 1.1016025378 1.4637371396 0.9463877418 1.1846214562 -0.5263668798 1.7315156631 1.4428514068 -1.2197352481 0.9144146579 1.0727263474 -0.1389358881 0.1092805780 0.7350208828 1.5293954595 0.0030278255 1.2472867347 -0.5258728625 1.3782633069 1.3495508831 -0.1403562064 0.2437382535 1.3804956588 0.8055826339 -0.0482092025 0.3327165165 -0.6311979224 0.7184578971 0.2491045282 1.4685857879 -0.8347049536 1.3670667538 -0.6855727502 1.6465021616 1.0593087096 0.0152957411 0.0638919221 0.9771215985 The result is   21.56503660... . Related task   Circles of given radius through two points. See also http://www.reddit.com/r/dailyprogrammer/comments/zff9o/9062012_challenge_96_difficult_water_droplets/ http://stackoverflow.com/a/1667789/10562
#Raku
Raku
class Point { has Real $.x; has Real $.y; has Int $!cbits; # bitmap of circle membership   method cbits { $!cbits //= set_cbits(self) } method gist { $!x ~ "\t" ~ $!y } }   multi infix:<to>(Point $p1, Point $p2) { sqrt ($p1.x - $p2.x) ** 2 + ($p1.y - $p2.y) ** 2; }   multi infix:<mid>(Point $p1, Point $p2) { Point.new(x => ($p1.x + $p2.x) / 2, y => ($p1.y + $p2.y) / 2); }   class Circle { has Point $.center; has Real $.radius;   has Point $.north = Point.new(x => $!center.x, y => $!center.y + $!radius); has Point $.west = Point.new(x => $!center.x - $!radius, y => $!center.y); has Point $.south = Point.new(x => $!center.x, y => $!center.y - $!radius); has Point $.east = Point.new(x => $!center.x + $!radius, y => $!center.y);   multi method contains(Circle $c) { $!center to $c.center <= $!radius - $c.radius } multi method contains(Point $p) { $!center to $p <= $!radius } method gist { $!center.gist ~ "\t" ~ $.radius } }   class Rect { has Point $.nw; has Point $.ne; has Point $.sw; has Point $.se;   method diag { $!ne to $!se } method area { ($!ne.x - $!nw.x) * ($!nw.y - $!sw.y) } method contains(Point $p) { $!nw.x < $p.x < $!ne.x and $!sw.y < $p.y < $!nw.y; } }   my @rawcircles = sort -*.radius, map -> $x, $y, $radius { Circle.new(:center(Point.new(:$x, :$y)), :$radius) }, < 1.6417233788 1.6121789534 0.0848270516 -1.4944608174 1.2077959613 1.1039549836 0.6110294452 -0.6907087527 0.9089162485 0.3844862411 0.2923344616 0.2375743054 -0.2495892950 -0.3832854473 1.0845181219 1.7813504266 1.6178237031 0.8162655711 -0.1985249206 -0.8343333301 0.0538864941 -1.7011985145 -0.1263820964 0.4776976918 -0.4319462812 1.4104420482 0.7886291537 0.2178372997 -0.9499557344 0.0357871187 -0.6294854565 -1.3078893852 0.7653357688 1.7952608455 0.6281269104 0.2727652452 1.4168575317 1.0683357171 1.1016025378 1.4637371396 0.9463877418 1.1846214562 -0.5263668798 1.7315156631 1.4428514068 -1.2197352481 0.9144146579 1.0727263474 -0.1389358881 0.1092805780 0.7350208828 1.5293954595 0.0030278255 1.2472867347 -0.5258728625 1.3782633069 1.3495508831 -0.1403562064 0.2437382535 1.3804956588 0.8055826339 -0.0482092025 0.3327165165 -0.6311979224 0.7184578971 0.2491045282 1.4685857879 -0.8347049536 1.3670667538 -0.6855727502 1.6465021616 1.0593087096 0.0152957411 0.0638919221 0.9771215985 >».Num;   # remove redundant circles my @circles; while @rawcircles { my $c = @rawcircles.shift; next if @circles.any.contains($c); push @circles, $c; }   sub set_cbits(Point $p) { my $cbits = 0; for @circles Z (1,2,4...*) -> ($c, $b) { $cbits += $b if $c.contains($p); } $cbits; }   my $xmin = min @circles.map: { .center.x - .radius } my $xmax = max @circles.map: { .center.x + .radius } my $ymin = min @circles.map: { .center.y - .radius } my $ymax = max @circles.map: { .center.y + .radius }   my $min-radius = @circles[*-1].radius;   my $outer-rect = Rect.new: nw => Point.new(x => $xmin, y => $ymax), ne => Point.new(x => $xmax, y => $ymax), sw => Point.new(x => $xmin, y => $ymin), se => Point.new(x => $xmax, y => $ymin);   my $outer-area = $outer-rect.area;   my @unknowns = $outer-rect; my $known-dry = 0e0; my $known-wet = 0e0; my $div = 1;   # divide current rects each into four rects, analyze each sub divide(@old) {   $div *= 2;   # rects too small to hold circle? my $smallish = @old[0].diag < $min-radius;   my @unk; for @old { my $center = .nw mid .se; my $north = .nw mid .ne; my $south = .sw mid .se; my $west = .nw mid .sw; my $east = .ne mid .se;   for Rect.new(nw => .nw, ne => $north, sw => $west, se => $center), Rect.new(nw => $north, ne => .ne, sw => $center, se => $east), Rect.new(nw => $west, ne => $center, sw => .sw, se => $south), Rect.new(nw => $center, ne => $east, sw => $south, se => .se) { my @bits = .nw.cbits, .ne.cbits, .sw.cbits, .se.cbits;   # if all 4 points wet by same circle, guaranteed wet if [+&] @bits { $known-wet += .area; next; }   # if all 4 corners are dry, must check further if not [+|] @bits and $smallish {   # check that no circle bulges into this rect my $ok = True; for @circles -> $c { if .contains($c.east) or .contains($c.west) or .contains($c.north) or .contains($c.south) { $ok = False; last; } } if $ok { $known-dry += .area; next; } } push @unk, $_; # dunno yet } } @unk; }   my $delta = 0.001; repeat until my $diff < $delta { @unknowns = divide(@unknowns);   $diff = $outer-area - $known-dry - $known-wet; say 'div: ', $div.fmt('%-5d'), ' unk: ', (+@unknowns).fmt('%-6d'), ' est: ', ($known-wet + $diff/2).fmt('%9.6f'), ' wet: ', $known-wet.fmt('%9.6f'), ' dry: ', ($outer-area - $known-dry).fmt('%9.6f'), ' diff: ', $diff.fmt('%9.6f'), ' error: ', ($diff - @unknowns * @unknowns[0].area).fmt('%e'); }
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]
#Erlang
Erlang
  -module(topological_sort). -compile(export_all).   -define(LIBRARIES, [{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, []}]).   -define(BAD_LIBRARIES, [{des_system_lib, [std, synopsys, std_cell_lib, des_system_lib, dw02, dw01, ramlib, ieee]}, {dw01, [ieee, dw01, dw04, 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, []}]).   main() -> top_sort(?LIBRARIES), top_sort(?BAD_LIBRARIES).   top_sort(Library) -> G = digraph:new(), lists:foreach(fun ({L,Deps}) -> digraph:add_vertex(G,L), % noop if library already added lists:foreach(fun (D) -> add_dependency(G,L,D) end, Deps) end, Library), T = digraph_utils:topsort(G), case T of false -> io:format("Unsortable contains circular dependencies:~n",[]), lists:foreach(fun (V) -> case digraph:get_short_cycle(G,V) of false -> ok; Vs -> print_path(Vs) end end, digraph:vertices(G)); _ -> print_path(T) end.   print_path(L) -> lists:foreach(fun (V) -> io:format("~s -> ",[V]) end, lists:sublist(L,length(L)-1)), io:format("~s~n",[lists:last(L)]).   add_dependency(_G,_L,_L) -> ok; add_dependency(G,L,D) -> digraph:add_vertex(G,D), % noop if dependency already added digraph:add_edge(G,D,L). % Dependencies represented as an edge D -> L  
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.
#Lambdatalk
Lambdatalk
  {require lib_H} // associative arrays library   {def tm {def tm.r {lambda {:data :rules :state :end :blank :i :N} {if {or {W.equal? :state :end} {> :N 400}} // recursion limited to 400 then :data else {let { {:data :data} {:rules :rules} {:state {H.get :state :rules}} {:end :end} {:blank :blank} {:i :i} {:N :N} {:cell {if {W.equal? {A.get :i :data} undefined} then :blank else {A.get :i :data}}} } {tm.r {A.set! :i {H.get write {H.get :cell :state}} :data}  :rules {H.get next {H.get :cell :state}}  :end  :blank {+ :i {H.get move {H.get :cell :state}} } {+ :N 1} } }}}} {lambda {:name :data :rules :state :end :blank}  :name: {A.duplicate :data} -> {tm.r :data :rules :state :end :blank 0 0}}} -> tm   {tm zero2one {A.new 0 0 0} {H.new A {H.new 0 {H.new write 1 | move 1 | next A} | B {H.new write . | move 1 | next H} } } A H B}   output: zero2one: [0,0,0] -> [1,1,1,.]   {tm add_one {A.new 1 1 1} {H.new A {H.new 1 {H.new write 1 | move 1 | next A} | B {H.new write 1 | move 0 | next B} } } A B B}   output: add_one: [1,1,1] -> [1,1,1,1]   {tm unary_adder {A.new 1 1 1 0 1 1 1} {H.new A {H.new 1 {H.new write 0 | move 1 | next B} } | B {H.new 1 {H.new write 1 | move 1 | next B} | 0 {H.new write 1 | move 0 | next H} } } A H B}   output: unary_adder: [1,1,1,0,1,1,1] -> [0,1,1,1,1,1,1]   {tm duplicate {A.new 1 1 1} {H.new q0 {H.new 1 {H.new write B | move 1 | next q1} } |   q1 {H.new 1 {H.new write 1 | move 1 | next q1} | 0 {H.new write 0 | move 1 | next q2} | B {H.new write 0 | move 1 | next q2}} |   q2 {H.new 1 {H.new write 1 | move 1 | next q2} | B {H.new write 1 | move -1 | next q3}} |   q3 {H.new 1 {H.new write 1 | move -1 | next q3} | 0 {H.new write 0 | move -1 | next q3} | B {H.new write 1 | move 1 | next q4}} |   q4 {H.new 1 {H.new write B | move 1 | next q1} | 0 {H.new write 0 | move 1 | next qf}} } q0 qf B}   output: duplicate: [1,1,1] -> [1,1,1,0,1,1,1]   {tm sort {A.new 2 1 2 2 2 1 1} {H.new A {H.new 1 {H.new write 1 | move 1 | next A} | 2 {H.new write 3 | move 1 | next B} | 0 {H.new write 0 | move -1 | next E}} |   B {H.new 1 {H.new write 1 | move 1 | next B} | 2 {H.new write 2 | move 1 | next B} | 0 {H.new write 0 | move -1 | next C}} |   C {H.new 1 {H.new write 2 | move -1 | next D} | 2 {H.new write 2 | move -1 | next C} | 3 {H.new write 2 | move -1 | next E}} |   D {H.new 1 {H.new write 1 | move -1 | next D} | 2 {H.new write 2 | move -1 | next D} | 3 {H.new write 1 | move 1 | next A}} |   E {H.new 1 {H.new write 1 | move -1 | next E} | 0 {H.new write 0 | move 1 | next H}} } A H 0}   output: sort: [2,1,2,2,2,1,1] -> [1,1,1,2,2,2,2,0]   {tm busy_beaver {A.new} {H.new A {H.new 0 {H.new write 1 | move 1 | next B} | 1 {H.new write 1 | move -1 | next C}} |   B {H.new 0 {H.new write 1 | move -1 | next A} | 1 {H.new write 1 | move 1 | next B}} |   C {H.new 0 {H.new write 1 | move -1 | next B} | 1 {H.new write 1 | move 0 | next H}} } A H 0}   output: busy_beaver: [] -> [1,1,1]   {tm busy_beaver2 {A.new} {H.new A {H.new 0 {H.new write 1 | move 1 | next B} | 1 {H.new write 1 | move -1 | next C}} |   B {H.new 0 {H.new write 1 | move 1 | next C} | 1 {H.new write 1 | move 1 | next B}} |   C {H.new 0 {H.new write 1 | move 1 | next D} | 1 {H.new write 0 | move -1 | next E}} |   D {H.new 0 {H.new write 1 | move -1 | next A} | 1 {H.new write 1 | move -1 | next D}} |   E {H.new 0 {H.new write 1 | move 0 | next K} | 1 {H.new write 0 | move -1 | next A}} } A K 0}   output: busy_beaver2: [] -> [1,1,1,1,1,1,1,1,1,1,1]    
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).
#jq
jq
  # jq optimizes the recursive call of _gcd in the following: def gcd(a;b): def _gcd: if .[1] != 0 then [.[1], .[0] % .[1]] | _gcd else .[0] end; [a,b] | _gcd ;   def count(s): reduce s as $x (0; .+1);   def totient: . as $n | count( range(0; .) | select( gcd($n; .) == 1) );   # input: determines the maximum via range(0; .) # and so may be `infinite` def primes_via_totient: range(0; .) | select(totient == . - 1);  
http://rosettacode.org/wiki/Topswops
Topswops
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is composed of reversing the first   m   cards where   m   is the value of the topmost card. Rounds are repeated until the topmost card is the number   1   and the number of swaps is recorded. For our example the swaps produce: [2, 4, 1, 3] # Initial shuffle [4, 2, 1, 3] [3, 1, 2, 4] [2, 1, 3, 4] [1, 2, 3, 4] For a total of four swaps from the initial ordering to produce the terminating case where   1   is on top. For a particular number   n   of cards,   topswops(n)   is the maximum swaps needed for any starting permutation of the   n   cards. Task The task is to generate and show here a table of   n   vs   topswops(n)   for   n   in the range   1..10   inclusive. Note Topswops   is also known as   Fannkuch   from the German word   Pfannkuchen   meaning   pancake. Related tasks   Number reversal game   Sorting algorithms/Pancake sort
#R
R
  topswops <- function(x){ i <- 0 while(x[1] != 1){ first <- x[1] if(first == length(x)){ x <- rev(x) } else{ x <- c(x[first:1], x[(first+1):length(x)]) } i <- i + 1 } return(i) }   library(iterpc)   result <- NULL   for(i in 1:10){ I <- iterpc(i, labels = 1:i, ordered = T) A <- getall(I) A <- data.frame(A) A$flips <- apply(A, 1, topswops) result <- rbind(result, c(i, max(A$flips))) }  
http://rosettacode.org/wiki/Topswops
Topswops
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is composed of reversing the first   m   cards where   m   is the value of the topmost card. Rounds are repeated until the topmost card is the number   1   and the number of swaps is recorded. For our example the swaps produce: [2, 4, 1, 3] # Initial shuffle [4, 2, 1, 3] [3, 1, 2, 4] [2, 1, 3, 4] [1, 2, 3, 4] For a total of four swaps from the initial ordering to produce the terminating case where   1   is on top. For a particular number   n   of cards,   topswops(n)   is the maximum swaps needed for any starting permutation of the   n   cards. Task The task is to generate and show here a table of   n   vs   topswops(n)   for   n   in the range   1..10   inclusive. Note Topswops   is also known as   Fannkuch   from the German word   Pfannkuchen   meaning   pancake. Related tasks   Number reversal game   Sorting algorithms/Pancake sort
#Racket
Racket
  #lang racket   (define (all-misplaced? l) (for/and ([x (in-list l)] [n (in-naturals 1)]) (not (= x n))))   (define (topswops n) (for/fold ([m 0]) ([p (in-permutations (range 1 (add1 n)))] #:when (all-misplaced? p)) (let loop ([p p] [n 0]) (if (= 1 (car p)) (max n m) (loop (let loop ([l '()] [r p] [n (car p)]) (if (zero? n) (append l r) (loop (cons (car r) l) (cdr r) (sub1 n)))) (add1 n))))))   (for ([i (in-range 1 11)]) (printf "~a\t~a\n" i (topswops i)))