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/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#ActionScript
ActionScript
public function move(n:int, from:int, to:int, via:int):void { if (n > 0) { move(n - 1, from, via, to); trace("Move disk from pole " + from + " to pole " + to); move(n - 1, via, to, from); } }
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
#11l
11l
F legendre(a, p) R pow(a, (p - 1) I/ 2, p)   F tonelli(n, p) assert(legendre(n, p) == 1, ‘not a square (mod p)’) V q = p - 1 V s = 0 L q % 2 == 0 q I/= 2 s++ I s == 1 R pow(n, (p + 1) I/ 4, p) V z = 2 L I p - 1 == legendre(z, p) L.break z++ V c = pow(z, q, p) V r = pow(n, (q + 1) I/ 2, p) V t = pow(n, q, p) V m = s V t2 = BigInt(0) L (t - 1) % p != 0 t2 = (t * t) % p V i = 1 L(ii) 1 .< m I (t2 - 1) % p == 0 i = ii L.break t2 = (t2 * t2) % p V b = pow(c, Int64(1 << (m - i - 1)), p) r = (r * b) % p c = (b * b) % p t = (t * c) % p m = i R r   V ttest = [(BigInt(10), BigInt(13)), (BigInt(56), BigInt(101)), (BigInt(1030), BigInt(10009)), (BigInt(44402), BigInt(100049)), (BigInt(665820697), BigInt(1000000009)), (BigInt(881398088036), BigInt(1000000000039)), (BigInt(‘41660815127637347468140745042827704103445750172002’), BigInt(10) ^ 50 + 577)] L(n, p) ttest V r = tonelli(n, p) assert((r * r - n) % p == 0) print(‘n = #. p = #.’.format(n, p)) print("\t roots : #. #.".format(r, p - 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
#Ada
Ada
with Ada.Text_Io; with Ada.Containers.Indefinite_Vectors; with Ada.Strings.Unbounded;   procedure Tokenize is   package String_Vectors is new Ada.Containers.Indefinite_Vectors (Positive, String); use String_Vectors;   function Split (Text  : String; Separator : Character := '|'; Escape  : Character := '^') return Vector is use Ada.Strings.Unbounded; Result  : Vector; Escaped : Boolean := False; Accu  : Unbounded_String; begin   for Char of Text loop   case Escaped is   when False => if Char = Escape then Escaped := True; elsif Char = Separator then Append (Result, To_String (Accu)); Accu := Null_Unbounded_String; else Append (Accu, Char); end if;   when True => Append (Accu, Char); Escaped := False;   end case;   end loop; Append (Result, To_String (Accu));   return Result; end Split;   procedure Put_Vector (List : Vector) is use Ada.Text_Io; begin for Element of List loop Put ("'"); Put (Element); Put ("'"); New_Line; end loop; end Put_Vector;   begin Put_Vector (Split ("one^|uno||three^^^^|four^^^|^cuatro|")); end 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
#FreeBASIC
FreeBASIC
#define dx 0.0001   'read in the data; I reordered them in descending order of radius 'This maximises our chance of being able to break early, saving run time, 'and we needn't bother finding out which circles are entirely inside others data -0.5263668798,1.7315156631,1.4428514068 data -0.1403562064,0.2437382535,1.3804956588 data 1.4685857879,-0.8347049536,1.3670667538 data -0.5258728625,1.3782633069,1.3495508831 data 1.5293954595,0.0030278255,1.2472867347 data 1.4637371396,0.9463877418,1.1846214562 data -1.4944608174,1.2077959613,1.1039549836 data 1.4168575317,1.0683357171,1.1016025378 data -0.249589295,-0.3832854473,1.0845181219 data -1.2197352481,0.9144146579,1.0727263474 data -0.6855727502,1.6465021616,1.0593087096 data 0.0152957411,0.0638919221,0.9771215985 data 0.6110294452,-0.6907087527,0.9089162485 data 1.7813504266,1.6178237031,0.8162655711 data -0.4319462812,1.4104420482,0.7886291537 data -0.6294854565,-1.3078893852,0.7653357688 data -0.1389358881,0.109280578,0.7350208828 data -1.7011985145,-0.1263820964,0.4776976918 data 0.8055826339,-0.0482092025,0.3327165165 data 1.7952608455,0.6281269104,0.2727652452 data -0.6311979224,0.7184578971,0.2491045282 data 0.3844862411,0.2923344616,0.2375743054 data 1.6417233788,1.6121789534,0.0848270516 data -0.1985249206,-0.8343333301,0.0538864941 data 0.2178372997,-0.9499557344,0.0357871187   function dist(x0 as double, y0 as double, x1 as double, y1 as double) as double 'distance between two points in 2d space return sqr( (x1-x0)^2 + (y1-y0)^2 ) end function   dim as double x(1 to 25), y(1 to 25), r(1 to 25), gx, gy, A0, A1, A2, A dim as integer i, cx, cy   for i = 1 to 25 read x(i), y(i), r(i) next i   for gx = -2.6 to 2.9 step dx 'sample points on a grid cx += 1 for gy = -2.3 to 3.2 step dx cy += 1 for i = 1 to 25 if dist(gx, gy, x(i), y(i)) <= r(i) then 'if our grid point is in the circle A2 += dx^2 'add the area of a grid square if cx mod 2 = 0 and cy mod 2 = 0 then A1 += 4*dx^2 if cx mod 4 = 0 and cy mod 4 = 0 then A0 += 16*dx^2 'also keep track of coarser grid areas of twice and four times the size 'You'll see why in a moment exit for end if next i next gy next gx   'use Shanks method to refine our estimate of the area A = (A0*A2-A1^2) / (A0 + A2 - 2*A1) print A0, A1, A2, A
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]
#Ada
Ada
with Ada.Containers.Vectors; use Ada.Containers;   package Digraphs is   type Node_Idx_With_Null is new Natural; subtype Node_Index is Node_Idx_With_Null range 1 .. Node_Idx_With_Null'Last; -- a Node_Index is a number from 1, 2, 3, ... and the representative of a node   type Graph_Type is tagged private;   -- make sure Node is in Graph (possibly without connections) procedure Add_Node (Graph: in out Graph_Type'Class; Node: Node_Index);   -- insert an edge From->To into Graph; do nothing if already there procedure Add_Connection (Graph: in out Graph_Type'Class; From, To: Node_Index);   -- get the largest Node_Index used in any Add_Node or Add_Connection op. -- iterate over all nodes of Graph: "for I in 1 .. Graph.Node_Count loop ..." function Node_Count(Graph: Graph_Type) return Node_Idx_With_Null;   -- remove an edge From->To from Fraph; do nothing if not there -- Graph.Node_Count is not changed procedure Del_Connection (Graph: in out Graph_Type'Class; From, To: Node_Index);   -- check if an edge From->to exists in Graph function Connected (Graph: Graph_Type; From, To: Node_Index) return Boolean;   -- data structure to store a list of nodes package Node_Vec is new Vectors(Positive, Node_Index);   -- get a list of all nodes From->Somewhere in Graph function All_Connections (Graph: Graph_Type; From: Node_Index) return Node_Vec.Vector;   Graph_Is_Cyclic: exception;   -- a depth-first search to find a topological sorting of the nodes -- raises Graph_Is_Cyclic if no topological sorting is possible function Top_Sort (Graph: Graph_Type) return Node_Vec.Vector;   private   package Conn_Vec is new Vectors(Node_Index, Node_Vec.Vector, Node_Vec."=");   type Graph_Type is new Conn_Vec.Vector with null record;   end Digraphs;
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.
#EchoLisp
EchoLisp
  (require 'struct)   (struct TM (read-only: name states symbs final rules mem state-values: tape pos state))   (define-syntax-rule (rule-idx state symb numstates) (+ state (* symb numstates)))   (define-syntax-rule (make-TM name states symbs rules) (_make-TM name 'states 'symbs 'rules))   ;; a rule is (state symbol --> write move new-state) ;; index for rule = state-num + (number of states) * symbol-num ;; convert states/symbol into vector indices (define (compile-rule T rule into: rules) (define numstates (vector-length (TM-states T))) (define state (vector-index [rule 0](TM-states T) )) ; index (define symb (vector-index [rule 1](TM-symbs T) )) (define write-symb (vector-index [rule 2] (TM-symbs T) )) (define move (1- (vector-index [rule 3] #(left stay right) ))) (define new-state (vector-index [rule 4](TM-states T))) (define rulenum (rule-idx state symb numstates)) (vector-set! rules rulenum (vector write-symb move new-state)) ; (writeln 'rule rulenum [rules rulenum]) )   (define (_make-TM name states symbs rules) (define T (TM name (list->vector states) (list->vector symbs) null null)) (set-TM-final! T (1- (length states))) ;; assume one final state (set-TM-rules! T (make-vector (* (length states) (length symbs)))) (for ((rule rules)) (compile-rule T (list->vector rule) into: (TM-rules T))) T ) ; returns a TM   ;;------------------ ;; TM-trace ;;------------------- (string-delimiter "")   (define (TM-print T symb-index: symb (hilite #f)) (cond ((= 0 symb) (if hilite "🔲" "◽️" )) ((= 1 symb) (if hilite "🔳 " "◾️" )) (else "X")))   (define (TM-trace T tape pos state step) (if (= (TM-final T) state) (write "🔴") (write "🔵"))   (for [(p (in-range (- (TM-mem T) 7) (+ (TM-mem T) 8)))] (write (TM-print T [tape p] (= p pos)))) (write step) (writeln))   ;;--------------- ;; TM-init : alloc and init tape ;;--------------- (define (TM-init T input-symbs (mem 20)) ;; init state variables (set-TM-tape! T (make-vector (* 2 mem))) (set-TM-pos! T mem) (set-TM-state! T 0) (set-TM-mem! T mem)   (for [(symb input-symbs) (i (in-naturals))] (vector-set! (TM-tape T) [+ i (TM-pos T)] (vector-index symb (TM-symbs T)))) (TM-trace T (TM-tape T) mem 0 0) mem )   ;;--------------- ;; TM-run : run at most maxsteps ;;--------------- (define (TM-run T (verbose #f) (maxsteps 1_000_000)) (define count 0) (define final (TM-final T)) (define rules (TM-rules T)) (define rule 0) (define numstates (vector-length (TM-states T))) ;; set current state vars (define pos (TM-pos T)) (define state (TM-state T)) (define tape (TM-tape T))   (when (and (zero? state) (= pos (TM-mem T))) (writeln 'Starting (TM-name T)) (TM-trace T tape pos 0 count))   (while (and (!= state final) (< count maxsteps)) (++ count) ;; The machine (set! rule [rules (rule-idx state [tape pos] numstates)]) (when (= rule 0) (error "missing rule" (list state [tape pos]))) (vector-set! tape pos [rule 0]) (set! state [rule 2]) (+= pos [rule 1]) ;; end machine (when verbose (TM-trace T tape pos state count ))) ;; save TM state (set-TM-pos! T pos) (set-TM-state! T state) (when (= final state) (writeln 'Stopping (TM-name T) 'at-pos (- pos (TM-mem T)))) count)  
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).
#C.23
C#
using static System.Console; using static System.Linq.Enumerable;   public class Program { static void Main() { for (int i = 1; i <= 25; i++) { int t = Totient(i); WriteLine(i + "\t" + t + (t == i - 1 ? "\tprime" : "")); } WriteLine(); for (int i = 100; i <= 100_000; i *= 10) { WriteLine($"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}"); } }   static int Totient(int n) { if (n < 3) return 1; if (n == 3) return 2;   int totient = n;   if ((n & 1) == 0) { totient >>= 1; while (((n >>= 1) & 1) == 0) ; }   for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) { totient -= totient / i; while ((n /= i) % i == 0) ; } } if (n > 1) totient -= totient / n; return totient; } }
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
#Icon_and_Unicon
Icon and Unicon
procedure main() every n := 1 to 10 do { ts := 0 every (ts := 0) <:= swop(permute([: 1 to n :])) write(right(n, 3),": ",right(ts,4)) } end   procedure swop(A) count := 0 while A[1] ~= 1 do { A := reverse(A[1+:A[1]]) ||| A[(A[1]+1):0] count +:= 1 } return count end   procedure permute(A) if *A <= 1 then return A suspend [(A[1]<->A[i := 1 to *A])] ||| permute(A[2:0]) end
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.
#bc
bc
/* t(x) = tangent of x */ define t(x) { return s(x) / c(x) }   /* y(y) = arcsine of y, domain [-1, 1], range [-pi/2, pi/2] */ define y(y) { /* Handle angles with no tangent. */ if (y == -1) return -2 * a(1) /* -pi/2 */ if (y == 1) return 2 * a(1) /* pi/2 */   /* Tangent of angle is y / x, where x^2 + y^2 = 1. */ return a(y / sqrt(1 - y * y)) }   /* x(x) = arccosine of x, domain [-1, 1], range [0, pi] */ define x(x) { auto a   /* Handle angle with no tangent. */ if (x == 0) return 2 * a(1) /* pi/2 */   /* Tangent of angle is y / x, where x^2 + y^2 = 1. */ a = a(sqrt(1 - x * x) / x) if (a < 0) { return a + 4 * a(1) /* add pi */ } else { return a } }     scale = 50 p = 4 * a(1) /* pi */ d = p / 180 /* one degree in radians */   "Using radians: " " sin(-pi / 6) = "; s(-p / 6) " cos(3 * pi / 4) = "; c(3 * p / 4) " tan(pi / 3) = "; t(p / 3) " asin(-1 / 2) = "; y(-1 / 2) " acos(-sqrt(2) / 2) = "; x(-sqrt(2) / 2) " atan(sqrt(3)) = "; a(sqrt(3))   "Using degrees: " " sin(-30) = "; s(-30 * d) " cos(135) = "; c(135 * d) " tan(60) = "; t(60 * d) " asin(-1 / 2) = "; y(-1 / 2) / d " acos(-sqrt(2) / 2) = "; x(-sqrt(2) / 2) / d " atan(sqrt(3)) = "; a(sqrt(3)) / d   quit
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).
#Elixir
Elixir
defmodule Trabb_Pardo_Knuth do def task do Enum.reverse( get_11_numbers ) |> Enum.each( fn x -> perform_operation( &function(&1), 400, x ) end ) end   defp alert( n ), do: IO.puts "Operation on #{n} overflowed"   defp get_11_numbers do ns = IO.gets( "Input 11 integers. Space delimited, please: " ) |> String.split |> Enum.map( &String.to_integer &1 ) if 11 == length( ns ), do: ns, else: get_11_numbers end   defp function( x ), do: :math.sqrt( abs(x) ) + 5 * :math.pow( x, 3 )   defp perform_operation( fun, overflow, n ), do: perform_operation_check_overflow( n, fun.(n), overflow )   defp perform_operation_check_overflow( n, result, overflow ) when result > overflow, do: alert( n ) defp perform_operation_check_overflow( n, result, _overflow ), do: IO.puts "f(#{n}) => #{result}" end   Trabb_Pardo_Knuth.task
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).
#Erlang
Erlang
  -module( trabb_pardo_knuth ).   -export( [task/0] ).   task() -> Sequence = get_11_numbers(), S = lists:reverse( Sequence ), [perform_operation( fun function/1, 400, X) || X <- S].     alert( N ) -> io:fwrite( "Operation on ~p overflowed~n", [N] ).   get_11_numbers() -> {ok, Ns} = io:fread( "Input 11 integers. Space delimited, please: ", "~d ~d ~d ~d ~d ~d ~d ~d ~d ~d ~d" ), 11 = erlang:length( Ns ), Ns.   function( X ) -> math:sqrt( erlang:abs(X) ) + 5 * math:pow( X, 3 ).   perform_operation( Fun, Overflow, N ) -> perform_operation_check_overflow( N, Fun(N), Overflow ).   perform_operation_check_overflow( N, Result, Overflow ) when Result > Overflow -> alert( N ); perform_operation_check_overflow( N, Result, _Overflow ) -> io:fwrite( "f(~p) => ~p~n", [N, Result] ).  
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.
#Racket
Racket
  #lang racket   ;; A quick `amb' implementation (define failures null) (define (fail) (if (pair? failures) ((first failures)) (error "no more choices!"))) (define (amb/thunks choices) (let/cc k (set! failures (cons k failures))) (if (pair? choices) (let ([choice (first choices)]) (set! choices (rest choices)) (choice)) (begin (set! failures (rest failures)) (fail)))) (define-syntax-rule (amb E ...) (amb/thunks (list (lambda () E) ...))) (define (assert condition) (unless condition (fail)))   ;; just to make things more fun (define (⇔ x y) (assert (eq? x y))) (require (only-in racket [and ∧] [or ∨] [implies ⇒] [xor ⊻] [not ¬])) (define (count xs) (let loop ([n 0] [xs xs]) (if (null? xs) n (loop (if (car xs) (add1 n) n) (cdr xs))))) ;; even more fun, make []s infix (require (only-in racket [#%app r:app])) (define-syntax (#%app stx) (if (not (eq? #\[ (syntax-property stx 'paren-shape))) (syntax-case stx () [(_ x ...) #'(r:app x ...)]) (syntax-case stx ()  ;; extreme hack on next two cases, so it works for macros too. [(_ x op y) (syntax-property #'(op x y) 'paren-shape #f)] [(_ x op y op1 z) (free-identifier=? #'op #'op1) (syntax-property #'(op x y z) 'paren-shape #f)]))) ;; might as well do more (define-syntax-rule (define-booleans all x ...) (begin (define x (amb #t #f)) ... (define all (list x ...))))   (define (puzzle) (define-booleans all q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 q11 q12)  ;; 1. This is a numbered list of twelve statements. [q1 ⇔ [12 = (length all)]]  ;; 2. Exactly 3 of the last 6 statements are true. [q2 ⇔ [3 = (count (take-right all 6))]]  ;; 3. Exactly 2 of the even-numbered statements are true. [q3 ⇔ [2 = (count (list q2 q4 q6 q8 q10 q12))]]  ;; 4. If statement 5 is true, then statements 6 and 7 are both true. [q4 ⇔ [q5 ⇒ [q6 ∧ q7]]]  ;; 5. The 3 preceding statements are all false. [q5 ⇔ (¬ [q2 ∨ q3 ∨ q4])]  ;; 6. Exactly 4 of the odd-numbered statements are true. [q6 ⇔ [4 = (count (list q1 q3 q5 q7 q9 q11))]]  ;; 7. Either statement 2 or 3 is true, but not both. [q7 ⇔ [q2 ⊻ q3]]  ;; 8. If statement 7 is true, then 5 and 6 are both true. [q8 ⇔ [q7 ⇒ (and q5 q6)]]  ;; 9. Exactly 3 of the first 6 statements are true. [q9 ⇔ [3 = (count (take all 3))]]  ;; 10. The next two statements are both true. [q10 ⇔ [q11 ∧ q12]]  ;; 11. Exactly 1 of statements 7, 8 and 9 are true. [q11 ⇔ [1 = (count (list q7 q8 q9))]]  ;; 12. Exactly 4 of the preceding statements are true. [q12 ⇔ [4 = (count (drop-right all 1))]]  ;; done (for/list ([i (in-naturals 1)] [q all] #:when q) i))   (puzzle) ;; -> '(1 3 4 6 7 11)    
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.
#Raku
Raku
sub infix:<→> ($protasis, $apodosis) { !$protasis or $apodosis }   my @tests = { .end == 12 and all(.[1..12]) === any(True, False) }, { 3 == [+] .[7..12] }, { 2 == [+] .[2,4...12] }, { .[5] → all .[6,7] }, { none .[2,3,4] }, { 4 == [+] .[1,3...11] }, { one .[2,3] }, { .[7] → all .[5,6] }, { 3 == [+] .[1..6] }, { all .[11,12] }, { one .[7,8,9] }, { 4 == [+] .[1..11] }, ;   my @solutions; my @misses;   for [X] (True, False) xx 12 { my @assert = Nil, |$_; my @result = Nil, |@tests.map({ ?.(@assert) }); my @true = @assert.grep(?*, :k); my @cons = (@assert Z=== @result).grep(!*, :k); given @cons { when 0 { push @solutions, "<{@true}> is consistent."; } when 1 { push @misses, "<{@true}> implies { "¬" if !@result[~$_] }$_." } } }   .say for @solutions; say ""; say "Near misses:"; .say for @misses;
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.
#Pascal
Pascal
  program TruthTables; const StackSize = 80;   type TVariable = record Name: Char; Value: Boolean; end;   TStackOfBool = record Top: Integer; Elements: array [0 .. StackSize - 1] of Boolean; end;   var Expression: string; Variables: array [0 .. 23] of TVariable; VariablesLength: Integer; i: Integer; e: Char;   // Stack manipulation functions function IsFull(var s: TStackOfBool): Boolean; begin IsFull := s.Top = StackSize - 1; end;   function IsEmpty(var s: TStackOfBool): Boolean; begin IsEmpty := s.Top = -1; end;   function Peek(var s: TStackOfBool): Boolean; begin if not IsEmpty(s) then Peek := s.Elements[s.Top] else begin Writeln('Stack is empty.'); Halt; end; end;   procedure Push(var s: TStackOfBool; val: Boolean); begin if not IsFull(s) then begin Inc(s.Top); s.Elements[s.Top] := val; end else begin Writeln('Stack is full.'); Halt; end end;   function Pop(var s: TStackOfBool): Boolean; begin if not IsEmpty(s) then begin Result := s.Elements[s.Top]; Dec(s.Top); end else begin Writeln; Writeln('Stack is empty.'); Halt; end end;   procedure MakeEmpty(var s: TStackOfBool); begin s.Top := -1; end;   function ElementsCount(var s: TStackOfBool): Integer; begin ElementsCount := s.Top + 1; end;   function IsOperator(const c: Char): Boolean; begin IsOperator := (c = '&') or (c = '|') or (c = '!') or (c = '^'); end;   function VariableIndex(const c: Char): Integer; var i: Integer; begin for i := 0 to VariablesLength - 1 do if Variables[i].Name = c then begin VariableIndex := i; Exit; end; VariableIndex := -1; end;   function EvaluateExpression: Boolean; var i, vi: Integer; e: Char; s: TStackOfBool; begin MakeEmpty(s); for i := 1 to Length(Expression) do begin e := Expression[i]; vi := VariableIndex(e); if e = 'T' then Push(s, True) else if e = 'F' then Push(s, False) else if vi >= 0 then Push(s, Variables[vi].Value) else begin {$B+} case e of '&': Push(s, Pop(s) and Pop(s)); '|': Push(s, Pop(s) or Pop(s)); '!': Push(s, not Pop(s)); '^': Push(s, Pop(s) xor Pop(s)); else Writeln; Writeln('Non-conformant character ', e, ' in expression.'); Halt; end; {$B-} end; end; if ElementsCount(s) <> 1 then begin Writeln; Writeln('Stack should contain exactly one element.'); Halt; end; EvaluateExpression := Peek(s); end;   procedure SetVariables(pos: Integer); var i: Integer; begin if pos > VariablesLength then begin Writeln; Writeln('Argument to SetVariables cannot be greater than the number of variables.'); Halt; end else if pos = VariablesLength then begin for i := 0 to VariablesLength - 1 do begin if Variables[i].Value then Write('T ') else Write('F '); end; if EvaluateExpression then Writeln('T') else Writeln('F'); end else begin Variables[pos].Value := False; SetVariables(pos + 1); Variables[pos].Value := True; SetVariables(pos + 1); end end;   // removes space and converts to upper case procedure ProcessExpression; var i: Integer; exprTmp: string; begin exprTmp := ''; for i := 1 to Length(Expression) do begin if Expression[i] <> ' ' then exprTmp := Concat(exprTmp, UpCase(Expression[i])); end; Expression := exprTmp end;   begin Writeln('Accepts single-character variables (except for ''T'' and ''F'','); Writeln('which specify explicit true or false values), postfix, with'); Writeln('&|!^ for and, or, not, xor, respectively; optionally'); Writeln('seperated by space. Just enter nothing to quit.');   while (True) do begin Writeln; Write('Boolean expression: '); ReadLn(Expression); ProcessExpression; if Length(Expression) = 0 then Break; VariablesLength := 0; for i := 1 to Length(Expression) do begin e := Expression[i]; if (not IsOperator(e)) and (e <> 'T') and (e <> 'F') and (VariableIndex(e) = -1) then begin Variables[VariablesLength].Name := e; Variables[VariablesLength].Value := False; Inc(VariablesLength); end; end; WriteLn; if VariablesLength = 0 then Writeln('No variables were entered.') else begin for i := 0 to VariablesLength - 1 do Write(Variables[i].Name, ' '); Writeln(Expression); Writeln(StringOfChar('=', VariablesLength * 3 + Length(Expression))); SetVariables(0); end; end; 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
#Phix
Phix
with javascript_semantics function spiral(integer w, h, x, y) return iff(y?w+spiral(h-1,w,y-1,w-x-1):x) end function integer w = 9, h = 9 for i=h-1 to 0 by -1 do for j=w-1 to 0 by -1 do integer p = w*h-spiral(w,h,j,i) puts(1,"o "[2-is_prime(p)]) end for puts(1,'\n') end for
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.]
#Go
Go
package main   import "fmt"   func main() { sieve(1e6) if !search(6, 1e6, "left", func(n, pot int) int { return n % pot }) { panic("997?") } if !search(6, 1e6, "right", func(n, _ int) int { return n / 10 }) { panic("7393?") } }   var c []bool   func sieve(ss int) { c = make([]bool, ss) c[1] = true for p := 2; ; { p2 := p * p if p2 >= ss { break } for i := p2; i < ss; i += p { c[i] = true } for { p++ if !c[p] { break } } } }   func search(digits, pot int, s string, truncFunc func(n, pot int) int) bool { n := pot - 1 pot /= 10 smaller: for ; n >= pot; n -= 2 { for tn, tp := n, pot; tp > 0; tp /= 10 { if tn < tp || c[tn] { continue smaller } tn = truncFunc(tn, tp) } fmt.Println("max", s, "truncatable:", n) return true } if digits > 1 { return search(digits-1, pot, s, truncFunc) } return false }
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.
#APL
APL
preorder ← {l r←⍺ ⍵⍵ ⍵ ⋄ (⊃r)∇⍨⍣(×≢r)⊢(⊃l)∇⍨⍣(×≢l)⊢⍺ ⍺⍺ ⍵} inorder ← {l r←⍺ ⍵⍵ ⍵ ⋄ (⊃r)∇⍨⍣(×≢r)⊢⍵ ⍺⍺⍨(⊃l)∇⍨⍣(×≢l)⊢⍺} postorder← {l r←⍺ ⍵⍵ ⍵ ⋄ ⍵ ⍺⍺⍨(⊃r)∇⍨⍣(×≢r)⊢(⊃l)∇⍨⍣(×≢l)⊢⍺} lvlorder ← {0=⍴⍵:⍺ ⋄ (⊃⍺⍺⍨/(⌽⍵),⊂⍺)∇⊃∘(,/)⍣2⊢⍺∘⍵⍵¨⍵}
http://rosettacode.org/wiki/Topic_variable
Topic variable
Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language. For instance you can (but you don't have to) show how the topic variable can be used by assigning the number 3 {\displaystyle 3} to it and then computing its square and square root.
#Sidef
Sidef
say [9,16,25].map {.sqrt}; # prints: [3, 4, 5]
http://rosettacode.org/wiki/Topic_variable
Topic variable
Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language. For instance you can (but you don't have to) show how the topic variable can be used by assigning the number 3 {\displaystyle 3} to it and then computing its square and square root.
#Standard_ML
Standard ML
- 3.0; val it = 3.0 : real - it * it; val it = 9.0 : real - Math.sqrt it; val it = 3.0 : real -
http://rosettacode.org/wiki/Topic_variable
Topic variable
Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language. For instance you can (but you don't have to) show how the topic variable can be used by assigning the number 3 {\displaystyle 3} to it and then computing its square and square root.
#Tailspin
Tailspin
  3 -> \($-1! $+1!\) -> $*$ -> [$-1..$+1] -> '$; ' -> !OUT::write  
http://rosettacode.org/wiki/Topic_variable
Topic variable
Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language. For instance you can (but you don't have to) show how the topic variable can be used by assigning the number 3 {\displaystyle 3} to it and then computing its square and square root.
#UNIX_Shell
UNIX Shell
multiply 3 4 # We assume this user defined function has been previously defined echo $? # This will output 12, but $? will now be zero indicating a successful echo
http://rosettacode.org/wiki/Topic_variable
Topic variable
Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language. For instance you can (but you don't have to) show how the topic variable can be used by assigning the number 3 {\displaystyle 3} to it and then computing its square and square root.
#VBA
VBA
var T // global scope   var doSomethingWithT = Fn.new { [T * T, T.sqrt] }   T = 3 System.print(doSomethingWithT.call())
http://rosettacode.org/wiki/Topic_variable
Topic variable
Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language. For instance you can (but you don't have to) show how the topic variable can be used by assigning the number 3 {\displaystyle 3} to it and then computing its square and square root.
#Wren
Wren
var T // global scope   var doSomethingWithT = Fn.new { [T * T, T.sqrt] }   T = 3 System.print(doSomethingWithT.call())
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Ada
Ada
with Ada.Text_Io; use Ada.Text_Io;   procedure Towers is type Pegs is (Left, Center, Right); procedure Hanoi (Ndisks : Natural; Start_Peg : Pegs := Left; End_Peg : Pegs := Right; Via_Peg : Pegs := Center) is begin if Ndisks > 0 then Hanoi(Ndisks - 1, Start_Peg, Via_Peg, End_Peg); Put_Line("Move disk" & Natural'Image(Ndisks) & " from " & Pegs'Image(Start_Peg) & " to " & Pegs'Image(End_Peg)); Hanoi(Ndisks - 1, Via_Peg, End_Peg, Start_Peg); end if; end Hanoi; begin Hanoi(4); end Towers;
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
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */ /* program tonshan64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessStartPgm: .asciz "Program 64 bits start \n" szMessEndPgm: .asciz "Program normal end.\n" szMessError: .asciz "\033[31mError  !!!\n" szMessErrGen: .asciz "Error end program.\n" szMessOverflow: .asciz "Overflow function modulo.\n" szMessNoSolution: .asciz "No solution.\n" szCarriageReturn: .asciz "\n"   /* datas message display */ szMessEntry: .asciz "Number : @ modulo : @ ==> " szMessResult: .asciz "Racine 1 : @ Racine 2 : @ \n"     qNumberN: .quad 44402 qNumberP: .quad 100049 /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss .align 4 sZoneConv: .skip 24 /*******************************************/ /* code section */ /*******************************************/ .text .global main main: // program start ldr x0,qAdrszMessStartPgm // display start message bl affichageMess   mov x0,10 mov x1,13 bl displayEntry bl computeTonSha bl displayResult   mov x0,56 mov x1,101 bl displayEntry bl computeTonSha bl displayResult   mov x0,1030 mov x1,10009 bl displayEntry bl computeTonSha bl displayResult   mov x0,1032 mov x1,10009 bl displayEntry bl computeTonSha bcs 1f bl displayResult 1: ldr x4,qAdrqNumberN ldr x0,[x4] ldr x4,qAdrqNumberP ldr x1,[x4] bl displayEntry bl computeTonSha bl displayResult   ldr x0,qAdrszMessEndPgm // display end message bl affichageMess b 100f 99: // display error message ldr x0,qAdrszMessError bl affichageMess 100: // standard end of the program mov x0, #0 // return code mov x8, #EXIT // request to exit program svc 0 // perform system call qAdrszMessStartPgm: .quad szMessStartPgm qAdrszMessEndPgm: .quad szMessEndPgm qAdrszMessError: .quad szMessError qAdrszMessNoSolution: .quad szMessNoSolution qAdrszCarriageReturn: .quad szCarriageReturn qAdrqNumberN: .quad qNumberN qAdrqNumberP: .quad qNumberP   qAdrszMessResult: .quad szMessResult qAdrsZoneConv: .quad sZoneConv   /******************************************************************/ /* algorithm Tonelli–Shanks */ /******************************************************************/ /* x0 contains number */ /* x1 contains modulus */ /* x0 return root 1 */ /* x1 return root 2 */ computeTonSha: stp x10,lr,[sp,-16]! // save registres stp x2,x3,[sp,-16]! // save registres stp x4,x5,[sp,-16]! // save registres stp x6,x7,[sp,-16]! // save registres stp x8,x9,[sp,-16]! // save registres stp x11,x12,[sp,-16]! // save registres mov x9,x0 // save number mov x10,x1 // save modulo p mov x2,x10 sub x1,x2,1 lsr x1,x1,1 bl moduloPuR64 bcs 100f // error ? cmp x0,#1 bne 20f sub x5,x10,1 mov x6,#1 // s 1: lsr x5,x5,#1 // div by 2 tst x5,1 // even ? cinc x6,x6,eq // yes count beq 1b // and loop // x5 = q cmp x6,#1 // s = 1 ? bne 3f add x1,x10,1 // compute root 1 lsr x1,x1,#2 // p + 1 / 4 mov x0,x9 // n mov x2,x10 // p bl moduloPuR64 bcs 100f // error ? neg x1,x0 // compute root 2 = - root 1 b 100f // and end 3: mov x7,#3 // z 4: mov x0,x7 mov x2,x10 // p sub x1,x2,1 lsr x1,x1,1 // power = p - 1 / 2 bl moduloPuR64 bcs 100f // error ? cmp x0,#1 cinc x7,x7,eq // si égal à 1 cinc x7,x7,eq beq 4b cmp x0,0 cinc x7,x7,eq // si egal à 0 cinc x7,x7,eq beq 4b mov x0,x7 // z mov x1,x5 // q mov x2,x10 // p bl moduloPuR64 bcs 100f // error ? mov x12,x0 // c = z pow q mod p   add x1,x5,1 // = q +1 lsr x1,x1,1 // div 2 mov x0,x9 // n mov x2,x10 // p bl moduloPuR64 mov x4,x0 // r = n puis (q+1)/2 mod p   mov x0,x9 // n mov x1,x5 // = q mov x2,x10 // p bl moduloPuR64 bcs 100f // error ? mov x5,x0 // reuse r5 = t = n pow q mod p   8: // begin loop cmp x5,1 beq 10f mov x0,x5 // t mov x1,x6 // m mov x2,x10 // p bl searchI // search i for t puis 2 puis i = 1 mod p cmp x0,-1 // not find -> no solution beq 20f mov x9,x0 // i sub x8,x6,x0 // compute b sub x8,x8,1 // m - i - 1 mov x1,1 lsl x1,x1,x8 mov x0,x12 mov x2,x10 // p bl moduloPuR64 bcs 100f // error ? mov x7,x0 // b = c puis 2 puis 2 puis m-i-1 à verifier   mul x0,x7,x4 // r = r * b mod p umulh x1,x7,x4 mov x2,x10 bl divisionReg128U mov x4,x3 // r mod p mul x0,x7,x7 umulh x1,x7,x7 mov x2,x10 bl divisionReg128U mov x12,x3 // c mod p   mul x0,x5,x12 umulh x1,x5,x12 mov x2,x10 bl divisionReg128U mov x5,x3 // t mod p   mov x6,x9 // m = i b 8b 9:   10: mov x0,x4 // x0 return root 1 sub x1,x10,x0 // x1 return root 2 cmn x0,0 // carry à zero roots ok b 100f 20: ldr x0,qAdrszMessNoSolution bl affichageMess   mov x0,0 mov x1,0 cmp x0,0 // carry to 1 No solution 100: ldp x11,x12,[sp],16 ldp x8,x9,[sp],16 ldp x6,x7,[sp],16 ldp x4,x5,[sp],16 ldp x2,x3,[sp],16 ldp x10,lr,[sp],16 // restaur des 2 registres ret // retour adresse lr x30   /******************************************************************/ /* search i */ /******************************************************************/ // x0 contains t // x1 contains maxi // x2 contains modulo searchI: stp x1,lr,[sp,-16]! // save registres stp x2,x3,[sp,-16]! // save registres stp x4,x5,[sp,-16]! // save registres stp x6,x7,[sp,-16]! // save registres mov x4,x0 // t mov x6,x1 // m mov x3,1 // i 1: mov x5,1 lsl x5,x5,x3 // compute 2 power i   mov x0,x4 mov x1,x5 bl moduloPuR64 // compute t pow 2 pow i mod p cmp x0,1 // = 1 ? beq 3f // yes it is ok add x3,x3,1 // next i cmp x3,x6 blt 1b // loop mov x0,-1 // not find b 100f 3: mov x0,x3 // return i 100: ldp x6,x7,[sp],16 ldp x4,x5,[sp],16 ldp x2,x3,[sp],16 ldp x1,lr,[sp],16 // restaur des 2 registres ret // retour adresse lr x30 /******************************************************************/ /* display numbers */ /******************************************************************/ /* x0 contains number */ /* x1 contains modulo */ displayEntry: stp x0,lr,[sp,-16]! // save registres stp x1,x2,[sp,-16]! // save registres mov x2,x1 // root 2 ldr x1,qAdrsZoneConv // convert root 1 in r0 bl conversion10S // convert ascii string ldr x0,qAdrszMessEntry ldr x1,qAdrsZoneConv bl strInsertAtCharInc // and put in message mov x3,x0 mov x0,x2 // racine 2 ldr x1,qAdrsZoneConv bl conversion10S // convert ascii string mov x0,x3 ldr x1,qAdrsZoneConv bl strInsertAtCharInc // and put in message bl affichageMess 100: ldp x1,x2,[sp],16 ldp x0,lr,[sp],16 // restaur des 2 registres ret // retour adresse lr x30 qAdrszMessEntry: .quad szMessEntry /******************************************************************/ /* display roots */ /******************************************************************/ /* x0 contains root 1 */ /* x1 contains root 2 */ displayResult: stp x1,lr,[sp,-16]! // save registres stp x2,x3,[sp,-16]! // save registres mov x2,x1 // root 2 ldr x1,qAdrsZoneConv // convert root 1 in r0 bl conversion10S // convert ascii string ldr x0,qAdrszMessResult ldr x1,qAdrsZoneConv bl strInsertAtCharInc // and put in message mov x3,x0 mov x0,x2 // racine 2 ldr x1,qAdrsZoneConv bl conversion10S // convert ascii string mov x0,x3 ldr x1,qAdrsZoneConv bl strInsertAtCharInc // and put in message bl affichageMess 100: ldp x2,x3,[sp],16 ldp x1,lr,[sp],16 // restaur des 2 registres ret // retour adresse lr x30 /**************************************************************/ /********************************************************/ /* Calcul modulo de b puissance e modulo m */ /* Exemple 4 puissance 13 modulo 497 = 445 */ /********************************************************/ /* x0 nombre */ /* x1 exposant */ /* x2 modulo */ moduloPuR64: stp x1,lr,[sp,-16]! // save registres stp x3,x4,[sp,-16]! // save registres stp x5,x6,[sp,-16]! // save registres stp x7,x8,[sp,-16]! // save registres stp x9,x10,[sp,-16]! // save registres cbz x0,100f cbz x1,100f mov x8,x0 mov x7,x1 mov x6,1 // resultat udiv x4,x8,x2 msub x9,x4,x2,x8 // contient le reste 1: tst x7,1 beq 2f mul x4,x9,x6 umulh x5,x9,x6 mov x6,x4 mov x0,x6 mov x1,x5 bl divisionReg128U cbnz x1,99f // overflow mov x6,x3 2: mul x8,x9,x9 umulh x5,x9,x9 mov x0,x8 mov x1,x5 bl divisionReg128U cbnz x1,99f // overflow mov x9,x3 lsr x7,x7,1 cbnz x7,1b cmn x0,0 // carry à zero pas d'erreur mov x0,x6 // result b 100f 99: ldr x0,qAdrszMessOverflow bl affichageMess cmp x0,0 // carry à un car erreur mov x0,-1 // code erreur   100: ldp x9,x10,[sp],16 // restaur des 2 registres ldp x7,x8,[sp],16 // restaur des 2 registres ldp x5,x6,[sp],16 // restaur des 2 registres ldp x3,x4,[sp],16 // restaur des 2 registres ldp x1,lr,[sp],16 // restaur des 2 registres ret // retour adresse lr x30 qAdrszMessOverflow: .quad szMessOverflow /***************************************************/ /* division d un nombre de 128 bits par un nombre de 64 bits */ /***************************************************/ /* x0 contient partie basse dividende */ /* x1 contient partie haute dividente */ /* x2 contient le diviseur */ /* x0 retourne partie basse quotient */ /* x1 retourne partie haute quotient */ /* x3 retourne le reste */ divisionReg128U: stp x6,lr,[sp,-16]! // save registres stp x4,x5,[sp,-16]! // save registres mov x5,#0 // raz du reste R mov x3,#128 // compteur de boucle mov x4,#0 // dernier bit 1: lsl x5,x5,#1 // on decale le reste de 1 tst x1,1<<63 // test du bit le plus à gauche lsl x1,x1,#1 // on decale la partie haute du quotient de 1 beq 2f orr x5,x5,#1 // et on le pousse dans le reste R 2: tst x0,1<<63 lsl x0,x0,#1 // puis on decale la partie basse beq 3f orr x1,x1,#1 // et on pousse le bit de gauche dans la partie haute 3: orr x0,x0,x4 // position du dernier bit du quotient mov x4,#0 // raz du bit cmp x5,x2 blt 4f sub x5,x5,x2 // on enleve le diviseur du reste mov x4,#1 // dernier bit à 1 4: // et boucle subs x3,x3,#1 bgt 1b lsl x1,x1,#1 // on decale le quotient de 1 tst x0,1<<63 lsl x0,x0,#1 // puis on decale la partie basse beq 5f orr x1,x1,#1 5: orr x0,x0,x4 // position du dernier bit du quotient mov x3,x5 100: ldp x4,x5,[sp],16 // restaur des 2 registres ldp x6,lr,[sp],16 // restaur des 2 registres ret // retour adresse lr x30   /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
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
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI or android 32 bits */ /* program tonshan.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a file in arm assembly */ /************************************/ /* Constantes */ /************************************/ .include "../constantes.inc"   /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessStartPgm: .asciz "Program 32 bits start \n" szMessEndPgm: .asciz "Program normal end.\n" szMessError: .asciz "\033[31mError  !!!\n" szMessErrGen: .asciz "Error end program.\n" szMessOverflow: .asciz "Overflow function modulo.\n" szMessNoSolution: .asciz "No solution.\n" szCarriageReturn: .asciz "\n"   /* datas message display */ szMessEntry: .asciz "Number : @ modulo : @ ==> " szMessResult: .asciz "Racine 1 : @ Racine 2 : @ \n"   iNumberN: .int 1030 iNumberP: .int 10009   iNumberN1: .int 1032 iNumberP1: .int 10009   iNumberN2: .int 44402 iNumberP2: .int 100049   /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss .align 4 sZoneConv: .skip 24 /*******************************************/ /* code section */ /*******************************************/ .text .global main main: // program start ldr r0,iAdrszMessStartPgm // display start message bl affichageMess   mov r0,#10 mov r1,#13 bl displayEntry // display entry number bl computeTonSha // compute roots bl displayResult // display roots   mov r0,#56 mov r1,#101 bl displayEntry bl computeTonSha bl displayResult     ldr r4,iAdriNumberN ldr r0,[r4] ldr r4,iAdriNumberP ldr r1,[r4] bl displayEntry bl computeTonSha bl displayResult   ldr r4,iAdriNumberN1 ldr r0,[r4] ldr r4,iAdriNumberP1 ldr r1,[r4] bl displayEntry bl computeTonSha bcs 1f bl displayResult 1: ldr r4,iAdriNumberN2 ldr r0,[r4] ldr r4,iAdriNumberP2 ldr r1,[r4] bl displayEntry bl computeTonSha bl displayResult   ldr r0,iAdrszMessEndPgm // display end message bl affichageMess 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 system call iAdrszMessStartPgm: .int szMessStartPgm iAdrszMessEndPgm: .int szMessEndPgm iAdrszMessError: .int szMessError iAdrszMessNoSolution: .int szMessNoSolution iAdrszCarriageReturn: .int szCarriageReturn iAdriNumberN: .int iNumberN iAdriNumberP: .int iNumberP iAdriNumberN1: .int iNumberN1 iAdriNumberP1: .int iNumberP1 iAdriNumberN2: .int iNumberN2 iAdriNumberP2: .int iNumberP2   iAdrszMessResult: .int szMessResult iAdrsZoneConv: .int sZoneConv   /******************************************************************/ /* algorithm Tonelli–Shanks */ /******************************************************************/ /* r0 contains number */ /* r1 contains modulus */ /* r0 return root 1 */ /* r1 return root 2 */ computeTonSha: push {r2-r12,lr}   mov r9,r0 // save number mov r10,r1 // save modulo p mov r2,r10 sub r1,r2,#1 lsr r1,r1,#1 bl moduloPuR32 cmp r0,#1 bne 20f sub r5,r10,#1 mov r6,#1 // s 1: lsr r5,r5,#1 // div by 2 tst r5,#1 // even ? addeq r6,#1 beq 1b // and loop // r5 = q cmp r6,#1 // s = 1 ? bne 3f add r1,r10,#1 // compute root 1 lsr r1,r1,#2 // p + 1 / 4 mov r0,r9 // n mov r2,r10 // p bl moduloPuR32 neg r1,r0 // compute root 2 = - root 1 b 100f // and end 3: mov r7,#3 // z 4: mov r0,r7 mov r2,r10 // p sub r1,r2,#1 lsr r1,r1,#1 // power = p - 1 / 2 bl moduloPuR32 cmp r0,#1 addeq r7,#2 beq 4b cmp r0,#0 addeq r7,#2 beq 4b mov r0,r7 // z mov r1,r5 // q mov r2,r10 // p bl moduloPuR32 mov r12,r0 // c = z pow q mod p   add r1,r5,#1 // = q +1 lsr r1,r1,#1 // div 2 mov r0,r9 // n mov r2,r10 // p bl moduloPuR32 mov r4,r0 // r = n puis (q+1)/2 mod p   mov r0,r9 // n mov r1,r5 // = q mov r2,r10 // p bl moduloPuR32 mov r5,r0 // reuse r5 = t = n pow q mod p   8: // begin loop cmp r5,#1 beq 10f mov r0,r5 // t mov r1,r6 // m mov r2,r10 // p bl searchI // search i for t puis 2 puis i = 1 mod p cmp r0,#-1 // not find -> no solution beq 20f mov r9,r0 // i sub r8,r6,r0 // compute b sub r8,r8,#1 // m - i - 1 mov r1,#1 lsl r1,r1,r8 mov r0,r12 mov r2,r10 // p bl moduloPuR32 mov r7,r0 // b = c puis 2 puis 2 puis m-i-1 à verifier   umull r0,r1,r7,r4 // r = r * b mod p mov r2,r10 bl division32R mov r4,r2 // r mod p umull r0,r1,r7,r7 mov r2,r10 bl division32R mov r12,r2 // c mod p   umull r0,r1,r5,r12 mov r2,r10 bl division32R mov r5,r2 // t mod p   mov r6,r9 // m = i b 8b 9:   10: mov r0,r4 // r0 return root 1 sub r1,r10,r0 // r1 return root 2 cmn r0,#0 // carry à zero roots ok b 100f 20: ldr r0,iAdrszMessNoSolution bl affichageMess   mov r0,#0 mov r1,#0 cmp r0,#0 // carry to 1 No solution 100: pop {r2-r12,lr} // restaur registers bx lr // return /******************************************************************/ /* search i */ /******************************************************************/ // r0 contains t // r1 contains maxi // r2 contains modulo // r0 return i searchI: push {r1-r6,lr}   mov r4,r0 // t mov r6,r1 // m mov r3,#1 // i 1: mov r5,#1 lsl r5,r5,r3 // compute 2 power i   mov r0,r4 mov r1,r5 bl moduloPuR32 // compute t pow 2 pow i mod p cmp r0,#1 // = 1 ? beq 3f // yes it is ok add r3,r3,#1 // next i cmp r3,r6 blt 1b // loop mov r0,#-1 // not find b 100f 3: mov r0,r3 // return i 100: pop {r1-r6,lr} // restaur registers bx lr // return /******************************************************************/ /* display numbers */ /******************************************************************/ /* r0 contains number */ /* r1 contains modulo */ displayEntry: push {r0-r3,lr} mov r2,r1 // root 2 ldr r1,iAdrsZoneConv // convert root 1 in r0 bl conversion10S // convert ascii string ldr r0,iAdrszMessEntry ldr r1,iAdrsZoneConv bl strInsertAtCharInc // and put in message mov r3,r0 mov r0,r2 // racine 2 ldr r1,iAdrsZoneConv bl conversion10S // convert ascii string mov r0,r3 ldr r1,iAdrsZoneConv bl strInsertAtCharInc // and put in message bl affichageMess 100: pop {r0-r3,lr} // restaur registers bx lr // return iAdrszMessEntry: .int szMessEntry /******************************************************************/ /* display roots */ /******************************************************************/ /* r0 contains root 1 */ /* r1 contains root 2 */ displayResult: push {r1-r3,lr} mov r2,r1 // root 2 ldr r1,iAdrsZoneConv // convert root 1 in r0 bl conversion10S // convert ascii string ldr r0,iAdrszMessResult ldr r1,iAdrsZoneConv bl strInsertAtCharInc // and put in message mov r3,r0 mov r0,r2 // racine 2 ldr r1,iAdrsZoneConv bl conversion10S // convert ascii string mov r0,r3 ldr r1,iAdrsZoneConv bl strInsertAtCharInc // and put in message bl affichageMess 100:   pop {r1-r3,lr} // restaur registers bx lr // return /********************************************************/ /* Calcul modulo de b puissance e modulo m */ /* Exemple 4 puissance 13 modulo 497 = 445 */ /* */ /********************************************************/ /* r0 nombre */ /* r1 exposant */ /* r2 modulo */ /* r0 return result */ moduloPuR32: push {r1-r7,lr} @ save registers cmp r0,#0 @ verif <> zero beq 90f cmp r1,#0 @ verif <> zero moveq r0,#0 beq 90f cmp r2,#0 @ verif <> zero moveq r0,#0 beq 90f @ 1: mov r4,r2 @ save modulo mov r5,r1 @ save exposant mov r6,r0 @ save base mov r3,#1 @ start result   mov r1,#0 @ division de r0,r1 par r2 bl division32R mov r6,r2 @ base <- remainder 2: tst r5,#1 @ exposant even or odd beq 3f umull r0,r1,r6,r3 mov r2,r4 bl division32R mov r3,r2 @ result <- remainder 3: umull r0,r1,r6,r6 mov r2,r4 bl division32R mov r6,r2 @ base <- remainder   lsr r5,#1 @ left shift 1 bit cmp r5,#0 @ end ? bne 2b mov r0,r3 90: cmn r0,#0 @ no error 100: @ fin standard de la fonction pop {r1-r7,lr} @ restaur des registres bx lr @ retour de la fonction en utilisant lr   /***************************************************/ /* division number 64 bits in 2 registers by number 32 bits */ /***************************************************/ /* r0 contains lower part dividende */ /* r1 contains upper part dividende */ /* r2 contains divisor */ /* r0 return lower part quotient */ /* r1 return upper part quotient */ /* r2 return remainder */ division32R: push {r3-r9,lr} @ save registers mov r6,#0 @ init upper upper part remainder  !! mov r7,r1 @ init upper part remainder with upper part dividende mov r8,r0 @ init lower part remainder with lower part dividende mov r9,#0 @ upper part quotient mov r4,#0 @ lower part quotient mov r5,#32 @ bits number 1: @ begin loop lsl r6,#1 @ shift upper upper part remainder lsls r7,#1 @ shift upper part remainder orrcs r6,#1 lsls r8,#1 @ shift lower part remainder orrcs r7,#1 lsls r4,#1 @ shift lower part quotient lsl r9,#1 @ shift upper part quotient orrcs r9,#1 @ divisor sustract upper part remainder subs r7,r2 sbcs r6,#0 @ and substract carry bmi 2f @ négative ?   @ positive or equal orr r4,#1 @ 1 -> right bit quotient b 3f 2: @ negative orr r4,#0 @ 0 -> right bit quotient adds r7,r2 @ and restaur remainder adc r6,#0 3: subs r5,#1 @ decrement bit size bgt 1b @ end ? mov r0,r4 @ lower part quotient mov r1,r9 @ upper part quotient mov r2,r7 @ remainder 100: @ function end pop {r3-r9,lr} @ restaur registers bx lr /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"  
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
#ALGOL_68
ALGOL 68
BEGIN # returns s parsed according to delimiter and escape # PROC parse with escapes = ( STRING s, CHAR delimiter, escape )[]STRING: IF ( UPB s - LWB s ) + 1 < 1 THEN # empty string # [ 1 : 0 ]STRING empty array; empty array ELSE # at least one character # # allow for a string composed entirely of delimiter characters # [ 1 : ( UPB s - LWB s ) + 3 ]STRING result; INT r pos := 1; INT s pos := LWB s; result[ r pos ] := ""; WHILE s pos <= UPB s DO CHAR c = s[ s pos ]; IF c = delimiter THEN # start a new element # result[ r pos +:= 1 ] := "" ELIF c = escape THEN # use the next character even if it is an escape # s pos +:= 1; IF s pos < UPB s THEN # the escape is not the last character # result[ r pos ] +:= s[ s pos ] FI ELSE # normal character # result[ r pos ] +:= c FI; s pos +:= 1 OD; result[ 1 : r pos ] FI; # parse with escapes # # task test case # []STRING tokens = parse with escapes( "one^|uno||three^^^^|four^^^|^cuatro|", "|", "^" ); FOR t pos FROM LWB tokens TO UPB tokens DO print( ( "[", tokens[ t pos ], "]", newline ) ) OD 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
#Go
Go
package main   import ( "flag" "fmt" "math" "runtime" "sort" )   // Note, the standard "image" package has Point and Rectangle but we // can't use them here since they're defined using int rather than // float64.   type Circle struct{ X, Y, R, rsq float64 }   func NewCircle(x, y, r float64) Circle { // We pre-calculate r² as an optimization return Circle{x, y, r, r * r} }   func (c Circle) ContainsPt(x, y float64) bool { return distSq(x, y, c.X, c.Y) <= c.rsq }   func (c Circle) ContainsC(c2 Circle) bool { return distSq(c.X, c.Y, c2.X, c2.Y) <= (c.R-c2.R)*(c.R-c2.R) }   func (c Circle) ContainsR(r Rect) (full, corner bool) { nw := c.ContainsPt(r.NW()) ne := c.ContainsPt(r.NE()) sw := c.ContainsPt(r.SW()) se := c.ContainsPt(r.SE()) return nw && ne && sw && se, nw || ne || sw || se }   func (c Circle) North() (float64, float64) { return c.X, c.Y + c.R } func (c Circle) South() (float64, float64) { return c.X, c.Y - c.R } func (c Circle) West() (float64, float64) { return c.X - c.R, c.Y } func (c Circle) East() (float64, float64) { return c.X + c.R, c.Y }   type Rect struct{ X1, Y1, X2, Y2 float64 }   func (r Rect) Area() float64 { return (r.X2 - r.X1) * (r.Y2 - r.Y1) } func (r Rect) NW() (float64, float64) { return r.X1, r.Y2 } func (r Rect) NE() (float64, float64) { return r.X2, r.Y2 } func (r Rect) SW() (float64, float64) { return r.X1, r.Y1 } func (r Rect) SE() (float64, float64) { return r.X2, r.Y1 }   func (r Rect) Centre() (float64, float64) { return (r.X1 + r.X2) / 2.0, (r.Y1 + r.Y2) / 2.0 }   func (r Rect) ContainsPt(x, y float64) bool { return r.X1 <= x && x < r.X2 && r.Y1 <= y && y < r.Y2 }   func (r Rect) ContainsPC(c Circle) bool { // only N,W,E,S points of circle return r.ContainsPt(c.North()) || r.ContainsPt(c.South()) || r.ContainsPt(c.West()) || r.ContainsPt(c.East()) }   func (r Rect) MinSide() float64 { return math.Min(r.X2-r.X1, r.Y2-r.Y1) }   func distSq(x1, y1, x2, y2 float64) float64 { Δx, Δy := x2-x1, y2-y1 return (Δx * Δx) + (Δy * Δy) }   type CircleSet []Circle   // sort.Interface for sorting by radius big to small: func (s CircleSet) Len() int { return len(s) } func (s CircleSet) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s CircleSet) Less(i, j int) bool { return s[i].R > s[j].R }   func (sp *CircleSet) RemoveContainedC() { s := *sp sort.Sort(s) for i := 0; i < len(s); i++ { for j := i + 1; j < len(s); { if s[i].ContainsC(s[j]) { s[j], s[len(s)-1] = s[len(s)-1], s[j] s = s[:len(s)-1] } else { j++ } } } *sp = s }   func (s CircleSet) Bounds() Rect { x1 := s[0].X - s[0].R x2 := s[0].X + s[0].R y1 := s[0].Y - s[0].R y2 := s[0].Y + s[0].R for _, c := range s[1:] { x1 = math.Min(x1, c.X-c.R) x2 = math.Max(x2, c.X+c.R) y1 = math.Min(y1, c.Y-c.R) y2 = math.Max(y2, c.Y+c.R) } return Rect{x1, y1, x2, y2} }   var nWorkers = 4   func (s CircleSet) UnionArea(ε float64) (min, max float64) { sort.Sort(s) stop := make(chan bool) inside := make(chan Rect) outside := make(chan Rect) unknown := make(chan Rect, 5e7) // XXX   for i := 0; i < nWorkers; i++ { go s.worker(stop, unknown, inside, outside) } r := s.Bounds() max = r.Area() unknown <- r for max-min > ε { select { case r = <-inside: min += r.Area() case r = <-outside: max -= r.Area() } } close(stop) return min, max }   func (s CircleSet) worker(stop <-chan bool, unk chan Rect, in, out chan<- Rect) { for { select { case <-stop: return case r := <-unk: inside, outside := s.CategorizeR(r) switch { case inside: in <- r case outside: out <- r default: // Split midX, midY := r.Centre() unk <- Rect{r.X1, r.Y1, midX, midY} unk <- Rect{midX, r.Y1, r.X2, midY} unk <- Rect{r.X1, midY, midX, r.Y2} unk <- Rect{midX, midY, r.X2, r.Y2} } } } }   func (s CircleSet) CategorizeR(r Rect) (inside, outside bool) { anyCorner := false for _, c := range s { full, corner := c.ContainsR(r) if full { return true, false // inside } anyCorner = anyCorner || corner } if anyCorner { return false, false // uncertain } for _, c := range s { if r.ContainsPC(c) { return false, false // uncertain } } return false, true // outside }   func main() { flag.IntVar(&nWorkers, "workers", nWorkers, "how many worker go routines to use") maxproc := flag.Int("cpu", runtime.NumCPU(), "GOMAXPROCS setting") flag.Parse()   if *maxproc > 0 { runtime.GOMAXPROCS(*maxproc) } else { *maxproc = runtime.GOMAXPROCS(0) }   circles := CircleSet{ NewCircle(1.6417233788, 1.6121789534, 0.0848270516), NewCircle(-1.4944608174, 1.2077959613, 1.1039549836), NewCircle(0.6110294452, -0.6907087527, 0.9089162485), NewCircle(0.3844862411, 0.2923344616, 0.2375743054), NewCircle(-0.2495892950, -0.3832854473, 1.0845181219), NewCircle(1.7813504266, 1.6178237031, 0.8162655711), NewCircle(-0.1985249206, -0.8343333301, 0.0538864941), NewCircle(-1.7011985145, -0.1263820964, 0.4776976918), NewCircle(-0.4319462812, 1.4104420482, 0.7886291537), NewCircle(0.2178372997, -0.9499557344, 0.0357871187), NewCircle(-0.6294854565, -1.3078893852, 0.7653357688), NewCircle(1.7952608455, 0.6281269104, 0.2727652452), NewCircle(1.4168575317, 1.0683357171, 1.1016025378), NewCircle(1.4637371396, 0.9463877418, 1.1846214562), NewCircle(-0.5263668798, 1.7315156631, 1.4428514068), NewCircle(-1.2197352481, 0.9144146579, 1.0727263474), NewCircle(-0.1389358881, 0.1092805780, 0.7350208828), NewCircle(1.5293954595, 0.0030278255, 1.2472867347), NewCircle(-0.5258728625, 1.3782633069, 1.3495508831), NewCircle(-0.1403562064, 0.2437382535, 1.3804956588), NewCircle(0.8055826339, -0.0482092025, 0.3327165165), NewCircle(-0.6311979224, 0.7184578971, 0.2491045282), NewCircle(1.4685857879, -0.8347049536, 1.3670667538), NewCircle(-0.6855727502, 1.6465021616, 1.0593087096), NewCircle(0.0152957411, 0.0638919221, 0.9771215985), } fmt.Println("Starting with", len(circles), "circles.") circles.RemoveContainedC() fmt.Println("Removing redundant ones leaves", len(circles), "circles.") fmt.Println("Using", nWorkers, "workers with maxprocs =", *maxproc) const ε = 0.0001 min, max := circles.UnionArea(ε) avg := (min + max) / 2.0 rng := max - min fmt.Printf("Area = %v±%v\n", avg, rng) fmt.Printf("Area ≈ %.*f\n", 5, avg) }
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]
#Bracmat
Bracmat
( ("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.) (cycle-11.cycle-12) (cycle-12.cycle-11) (cycle-21.dw01 cycle-22 dw02 dw03) (cycle-22.cycle-21 dw01 dw04)  : ?libdeps & :?indeps & ( toposort = A Z res module dependants todo done .  !arg:(?todo.?done) & ( areDone = .  !arg: |  !arg  : ( %@  : [%( !module+!done+!indeps:?+(? !sjt ?)+? | ~(!libdeps:? (!sjt.?) ?) & !sjt !indeps:?indeps ) )  ?arg & areDone$!arg ) & (  !todo  :  ?A (?module.?dependants&areDone$!dependants) ( ?Z & toposort$(!A !Z.!done !module):?res ) & !res | (!todo.!done) ) ) & toposort$(!libdeps.):(?cycles.?res) & out$(" compile order:" !indeps !res "\ncycles:" !cycles) );
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.
#EDSAC_order_code
EDSAC order code
  [Attempt at Turing machine for Rosetta Code.] [EDSAC program, Initial Orders 2.]   [Library subroutine M3 prints header and is then overwritten.] PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF *!!NR!STEPS@&#..PZ [..PZ marks end of header]   T48K [& (delta) parameter: Turing machine tape.] P8F [Overwrites most of initial orders.]   T50K [X parameter: once-only code.] P100F [Gets overwritten by the Turing machine tape.]   [Put the following as high in memory as possible, to make room for the Turing machine tape.] T52K [A parameter: rules and initial pattern. Also marks end] P781F [of Turing tape, so must go immediately after tape area.]   T55K [V parameter: program-wide variables.] P810F [Even address, 9 locations]   T46K [N parameter: constants.] P820F [Even address]   T47K [M parameter: main routine.] P859F   T51K [G parameter: library subroutine P7] P988F [Even address, 35 locations.]   [============================= A parameter ===============================] E25K TA GK [0] [End of Turing tape area] [Comment-in the desired task, or add another (2 symbols only).] [Counts are stored in the address field.] [Each rule is defined by an EDSAC pseudo-order, as follows: Function letter: L = left, R = right, S = stay Address field = new state number Code letter: F if new symbol = 0, D if new symbol = 1. No rule is needed for the halt state.] [0] [Simple incrementer: states are q0 = 0, qf = halt = 1 P1F [1 state, excluding the halt state S1D RD [2 rules for each state (symbols 0 and 1) P1F [1 word in tape area to be initialized PF P3D [location 0 relative to tape, init to 7] [3-state busy beaver: states are a = 0, b = 1, c = 2, halt = 3] P3F [3 states, excluding the halt state] R1D L2D [2 rules for each state (symbols 0 and 1)] L0D R1D L1D S3D PF [0 words to be initialized (start with empty tape)] [5-state busy beaver: states are A = 0, ..., E = 4, halt = 5 P5F 5 states, excluding the halt state R1D L2D 2 rules for each state (symbols 0 and 1) R2D R1D R3D L4F L0D L3D S5D L0F PF 0 words to be initialized (start with empty tape)]   [============================= X parameter ===============================] E25K TX GK [The following once-only code is loaded into the Turing machine tape area.] [It runs at start-up, then gets overwritten when the tape is cleared.] [Enter with acc = 0.] [0] T2V [initial state assumed to be state 0] T3V [tape head starts at position 0 on Turing tape] T#V [reset count of steps] T4V [initialize maximum position] T5V [initialize minimum position] [Calculate number of available tape positions; store in address field] A22N [T order for exclusive end of tape] S21N [T order for start of tape] L4F [times 16, since each location holds 16 positions] T25N [store for later use] [Set up the loop in the main program that writes the initial pattern. The main program has a list of position-value pairs. This follows the list of rules, 2 rules per Turing machine state.] [9] AA [number of states] LD [times 2, because 2 rules per state] A2F [plus 1 for the count of states] A9@ [make A order to load number of position-value pairs] T14@ [plant order] [14] AM [load number of pairs (in address field)] LD [times 2 for length of table] TF [temp store in 0F] A14@ [load order that was planted above] A2F [make order to load first position] U13M [plant in main routine] AF [make A order for exclusive end] T28M [plant in main routine] [Set up order to load rules] A26@ A2F T18N [Here with acc = 0. Jump to main routine.] EM [26] AA   [============================= V parameter ===============================] E25K TV GK [0] PFPF [number of steps (35-bit, must be at even address)] [2] PF [current state of Turing machine] [3] PF [current tape position, stored in address field] [4] PF [maximum position on the tape so far] [5] PF [minimum position on the tape so far] [6] PF [rule for current state and symbol] [7] PF [working group of 16 cells (1 EDSAC location)] [8] PF [mask to select bit for current cell]   [============================= N parameter ===============================] E25K TN GK [17-bit masks: 11111111111111110, 11111111111111101, ..., 10111111111111111] [0] V2047F V2046D V2045D V2043D V2039D V2031D V2015D V1983D V1919D V1791D V1535D V1023D C2047D B2047D G2047D M2047D [16] OF [add to A order to make T order with same address] [17] AN [A order to load first mask in table] [18] AF [A order to load first rule] [19] A& [A order for start of tape] [20] AA [A order for end of tape] [21] T& [T order for start of tape] [22] TA [T order for exclusive end of tape] [23] P2047F [mask to pick out state from a Turing machine rule] [24] P15F [mask to extract bit number from position] [25] PF [number of tape positions available (calculated)] [26] @F [carriage return] [27] &F [line feed] [28] K4096F [null] [29] K2048F [set letters on teleprinter]   [============================= M parameter ===============================] E25K TM GK [Once-only code jumps to here with acc = 0] [Clear the tape; this overwrites the once-only code] [0] A21N [load T order for start of tape] E3@ [always jump (since T > 0)] [2] A22N [loop here after testing for end] [3] T4@ [plant order to clear 1 location] [4] TF [execute order] A4@ [load order just executed] A2F [inc address] S22N [test for end] G2@ [if not end, loop back] [Here with acc = 0] [Set up the starting pattern, i.e write 1's at zero or more positions on the tape.] [To save space, the orders marked (*) are set up by the once-only code.] [9] A13@ [load A order for next relative addess] S28@ [compare with A order for exclusive end] E29@ [if all done, jump out with acc = 0] TF [clear acc] [13] AF [(*) load relative address from table] G17@ [jump if < 0] A21N [make T order, addr counted from low end of tape] E18@ [join commoon code (always jumps since T > 0)] [17] A22N [make T order, addr counted from high end of tape] [18] T23@ [plant T order in code] A13@ [make order to load value from table] A2F T22@ [plant in code] [22] AF [load value from table] [23] TF [store in tape] A22@ [make A order for next address] A2F T13@ [plant in code] E9@ [always loop back] [28] AF [(*) A order for exclusive end of list] [29] [Next step, i.e. set up new symbol, state and tape position.] [Acc must be 0 here.] [Get tape position and deduce corresponding EDSAC location and bit number.] [29] H24N [mask for bit number] C3V [acc := bit number] UF [save bit number in 0F address field] A17N [make order to load from mask table] T44@ [plant order in code] A3V [position] SF [remove bit number part] R4F [divide by 16 for relative address] [If it's a non-negative address, add it to the start of the tape in EDSAC memory.] [If it's a negative address, add it to the end of the tape.] G40@ [jump if negative address] A19N [make A order to load from tape] G41@ [always jump to common code, since A < 0] [40] A20N [here if negative address] [41] U46@ [store order to load current group of 16 bits] A16N [convert to T order at same address] T69@ [store T order (a fair way down the code)] [44] AF [load mask] T8V [46] AF [load group] T7V [Get rule for this state and symbol (where symbol = 0 or 1)] H8V C7V [acc := bit group with current bit cleared] S7V [acc := 0 if bit is 0, -1 if bit is 1] E54@ TF [clear acc] A2F [to inc rule address if symbol is 1] [54] A2V [add state twice (because each state has 2 rules)] A2V A18N [manufacture A order to load rule] T58@ [58] AF [load rule] T6V [to work space] [Write new symbol (0 or 1) to tape. New symbol is in low bit of rule.] HN [H register := 111...1110] C6V S6V [result = 0 if new symbol is 0; -1 if it's 1] H8V [H register = mask 1...101...1 for current bit] G67@ [jump to set the bit] C7V [clear the bit] E69@ [always jump (because top bit in tape store is always 0)] [Set bit, assuming acc = -1 here (reason why it works is a bit complicated)] [67] C7V S8V [69] TF [manufactured order] [Update position of tape head, i.e. inc by 1, dec by 1, or no change.] [Move is in top 2 bits of rule, thus] [1x = move left, i.e. dec position (function letter can be L)] [00 = move right, i.e. inc position (function letter can be R)] [01 = stay, i.e. don't change position (function letter can be S)] A6V G83@ [left if top bit is 1] [72] LD [else test next bit] G95@ [skip move if next bit is 1] [74] TF [here to move right] A3V [inc position] A2F U3V [Here we update the maximum position if latest >= maximum.] [This is unnecessary if latest = maximum, but code is simpler this way.] S4V [test against maximum position] G95@ [skip if latest < maximum] A4V [restore after test] T4V [update maximum] E91@ [always jump, to check for overflow] [83] TF [here to move left] A3V [dec position] S2F [86] U3V S5V [test against current minimum position] E95@ [jump if >= minimum] A5V [restore acc after test] T5V [update minimum] [After updating maximum or minimum position, check that available memory hasn't been exceeded.] [91] A4V [maximum position] S5V [subtract minimum position] S25N [compare against number available] E107@ [jump out if overflow] [The next order also serves as a constant] [95] TF [clear acc for next part] [Increment the number of steps] A#V YFYF T#V [Finally set the new state.] [100] H23N [mask for state bits in rule] C6V [acc := new state] SA [is it the last state?] E111@ [if yes, halt the Turing machine] AA [restore acc after test] T2V [update state] E29@ [loop back for next step] [Overflow, i.e. non-negative tape positions (ascending in EDSAC memory) collide with negative tape positions (descending).] [107] O29N [set teleprinter to letters] O107@ ON [print 'OV' to indicate overflow] E116@ [jump to exit] [Print number of steps] [111] TF A#V [clear accc, load number of steps] TD [number of steps to 0D for print subroutine [114] A114 @GG [call print subroutine] [116] O26N O27N [print CR, LF] O28N [print null to flush teleprinter buffer] ZF [stop]   [============================= G parameter ===============================] E25K TG [Library subroutine P7. 35 locations, even address. WWG page 18.] [Prints non-negative integer, up to 10 digits, right-justified.] GKA3FT26@H28#@NDYFLDT4DS27@TFH8@S8@T1FV4DAFG31@SFLDUFOFFFSFL4F T4DA1FA27@G11@XFT28#ZPFT27ZP1024FP610D@524D!FO30@SFL8FE22@   [========================== X parameter again ===============================] E25K TX GK EZ [define entry point] PF [enter with acc = 0] [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).
#C.2B.2B
C++
#include <cassert> #include <iomanip> #include <iostream> #include <vector>   class totient_calculator { public: explicit totient_calculator(int max) : totient_(max + 1) { for (int i = 1; i <= max; ++i) totient_[i] = i; for (int i = 2; i <= max; ++i) { if (totient_[i] < i) continue; for (int j = i; j <= max; j += i) totient_[j] -= totient_[j] / i; } } int totient(int n) const { assert (n >= 1 && n < totient_.size()); return totient_[n]; } bool is_prime(int n) const { return totient(n) == n - 1; } private: std::vector<int> totient_; };   int count_primes(const totient_calculator& tc, int min, int max) { int count = 0; for (int i = min; i <= max; ++i) { if (tc.is_prime(i)) ++count; } return count; }   int main() { const int max = 10000000; totient_calculator tc(max); std::cout << " n totient prime?\n"; for (int i = 1; i <= 25; ++i) { std::cout << std::setw(2) << i << std::setw(9) << tc.totient(i) << std::setw(8) << (tc.is_prime(i) ? "yes" : "no") << '\n'; } for (int n = 100; n <= max; n *= 10) { std::cout << "Count of primes up to " << n << ": " << count_primes(tc, 1, n) << '\n'; } return 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
#J
J
swops =: ((|.@:{. , }.)~ {.)^:a:
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.
#BQN
BQN
⟨sin, cos, tan⟩ ← •math Sin 0 0 Sin π÷2 1 Cos 0 1 Cos π÷2 6.123233995736766e¯17 Tan 0 0 Tan π÷2 16331239353195370 Sin⁼ 0 0 Sin⁼ 1 1.5707963267948966 Cos⁼ 1 0 Cos⁼ 0 1.5707963267948966 Tan⁼ 0 0 Tan⁼ ∞ 1.5707963267948966
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).
#ERRE
ERRE
  !Trabb Pardo-Knuth algorithm PROGRAM TPK !VAR I%,Y DIM A[10]   FUNCTION F(T) F=SQR(ABS(T))+5*T^3 END FUNCTION   BEGIN DATA(10,-1,1,2,3,4,4.3,4.305,4.303,4.302,4.301) FOR I%=0 TO 10 DO READ(A[I%]) END FOR FOR I%=10 TO 0 STEP -1 DO Y=F(A[I%]) PRINT("F(";A[I%];")=";) IF Y>400 THEN PRINT("--->too large<---") ELSE PRINT(Y) END IF END FOR END PROGRAM  
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).
#F.23
F#
  module ``Trabb Pardo - Knuth`` open System let f (x: float) = sqrt(abs x) + (5.0 * (x ** 3.0))   Console.WriteLine "Enter 11 numbers:" [for _ in 1..11 -> Convert.ToDouble(Console.ReadLine())] |> List.rev |> List.map f |> List.iter (function | n when n <= 400.0 -> Console.WriteLine(n) | _ -> Console.WriteLine("Overflow"))  
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.
#REXX
REXX
/*REXX program solves the "Twelve Statement Puzzle". */ q=12; @stmt=right('statement',20) /*number of statements in the puzzle. */ m=0 /*[↓] statement one is TRUE by fiat.*/ do pass=1 for 2 /*find the maximum number of "trues". */ do e=0 for 2**(q-1); n = '1'right( x2b( d2x( e ) ), q-1, 0) do b=1 for q /*define various bits in the number Q.*/ @.b=substr(n, b, 1) /*define a particular @ bit (in Q).*/ end /*b*/ if @.1 then if yeses(1, 1) \==1 then iterate if @.2 then if yeses(7, 12) \==3 then iterate if @.3 then if yeses(2, 12,2) \==2 then iterate if @.4 then if yeses(5, 5) then if yeses(6, 7) \==2 then iterate if @.5 then if yeses(2, 4) \==0 then iterate if @.6 then if yeses(1, 12,2) \==4 then iterate if @.7 then if yeses(2, 3) \==1 then iterate if @.8 then if yeses(7, 7) then if yeses(5,6) \==2 then iterate if @.9 then if yeses(1, 6) \==3 then iterate if @.10 then if yeses(11,12) \==2 then iterate if @.11 then if yeses(7, 9) \==1 then iterate if @.12 then if yeses(1, 11) \==4 then iterate g=yeses(1, 12) if pass==1 then do; m=max(m,g); iterate; end else if g\==m then iterate do j=1 for q; z=substr(n, j, 1) if z then say @stmt right(j, 2) " is " word('false true', 1 + z) end /*tell*/ end /*e*/ end /*pass*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ yeses: parse arg L,H,B; #=0; do i=L to H by word(B 1, 1); #=#[email protected]; end; return #
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.
#Perl
Perl
#!/usr/bin/perl   sub truth_table { my $s = shift; my (%seen, @vars); for ($s =~ /([a-zA-Z_]\w*)/g) { $seen{$_} //= do { push @vars, $_; 1 }; }   print "\n", join("\t", @vars, $s), "\n", '-' x 40, "\n"; @vars = map("\$$_", @vars);   $s =~ s/([a-zA-Z_]\w*)/\$$1/g; $s = "print(".join(',"\t", ', map("($_?'T':'F')", @vars, $s)).",\"\\n\")"; $s = "for my $_ (0, 1) { $s }" for (reverse @vars); eval $s; }   truth_table 'A ^ A_1'; truth_table 'foo & bar | baz'; truth_table 'Jim & (Spock ^ Bones) | Scotty';
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
#PicoLisp
PicoLisp
(load "@lib/simul.l")   (de ceil (A) (/ (+ A 1) 2) )   (de prime? (N) (or (= N 2) (and (> N 1) (bit? 1 N) (let S (sqrt N) (for (D 3 T (+ D 2)) (T (> D S) T) (T (=0 (% N D)) NIL) ) ) ) ) )   (de ulam (N) (let (G (grid N N) D '(north west south east .) M (ceil N) ) (setq This (intern (pack (char (+ 96 (if (bit? 1 N) M (inc M))) ) M ) ) ) (=: V '_) (with ((car D) This) (for (X 2 (>= (* N N) X) (inc X)) (=: V (if (prime? X) '. '_)) (setq This (or (with ((cadr D) This) (unless (: V) (pop 'D) This) ) ((pop D) This) ) ) ) ) G ) )   (mapc '((L) (for This L (prin (align 3 (: V))) ) (prinl) ) (ulam 9) )   (bye)
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.]
#Haskell
Haskell
import Data.Numbers.Primes(primes, isPrime) import Data.List import Control.Arrow   primes1e6 = reverse. filter (notElem '0'. show) $ takeWhile(<=1000000) primes   rightT, leftT :: Int -> Bool rightT = all isPrime. takeWhile(>0). drop 1. iterate (`div`10) leftT x = all isPrime. takeWhile(<x).map (x`mod`) $ iterate (*10) 10   main = do let (ltp, rtp) = (head. filter leftT &&& head. filter rightT) primes1e6 putStrLn $ "Left truncatable " ++ show ltp putStrLn $ "Right truncatable " ++ show rtp
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.
#AppleScript
AppleScript
on run -- Sample tree of integers set tree to node(1, ¬ {node(2, ¬ {node(4, {node(7, {})}), ¬ node(5, {})}), ¬ node(3, ¬ {node(6, {node(8, {}), ¬ node(9, {})})})})     -- Output of AppleScript code at Rosetta Code task -- 'Visualize a Tree': set strTree to unlines({¬ " ┌ 4 ─ 7", ¬ " ┌ 2 ┤", ¬ " │ └ 5", ¬ " 1 ┤", ¬ " │ ┌ 8", ¬ " └ 3 ─ 6 ┤", ¬ " └ 9"})   script tabulate on |λ|(s, xs) justifyRight(14, space, s & ": ") & unwords(xs) end |λ| end script   set strResult to strTree & linefeed & unlines(zipWith(tabulate, ¬ ["preorder", "inorder", "postorder", "level-order"], ¬ apList([¬ foldTree(preorder), ¬ foldTree(inorder), ¬ foldTree(postorder), ¬ levelOrder], [tree])))   set the clipboard to strResult return strResult end run     ---------------------- TREE TRAVERSAL ----------------------   -- preorder :: a -> [[a]] -> [a] on preorder(x, xs) {x} & concat(xs) end preorder     -- inorder :: a -> [[a]] -> [a] on inorder(x, xs) if {} ≠ xs then item 1 of xs & x & concat(rest of xs) else {x} end if end inorder     -- postorder :: a -> [[a]] -> [a] on postorder(x, xs) concat(xs) & {x} end postorder     -- levelOrder :: Tree a -> [a] on levelOrder(tree) concat(levels(tree)) end levelOrder     -- foldTree :: (a -> [b] -> b) -> Tree a -> b on foldTree(f) script on |λ|(tree) script go property g : |λ| of mReturn(f) on |λ|(oNode) g(root of oNode, |λ|(nest of oNode) ¬ of map(go)) end |λ| end script |λ|(tree) of go end |λ| end script end foldTree     ------------------------- GENERIC --------------------------   -- Node :: a -> [Tree a] -> Tree a on node(v, xs) {type:"Node", root:v, nest:xs} end node     -- e.g. [(*2),(/2), sqrt] <*> [1,2,3] -- --> ap([dbl, hlf, root], [1, 2, 3]) -- --> [2,4,6,0.5,1,1.5,1,1.4142135623730951,1.7320508075688772]   -- Each member of a list of functions applied to -- each of a list of arguments, deriving a list of new values -- apList (<*>) :: [(a -> b)] -> [a] -> [b] on apList(fs, xs) set lst to {} repeat with f in fs tell mReturn(contents of f) repeat with x in xs set end of lst to |λ|(contents of x) end repeat end tell end repeat return lst end apList     -- concat :: [[a]] -> [a] -- concat :: [String] -> String on concat(xs) set lng to length of xs if 0 < lng and string is class of (item 1 of xs) then set acc to "" else set acc to {} end if repeat with i from 1 to lng set acc to acc & item i of xs end repeat acc end concat     -- foldr :: (a -> b -> b) -> b -> [a] -> b on foldr(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from lng to 1 by -1 set v to |λ|(item i of xs, v, i, xs) end repeat return v end tell end foldr     -- justifyRight :: Int -> Char -> String -> String on justifyRight(n, cFiller, strText) if n > length of strText then text -n thru -1 of ((replicate(n, cFiller) as text) & strText) else strText end if end justifyRight     -- length :: [a] -> Int on |length|(xs) set c to class of xs if list is c or string is c then length of xs else (2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite) end if end |length|     -- levels :: Tree a -> [[a]] on levels(tree) -- A list of lists, grouping the root -- values of each level of the tree. script go on |λ|(node, a) if {} ≠ a then tell a to set {h, t} to {item 1, rest} else set {h, t} to {{}, {}} end if   {{root of node} & h} & foldr(go, t, nest of node) end |λ| end script   |λ|(tree, {}) of go end levels   -- mReturn :: First-class m => (a -> b) -> m (a -> b) on mReturn(f) -- 2nd class handler function lifted into 1st class script wrapper. if script is class of f then f else script property |λ| : f end script end if end mReturn     -- map :: (a -> b) -> [a] -> [b] on map(f) -- The list obtained by applying f -- to each element of xs. script on |λ|(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 |λ| end script end map     -- min :: Ord a => a -> a -> a on min(x, y) if y < x then y else x end if end min     -- nest :: Tree a -> [a] on nest(oTree) nest of oTree end nest     -- Egyptian multiplication - progressively doubling a list, appending -- stages of doubling to an accumulator where needed for binary -- assembly of a target length -- replicate :: Int -> a -> [a] on replicate(n, a) set out to {} if 1 > n then return out set dbl to {a}   repeat while (1 < n) if 0 < (n mod 2) then set out to out & dbl set n to (n div 2) set dbl to (dbl & dbl) end repeat return out & dbl end replicate   -- root :: Tree a -> a on root(oTree) root of oTree end root     -- take :: Int -> [a] -> [a] -- take :: Int -> String -> String on take(n, xs) set c to class of xs if list is c then if 0 < n then items 1 thru min(n, length of xs) of xs else {} end if else if string is c then if 0 < n then text 1 thru min(n, length of xs) of xs else "" end if else if script is c then set ys to {} repeat with i from 1 to n set v to |λ|() of xs if missing value is v then return ys else set end of ys to v end if end repeat return ys else missing value end if end take     -- unlines :: [String] -> String on unlines(xs) -- A single string formed by the intercalation -- of a list of strings with the newline character. 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     -- unwords :: [String] -> String on unwords(xs) set {dlm, my text item delimiters} to ¬ {my text item delimiters, space} set s to xs as text set my text item delimiters to dlm return s end unwords     -- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] on zipWith(f, xs, ys) set lng to min(|length|(xs), |length|(ys)) if 1 > lng then return {} set xs_ to take(lng, xs) -- Allow for non-finite set ys_ to take(lng, ys) -- generators like cycle etc set lst to {} tell mReturn(f) repeat with i from 1 to lng set end of lst to |λ|(item i of xs_, item i of ys_) end repeat return lst end tell end zipWith
http://rosettacode.org/wiki/Topic_variable
Topic variable
Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language. For instance you can (but you don't have to) show how the topic variable can be used by assigning the number 3 {\displaystyle 3} to it and then computing its square and square root.
#zkl
zkl
a,_,c:=List(1,2,3,4,5,6) //-->a=1, c=3, here _ is used as "ignore" 3.0 : _.sqrt() : println(_) //-->"1.73205", _ (and :) is used to "explode" a computation // as syntactic sugar 1.0 + 2 : _.sqrt() : _.pow(4) // no variables used, the compiler "implodes" the computation // --> 9  
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
#11l
11l
V data = [(‘Tyler Bennett’, ‘E10297’, 32000, ‘D101’), (‘John Rappl’, ‘E21437’, 47000, ‘D050’), (‘George Woltman’, ‘E00127’, 53500, ‘D101’), (‘Adam Smith’, ‘E63535’, 18000, ‘D202’), (‘Claire Buckman’, ‘E39876’, 27800, ‘D202’), (‘David McClellan’, ‘E04242’, 41500, ‘D101’), (‘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’)]   DefaultDict[String, [(String, String, Int, String)]] departments L(rec) data departments[rec[3]].append(rec)   V n = 3 L(department, recs) sorted(departments.items()) print(‘Department #.’.format(department)) print(‘ #<15 #<15 #<15 #<15 ’.format(‘Employee Name’, ‘Employee ID’, ‘Salary’, ‘Department’)) L(rec) sorted(recs, key' rec -> rec[2], reverse' 1B)[0 .< n] print(‘ #<15 #<15 #<15 #<15 ’.format(rec[0], rec[1], rec[2], rec[3])) print()
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Agena
Agena
move := proc(n::number, src::number, dst::number, via::number) is if n > 0 then move(n - 1, src, via, dst) print(src & ' to ' & dst) move(n - 1, via, dst, src) fi end   move(4, 1, 2, 3)
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#11l
11l
F thue_morse_digits(digits) R (0 .< digits).map(n -> bin(n).count(‘1’) % 2)   print(thue_morse_digits(20))
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
#C
C
#include <stdbool.h> #include <stdint.h> #include <stdio.h>   uint64_t modpow(uint64_t a, uint64_t b, uint64_t n) { uint64_t x = 1, y = a; while (b > 0) { if (b % 2 == 1) { x = (x * y) % n; // multiplying with base } y = (y * y) % n; // squaring the base b /= 2; } return x % n; }   struct Solution { uint64_t root1, root2; bool exists; };   struct Solution makeSolution(uint64_t root1, uint64_t root2, bool exists) { struct Solution sol; sol.root1 = root1; sol.root2 = root2; sol.exists = exists; return sol; }   struct Solution ts(uint64_t n, uint64_t p) { uint64_t q = p - 1; uint64_t ss = 0; uint64_t z = 2; uint64_t c, r, t, m;   if (modpow(n, (p - 1) / 2, p) != 1) { return makeSolution(0, 0, false); }   while ((q & 1) == 0) { ss += 1; q >>= 1; }   if (ss == 1) { uint64_t r1 = modpow(n, (p + 1) / 4, p); return makeSolution(r1, p - r1, true); }   while (modpow(z, (p - 1) / 2, p) != p - 1) { z++; }   c = modpow(z, q, p); r = modpow(n, (q + 1) / 2, p); t = modpow(n, q, p); m = ss;   while (true) { uint64_t i = 0, zz = t; uint64_t b = c, e; if (t == 1) { return makeSolution(r, p - r, true); } while (zz != 1 && i < (m - 1)) { zz = zz * zz % p; i++; } e = m - i - 1; while (e > 0) { b = b * b % p; e--; } r = r * b % p; c = b * b % p; t = t * c % p; m = i; } }   void test(uint64_t n, uint64_t p) { struct Solution sol = ts(n, p); printf("n = %llu\n", n); printf("p = %llu\n", p); if (sol.exists) { printf("root1 = %llu\n", sol.root1); printf("root2 = %llu\n", sol.root2); } else { printf("No solution exists\n"); } printf("\n"); }   int main() { test(10, 13); test(56, 101); test(1030, 10009); test(1032, 10009); test(44402, 100049);   return 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
#AppleScript
AppleScript
------------------ TOKENIZE WITH ESCAPING ----------------   -- tokenize :: String -> Character -> Character -> [String] on tokenize(str, delimChar, chrEsc)   script charParse -- Record: {esc:Bool, token:String, tokens:[String]} -- charParse :: Record -> Character -> Record on |λ|(a, x) set blnEsc to esc of a set blnEscChar to ((not blnEsc) and (x = chrEsc))   if ((not blnEsc) and (x = delimChar)) then set k to "" set ks to (tokens of a) & token of a else set k to (token of a) & cond(blnEscChar, "", x) set ks to tokens of (a) end if   {esc:blnEscChar, token:k, tokens:ks} end |λ| end script   set recParse to foldl(charParse, ¬ {esc:false, token:"", tokens:[]}, splitOn("", str))   tokens of recParse & token of recParse end tokenize     --------------------------- TEST ------------------------- on run script numberedLine on |λ|(a, s) set iLine to lineNum of a {lineNum:iLine + 1, report:report of a & iLine & ":" & tab & s & linefeed} end |λ| end script   report of foldl(numberedLine, {lineNum:1, report:""}, ¬ tokenize("one^|uno||three^^^^|four^^^|^cuatro|", "|", "^")) end run     -------------------- GENERIC FUNCTIONS -------------------   -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl     -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn     -- splitOn :: String -> String -> [String] on splitOn(pat, src) set {dlm, my text item delimiters} to ¬ {my text item delimiters, pat} set xs to text items of src set my text item delimiters to dlm return xs end splitOn     -- cond :: Bool -> a -> a -> a on cond(bool, f, g) if bool then f else g end if end cond
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
#Haskell
Haskell
data Circle = Circle { cx :: Double, cy :: Double, cr :: Double }   isInside :: Double -> Double -> Circle -> Bool isInside x y c = (x - cx c) ^ 2 + (y - cy c) ^ 2 <= (cr c ^ 2)   isInsideAny :: Double -> Double -> [Circle] -> Bool isInsideAny x y = any (isInside x y)   approximatedArea :: [Circle] -> Int -> Double approximatedArea cs box_side = (fromIntegral count) * dx * dy where -- compute the bounding box of the circles x_min = minimum [cx c - cr c | c <- circles] x_max = maximum [cx c + cr c | c <- circles] y_min = minimum [cy c - cr c | c <- circles] y_max = maximum [cy c + cr c | c <- circles] dx = (x_max - x_min) / (fromIntegral box_side) dy = (y_max - y_min) / (fromIntegral box_side) count = length [0 | r <- [0 .. box_side - 1], c <- [0 .. box_side - 1], isInsideAny (posx c) (posy r) circles] posy r = y_min + (fromIntegral r) * dy posx c = x_min + (fromIntegral c) * dx   circles :: [Circle] 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]   main = putStrLn $ "Approximated area: " ++ (show $ approximatedArea circles 5000)
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]
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h>   char input[] = "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n" "dw01 ieee dw01 dware gtech\n" "dw02 ieee dw02 dware\n" "dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n" "dw04 dw04 ieee dw01 dware gtech\n" "dw05 dw05 ieee dware\n" "dw06 dw06 ieee dware\n" "dw07 ieee dware\n" "dware ieee dware\n" "gtech ieee gtech\n" "ramlib std ieee\n" "std_cell_lib ieee std_cell_lib\n" "synopsys\n" "cycle_11 cycle_12\n" "cycle_12 cycle_11\n" "cycle_21 dw01 cycle_22 dw02 dw03\n" "cycle_22 cycle_21 dw01 dw04";   typedef struct item_t item_t, *item; struct item_t { const char *name; int *deps, n_deps, idx, depth; };   int get_item(item *list, int *len, const char *name) { int i; item lst = *list;   for (i = 0; i < *len; i++) if (!strcmp(lst[i].name, name)) return i;   lst = *list = realloc(lst, ++*len * sizeof(item_t)); i = *len - 1; memset(lst + i, 0, sizeof(item_t)); lst[i].idx = i; lst[i].name = name; return i; }   void add_dep(item it, int i) { if (it->idx == i) return; it->deps = realloc(it->deps, (it->n_deps + 1) * sizeof(int)); it->deps[it->n_deps++] = i; }   int parse_input(item *ret) { int n_items = 0; int i, parent, idx; item list = 0;   char *s, *e, *word, *we; for (s = input; ; s = 0) { if (!(s = strtok_r(s, "\n", &e))) break;   for (i = 0, word = s; ; i++, word = 0) { if (!(word = strtok_r(word, " \t", &we))) break; idx = get_item(&list, &n_items, word);   if (!i) parent = idx; else add_dep(list + parent, idx); } }   *ret = list; return n_items; }   /* recursively resolve compile order; negative means loop */ int get_depth(item list, int idx, int bad) { int max, i, t;   if (!list[idx].deps) return list[idx].depth = 1;   if ((t = list[idx].depth) < 0) return t;   list[idx].depth = bad; for (max = i = 0; i < list[idx].n_deps; i++) { if ((t = get_depth(list, list[idx].deps[i], bad)) < 0) { max = t; break; } if (max < t + 1) max = t + 1; } return list[idx].depth = max; }   int main() { int i, j, n, bad = -1, max, min; item items; n = parse_input(&items);   for (i = 0; i < n; i++) if (!items[i].depth && get_depth(items, i, bad) < 0) bad--;   for (i = 0, max = min = 0; i < n; i++) { if (items[i].depth > max) max = items[i].depth; if (items[i].depth < min) min = items[i].depth; }   printf("Compile order:\n"); for (i = min; i <= max; i++) { if (!i) continue;   if (i < 0) printf(" [unorderable]"); else printf("%d:", i);   for (j = 0; j < n || !putchar('\n'); j++) if (items[j].depth == i) printf(" %s", items[j].name); }   return 0; }
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.
#Erlang
Erlang
#!/usr/bin/env escript   -module(turing). -mode(compile).   -export([main/1]).   % Incrementer definition: % States: a | halt % Initial state: a % Halting states: halt % Symbols: b | '1' % Blank symbol: b incrementer_config() -> {a, [halt], b}. incrementer(a, '1') -> {'1', right, a}; incrementer(a, b) -> {'1', stay, halt}.   % Busy beaver definition: % States: a | b | c | halt % Initial state: a % Halting states: halt % Symbols: '0' | '1' % Blank symbol: '0' busy_beaver_config() -> {a, [halt], '0'}. busy_beaver(a, '0') -> {'1', right, b}; busy_beaver(a, '1') -> {'1', left, c}; busy_beaver(b, '0') -> {'1', left, a}; busy_beaver(b, '1') -> {'1', right, b}; busy_beaver(c, '0') -> {'1', left, b}; busy_beaver(c, '1') -> {'1', stay, halt}.   % Mainline code. main([]) -> io:format("==============================~n"), io:format("Turing machine simulator test.~n"), io:format("==============================~n"),   Tape1 = turing(fun incrementer_config/0, fun incrementer/2, ['1','1','1']), io:format("~w~n", [Tape1]),   Tape2 = turing(fun busy_beaver_config/0, fun busy_beaver/2, []), io:format("~w~n", [Tape2]).   % Universal Turing machine simulator. turing(Config, Rules, Input) -> {Start, _, _} = Config(), {Left, Right} = perform(Config, Rules, Start, {[], Input}), lists:reverse(Left) ++ Right.   perform(Config, Rules, State, Input = {LeftInput, RightInput}) -> {_, Halts, Blank} = Config(), case lists:member(State, Halts) of true -> Input; false -> {NewRight, Symbol} = symbol(RightInput, Blank), {NewSymbol, Action, NewState} = Rules(State, Symbol), NewInput = action(Action, Blank, {LeftInput, [NewSymbol| NewRight]}), perform(Config, Rules, NewState, NewInput) end.   symbol([], Blank) -> {[], Blank}; symbol([S|R], _) -> {R, S}.   action(left, Blank, {[], Right}) -> {[], [Blank|Right]}; action(left, _, {[L|Ls], Right}) -> {Ls, [L|Right]}; action(stay, _, Tape) -> Tape; action(right, Blank, {Left, []}) -> {[Blank|Left], []}; action(right, _, {Left, [R|Rs]}) -> {[R|Left], Rs}.
http://rosettacode.org/wiki/Totient_function
Totient function
The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the integers up to a given positive integer   n   that are relatively prime to   n   counts the integers   k   in the range   1 ≤ k ≤ n   for which the greatest common divisor   gcd(n,k)   is equal to   1   counts numbers   ≤ n   and   prime to   n If the totient number   (for N)   is one less than   N,   then   N   is prime. Task Create a   totient   function and:   Find and display   (1 per line)   for the 1st   25   integers:   the integer   (the index)   the totient number for that integer   indicate if that integer is prime   Find and display the   count   of the primes up to          100   Find and display the   count   of the primes up to       1,000   Find and display the   count   of the primes up to     10,000   Find and display the   count   of the primes up to   100,000     (optional) Show all output here. Related task   Perfect totient numbers Also see   Wikipedia: Euler's totient function.   MathWorld: totient function.   OEIS: Euler totient function phi(n).
#D
D
import std.stdio;   int totient(int n) { int tot = n;   for (int i = 2; i * i <= n; i += 2) { if (n % i == 0) { while (n % i == 0) { n /= i; } tot -= tot / i; } if (i==2) { i = 1; } }   if (n > 1) { tot -= tot / n; } return tot; }   void main() { writeln(" n φ prime"); writeln("---------------");   int count = 0; for (int n = 1; n <= 25; n++) { int tot = totient(n);   if (n - 1 == tot) { count++; }   writefln("%2d  %2d  %s", n,tot, n - 1 == tot); } writeln;   writefln("Number of primes up to %6d = %4d", 25, count); for (int n = 26; n <= 100_000; n++) { int tot = totient(n);   if (n - 1 == tot) { count++; }   if (n == 100 || n == 1_000 || n % 10_000 == 0) { writefln("Number of primes up to %6d = %4d", n, count); } } }
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
#Java
Java
public class Topswops { static final int maxBest = 32; static int[] best;   static private void trySwaps(int[] deck, int f, int d, int n) { if (d > best[n]) best[n] = d;   for (int i = n - 1; i >= 0; i--) { if (deck[i] == -1 || deck[i] == i) break; if (d + best[i] <= best[n]) return; }   int[] deck2 = deck.clone(); for (int i = 1; i < n; i++) { final int k = 1 << i; if (deck2[i] == -1) { if ((f & k) != 0) continue; } else if (deck2[i] != i) continue;   deck2[0] = i; for (int j = i - 1; j >= 0; j--) deck2[i - j] = deck[j]; // Reverse copy. trySwaps(deck2, f | k, d + 1, n); } }   static int topswops(int n) { assert(n > 0 && n < maxBest); best[n] = 0; int[] deck0 = new int[n + 1]; for (int i = 1; i < n; i++) deck0[i] = -1; trySwaps(deck0, 1, 0, n); return best[n]; }   public static void main(String[] args) { best = new int[maxBest]; for (int i = 1; i < 11; i++) System.out.println(i + ": " + topswops(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.
#C
C
#include <math.h> #include <stdio.h>   int main() { double pi = 4 * atan(1); /*Pi / 4 is 45 degrees. All answers should be the same.*/ double radians = pi / 4; double degrees = 45.0; double temp; /*sine*/ printf("%f %f\n", sin(radians), sin(degrees * pi / 180)); /*cosine*/ printf("%f %f\n", cos(radians), cos(degrees * pi / 180)); /*tangent*/ printf("%f %f\n", tan(radians), tan(degrees * pi / 180)); /*arcsine*/ temp = asin(sin(radians)); printf("%f %f\n", temp, temp * 180 / pi); /*arccosine*/ temp = acos(cos(radians)); printf("%f %f\n", temp, temp * 180 / pi); /*arctangent*/ temp = atan(tan(radians)); printf("%f %f\n", temp, temp * 180 / pi);   return 0; }
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).
#Factor
Factor
USING: formatting io kernel math math.functions math.parser prettyprint sequences splitting ; IN: rosetta-code.trabb-pardo-knuth   CONSTANT: threshold 400 CONSTANT: prompt "Please enter 11 numbers: "   : fn ( x -- y ) [ abs 0.5 ^ ] [ 3 ^ 5 * ] bi + ;   : overflow? ( x -- ? ) threshold > ;   : get-input ( -- seq ) prompt write flush readln " " split dup length 11 = [ drop get-input ] unless ;   : ?result ( ..a quot: ( ..a -- ..b ) -- ..b ) [ "f(%u) = " sprintf ] swap bi dup overflow? [ drop "overflow" ] [ "%.3f" sprintf ] if append ; inline   : main ( -- ) get-input reverse [ string>number [ fn ] ?result print ] each ;   MAIN: main
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).
#Forth
Forth
: f(x) fdup fsqrt fswap 3e f** 5e f* f+ ;   4e2 fconstant f-too-big   11 Constant #Elements   : float-array ( compile: n -- / run: n -- addr ) create floats allot does> swap floats + ;   #Elements float-array vec   : get-it ( -- ) ." Enter " #Elements . ." numbers:" cr #Elements 0 DO ." > " pad 25 accept cr pad swap >float 0= abort" Invalid Number" i vec F! LOOP ;   : reverse-it ( -- ) #Elements 2/ 0 DO i vec F@ #Elements i - 1- vec F@ i vec F! #Elements i - 1- vec F! LOOP ;   : do-it ( -- ) #Elements 0 DO i vec F@ fdup f. [char] : emit space f(x) fdup f-too-big f> IF fdrop ." too large" ELSE f. THEN cr LOOP ;   : tpk ( -- ) get-it reverse-it do-it ;
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.
#Ruby
Ruby
constraints = [ ->(st) { st.size == 12 }, ->(st) { st.last(6).count(true) == 3 }, ->(st) { st.each_slice(2).map(&:last).count(true) == 2 }, ->(st) { st[4] ? (st[5] & st[6]) : true }, ->(st) { st[1..3].none? }, ->(st) { st.each_slice(2).map(&:first).count(true) == 4 }, ->(st) { st[1] ^ st[2] }, ->(st) { st[6] ? (st[4] & st[5]) : true }, ->(st) { st.first(6).count(true) == 3 }, ->(st) { st[10] & st[11] }, ->(st) { st[6..8].one? }, ->(st) { st[0,11].count(true) == 4 }, ]   Result = Struct.new(:truths, :consistency)   results = [true, false].repeated_permutation(12).map do |truths| Result.new(truths, constraints.zip(truths).map {|cn,truth| cn[truths] == truth }) end   puts "solution:", results.find {|r| r.consistency.all? }.truths.to_s   puts "\nnear misses: " near_misses = results.select {|r| r.consistency.count(false) == 1 } near_misses.each do |r| puts "missed by statement #{r.consistency.index(false) + 1}", r.truths.to_s 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.
#Phix
Phix
sequence opstack = {} object token object op = 0 -- 0 = none string s -- the expression being parsed integer sidx -- idx to "" integer ch -- s[sidx] procedure err(string msg) printf(1,"%s\n%s^ %s\n\nPressEnter...",{s,repeat(' ',sidx-1),msg}) {} = wait_key() abort(0) end procedure procedure nxtch() sidx += 1 ch = iff(sidx>length(s)?-1:s[sidx]) end procedure procedure skipspaces() while find(ch," \t\r\n")!=0 do nxtch() end while end procedure procedure get_token() skipspaces() if find(ch,"()!") then token = s[sidx..sidx] nxtch() else integer tokstart = sidx if ch=-1 then token = "eof" return end if while 1 do nxtch() if ch<'A' then exit end if end while token = s[tokstart..sidx-1] end if end procedure procedure Match(string t) if token!=t then err(t&" expected") end if get_token() end procedure procedure PopFactor() object p2 = opstack[$] if op="not" then opstack[$] = {0,op,p2} else opstack = opstack[1..$-1] opstack[$] = {opstack[$],op,p2} end if op = 0 end procedure sequence names -- {"false","true",...} sequence flags -- { 0, 1, ,...} procedure PushFactor(string t) if op!=0 then PopFactor() end if integer k = find(t,names) if k=0 then names = append(names,t) k = length(names) end if opstack = append(opstack,k) end procedure procedure PushOp(string t) if op!=0 then PopFactor() end if op = t end procedure procedure Factor() if token="not" or token="!" then get_token() Factor() if op!=0 then PopFactor() end if PushOp("not") elsif token="(" then get_token() Expr(0) Match(")") elsif not find(token,{"and","or","xor"}) then PushFactor(token) if ch!=-1 then get_token() end if else err("syntax error") end if end procedure constant {operators, precedence} = columnize({{"not",6}, {"and",5}, {"xor",4}, {"or",3}}) procedure Expr(integer p) Factor() while 1 do integer k = find(token,operators) if k=0 then exit end if integer thisp = precedence[k] if thisp<p then exit end if get_token() Expr(thisp) PushOp(operators[k]) end while end procedure function eval(object s) if atom(s) then if s>=1 then s = flags[s] end if return s end if object {lhs,op,rhs} = s lhs = eval(lhs) rhs = eval(rhs) if op="and" then return lhs and rhs elsif op="or" then return lhs or rhs elsif op="xor" then return lhs xor rhs elsif op="not" then return not rhs else ?9/0 end if end function function next_comb() integer fdx = length(flags) while flags[fdx]=1 do flags[fdx] = 0 fdx -= 1 end while if fdx<=2 then return false end if -- all done flags[fdx] = 1 return true end function function fmt(bool b) return {"0","1"}[b+1] -- for 0/1 -- return {"F","T"}[b+1] -- for F/T end function procedure test(string expr) opstack = {} op = 0 names = {"false","true"} s = expr sidx = 0 nxtch() get_token() Expr(0) if op!=0 then PopFactor() end if if length(opstack)!=1 then err("some error") end if flags = repeat(0,length(names)) flags[2] = 1 -- set "true" true printf(1,"%s  %s\n",{join(names[3..$]),s}) while 1 do for i=3 to length(flags) do -- (skipping true&false) printf(1,"%s%s",{fmt(flags[i]),repeat(' ',length(names[i]))}) end for printf(1," %s\n",{fmt(eval(opstack[1]))}) if not next_comb() then exit end if end while puts(1,"\n") end procedure test("young and not (ugly or poor)") while 1 do puts(1,"input expression:") string t = trim(gets(0)) puts(1,"\n") if t="" then exit end if test(t) end while
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
#PowerShell
PowerShell
  function New-UlamSpiral ( [int]$N ) { # Generate list of primes $Primes = @( 2 ) For ( $X = 3; $X -le $N*$N; $X += 2 ) { If ( -not ( $Primes | Where { $X % $_ -eq 0 } | Select -First 1 ) ) { $Primes += $X } }   # Initialize variables $X = 0 $Y = -1 $i = $N * $N + 1 $Sign = 1   # Intialize array $A = New-Object 'boolean[,]' $N, $N   # Set top row 1..$N | ForEach { $Y += $Sign; $A[$X,$Y] = --$i -in $Primes }   # For each remaining half spiral... ForEach ( $M in ($N-1)..1 ) { # Set the vertical quarter spiral 1..$M | ForEach { $X += $Sign; $A[$X,$Y] = --$i -in $Primes }   # Curve the spiral $Sign = -$Sign   # Set the horizontal quarter spiral 1..$M | ForEach { $Y += $Sign; $A[$X,$Y] = --$i -in $Primes } }   # Convert the array of booleans to text output of dots and spaces $Spiral = ForEach ( $X in 1..$N ) { ( 1..$N | ForEach { ( ' ', '.' )[$A[($X-1),($_-1)]] } ) -join '' } return $Spiral }   New-UlamSpiral 100  
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.]
#Icon_and_Unicon
Icon and Unicon
procedure main(arglist) N := 0 < integer(\arglist[1]) | 1000000 # primes to generator 1 to ... (1M or 1st arglist) D := (0 < integer(\arglist[2]) | 10) / 2 # primes to display (10 or 2nd arglist) P := sieve(N) # from sieve task (modified) write("There are ",*P," prime numbers in the range 1 to ",N) if *P <= 2*D then every writes( "Primes: "|!sort(P)||" "|"\n" ) else every writes( "Primes: "|(L := sort(P))[1 to D]||" "|"... "|L[*L-D+1 to *L]||" "|"\n" ) largesttruncateable(P) end   procedure largesttruncateable(P) #: find the largest left and right trucatable numbers in P local ltp,rtp   every x := sort(P)[*P to 1 by -1] do # largest to smallest if not find('0',x) then { /ltp := islefttrunc(P,x) /rtp := isrighttrunc(P,x) if \ltp & \rtp then break # until both found } write("Largest left truncatable prime = ", ltp) write("Largest right truncatable prime = ", rtp) return end   procedure isrighttrunc(P,x) #: return integer x if x and all right truncations of x are in P or fails if x = 0 | (member(P,x) & isrighttrunc(P,x / 10)) then return x end   procedure islefttrunc(P,x) #: return integer x if x and all left truncations of x are in P or fails if *x = 0 | ( (x := integer(x)) & member(P,x) & islefttrunc(P,x[2:0]) ) then return x 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.
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program deftree2.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ READ, 3 .equ WRITE, 4   .equ NBVAL, 9   /*******************************************/ /* Structures */ /********************************************/ /* structure tree */ .struct 0 tree_root: @ root pointer .struct tree_root + 4 tree_size: @ number of element of tree .struct tree_size + 4 tree_fin: /* structure node tree */ .struct 0 node_left: @ left pointer .struct node_left + 4 node_right: @ right pointer .struct node_right + 4 node_value: @ element value .struct node_value + 4 node_fin: /* structure queue*/ .struct 0 queue_begin: @ next pointer .struct queue_begin + 4 queue_end: @ element value .struct queue_end + 4 queue_fin: /* structure node queue */ .struct 0 queue_node_next: @ next pointer .struct queue_node_next + 4 queue_node_value: @ element value .struct queue_node_value + 4 queue_node_fin: /* Initialized data */ .data szMessInOrder: .asciz "inOrder :\n" szMessPreOrder: .asciz "PreOrder :\n" szMessPostOrder: .asciz "PostOrder :\n" szMessLevelOrder: .asciz "LevelOrder :\n" szCarriageReturn: .asciz "\n" /* datas error display */ szMessErreur: .asciz "Error detected.\n" /* datas message display */ szMessResult: .ascii "Element value :" sValue: .space 12,' ' .asciz "\n"   /* UnInitialized data */ .bss stTree: .skip tree_fin @ place to structure tree stQueue: .skip queue_fin @ place to structure queue /* code section */ .text .global main main: mov r1,#1 @ node tree value 1: ldr r0,iAdrstTree @ structure tree address bl insertElement @ add element value r1 cmp r0,#-1 beq 99f add r1,#1 @ increment value cmp r1,#NBVAL @ end ? ble 1b @ no -> loop   ldr r0,iAdrszMessPreOrder bl affichageMess ldr r3,iAdrstTree @ tree root address (begin structure) ldr r0,[r3,#tree_root] ldr r1,iAdrdisplayElement @ function to execute bl preOrder   ldr r0,iAdrszMessInOrder bl affichageMess ldr r3,iAdrstTree ldr r0,[r3,#tree_root] ldr r1,iAdrdisplayElement @ function to execute bl inOrder   ldr r0,iAdrszMessPostOrder bl affichageMess ldr r3,iAdrstTree ldr r0,[r3,#tree_root] ldr r1,iAdrdisplayElement @ function to execute bl postOrder   ldr r0,iAdrszMessLevelOrder bl affichageMess ldr r3,iAdrstTree ldr r0,[r3,#tree_root] ldr r1,iAdrdisplayElement @ function to execute bl levelOrder b 100f 99: @ display error ldr r0,iAdrszMessErreur bl affichageMess 100: @ standard end of the program mov r7, #EXIT @ request to exit program svc 0 @ perform system call iAdrszMessInOrder: .int szMessInOrder iAdrszMessPreOrder: .int szMessPreOrder iAdrszMessPostOrder: .int szMessPostOrder iAdrszMessLevelOrder: .int szMessLevelOrder iAdrszMessErreur: .int szMessErreur iAdrszCarriageReturn: .int szCarriageReturn iAdrstTree: .int stTree iAdrstQueue: .int stQueue iAdrdisplayElement: .int displayElement /******************************************************************/ /* insert element in the tree */ /******************************************************************/ /* r0 contains the address of the tree structure */ /* r1 contains the value of element */ /* r0 returns address of element or - 1 if error */ insertElement: push {r1-r7,lr} @ save registers mov r4,r0 mov r0,#node_fin @ reservation place one element bl allocHeap cmp r0,#-1 @ allocation error beq 100f mov r5,r0 str r1,[r5,#node_value] @ store value in address heap mov r1,#0 str r1,[r5,#node_left] @ init left pointer with zero str r1,[r5,#node_right] @ init right pointer with zero ldr r2,[r4,#tree_size] @ load tree size cmp r2,#0 @ 0 element ? bne 1f str r5,[r4,#tree_root] @ yes -> store in root b 4f 1: @ else search free address in tree ldr r3,[r4,#tree_root] @ start with address root add r6,r2,#1 @ increment tree size clz r7,r6 @ compute zeroes left bits add r7,#1 @ for sustract the first left bit lsl r6,r7 @ shift number in left 2: lsls r6,#1 @ read left bit bcs 3f @ is 1 ? ldr r1,[r3,#node_left] @ no store node address in left pointer cmp r1,#0 @ if equal zero streq r5,[r3,#node_left] beq 4f mov r3,r1 @ else loop with next node b 2b 3: @ yes ldr r1,[r3,#node_right] @ store node address in right pointer cmp r1,#0 @ if equal zero streq r5,[r3,#node_right] beq 4f mov r3,r1 @ else loop with next node b 2b 4: add r2,#1 @ increment tree size str r2,[r4,#tree_size] 100: pop {r1-r7,lr} @ restaur registers bx lr @ return /******************************************************************/ /* preOrder */ /******************************************************************/ /* r0 contains the address of the node */ /* r1 function address */ preOrder: push {r1-r2,lr} @ save registers cmp r0,#0 beq 100f mov r2,r0 blx r1 @ call function   ldr r0,[r2,#node_left] bl preOrder ldr r0,[r2,#node_right] bl preOrder 100: pop {r1-r2,lr} @ restaur registers bx lr /******************************************************************/ /* inOrder */ /******************************************************************/ /* r0 contains the address of the node */ /* r1 function address */ inOrder: push {r1-r3,lr} @ save registers cmp r0,#0 beq 100f mov r3,r0 mov r2,r1 ldr r0,[r3,#node_left] bl inOrder mov r0,r3 blx r2 @ call function   ldr r0,[r3,#node_right] mov r1,r2 bl inOrder 100: pop {r1-r3,lr} @ restaur registers bx lr @ return /******************************************************************/ /* postOrder */ /******************************************************************/ /* r0 contains the address of the node */ /* r1 function address */ postOrder: push {r1-r3,lr} @ save registers cmp r0,#0 beq 100f mov r3,r0 mov r2,r1 ldr r0,[r3,#node_left] bl postOrder   ldr r0,[r3,#node_right] mov r1,r2 bl postOrder mov r0,r3 blx r2 @ call function 100: pop {r1-r3,lr} @ restaur registers bx lr @ return /******************************************************************/ /* levelOrder */ /******************************************************************/ /* r0 contains the address of the node */ /* r1 function address */ levelOrder: push {r1-r4,lr} @ save registers cmp r0,#0 beq 100f mov r2,r1 mov r1,r0 ldr r0,iAdrstQueue @ adresse queue bl enqueueNode @ queue the node 1: @ begin loop ldr r0,iAdrstQueue bl isEmptyQueue @ is queue empty cmp r0,#0 beq 100f @ yes -> end ldr r0,iAdrstQueue bl dequeueNode mov r3,r0 @ save node blx r2 @ call function ldr r4,[r3,#node_left] @ left node ok ? cmp r4,#0 beq 2f @ no ldr r0,iAdrstQueue @ yes -> enqueue mov r1,r4 bl enqueueNode 2: ldr r4,[r3,#node_right] @ right node ok ? cmp r4,#0 beq 3f @ no ldr r0,iAdrstQueue @ yes -> enqueue mov r1,r4 bl enqueueNode 3: b 1b @ and loop   100: pop {r1-r4,lr} @ restaur registers bx lr @ return /******************************************************************/ /* display node */ /******************************************************************/ /* r0 contains node address */ displayElement: push {r1,lr} @ save registers ldr r0,[r0,#node_value] ldr r1,iAdrsValue bl conversion10S ldr r0,iAdrszMessResult bl affichageMess 100: pop {r1,lr} @ restaur registers bx lr @ return iAdrszMessResult: .int szMessResult iAdrsValue: .int sValue /******************************************************************/ /* enqueue node */ /******************************************************************/ /* r0 contains the address of the queue */ /* r1 contains the value of element */ /* r0 returns address of element or - 1 if error */ enqueueNode: push {r1-r5,lr} @ save registers mov r4,r0 mov r0,#queue_node_fin @ allocation place heap bl allocHeap cmp r0,#-1 @ allocation error beq 100f mov r5,r0 @ save heap address str r1,[r5,#queue_node_value] @ store node value mov r1,#0 str r1,[r5,#queue_node_next] @ init pointer next ldr r0,[r4,#queue_end] cmp r0,#0 strne r5,[r0,#queue_node_next] streq r5,[r4,#queue_begin] str r5,[r4,#queue_end] mov r0,#0 pop {r1-r5,lr} bx lr @ return /******************************************************************/ /* dequeue node */ /******************************************************************/ /* r0 contains the address of the queue */ /* r0 returns address of element or - 1 if error */ dequeueNode: push {r1-r5,lr} @ save registers ldr r4,[r0,#queue_begin] ldr r5,[r4,#queue_node_value] ldr r6,[r4,#queue_node_next] str r6,[r0,#queue_begin] cmp r6,#0 streq r6,[r0,#queue_end] mov r0,r5 100: pop {r1-r5,lr} bx lr @ return /******************************************************************/ /* dequeue node */ /******************************************************************/ /* r0 contains the address of the queue */ /* r0 returns 0 if empty else 1 */ isEmptyQueue: ldr r0,[r0,#queue_begin] cmp r0,#0 movne r0,#1 bx lr @ return /******************************************************************/ /* memory allocation on the heap */ /******************************************************************/ /* r0 contains the size to allocate */ /* r0 returns address of memory heap or - 1 if error */ /* CAUTION : The size of the allowance must be a multiple of 4 */ allocHeap: push {r5-r7,lr} @ save registers @ allocation mov r6,r0 @ save size mov r0,#0 @ read address start heap mov r7,#0x2D @ call system 'brk' svc #0 mov r5,r0 @ save address heap for return add r0,r6 @ reservation place for size mov r7,#0x2D @ call system 'brk' svc #0 cmp r0,#-1 @ allocation error movne r0,r5 @ return address memory heap pop {r5-r7,lr} @ restaur registers bx lr @ return /******************************************************************/ /* 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 system pop {r0,r1,r2,r7,lr} @ restaur registers bx lr @ return /***************************************************/ /* Converting a register to a signed decimal */ /***************************************************/ /* r0 contains value and r1 area address */ conversion10S: push {r0-r4,lr} @ save registers mov r2,r1 @ debut zone stockage mov r3,#'+' @ par defaut le signe est + cmp r0,#0 @ negative number ? movlt r3,#'-' @ yes mvnlt r0,r0 @ number inversion addlt r0,#1 mov r4,#10 @ length area 1: @ start loop bl divisionpar10U add r1,#48 @ digit strb r1,[r2,r4] @ store digit on area sub r4,r4,#1 @ previous position cmp r0,#0 @ stop if quotient = 0 bne 1b   strb r3,[r2,r4] @ store signe subs r4,r4,#1 @ previous position blt 100f @ if r4 < 0 -> end   mov r1,#' ' @ space 2: strb r1,[r2,r4] @store byte space subs r4,r4,#1 @ previous position bge 2b @ loop if r4 > 0 100: pop {r0-r4,lr} @ restaur registers bx lr /***************************************************/ /* division par 10 unsigned */ /***************************************************/ /* r0 dividende */ /* r0 quotient */ /* r1 remainder */ divisionpar10U: push {r2,r3,r4, lr} mov r4,r0 @ save value //mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3 //movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3 ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2 umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3 add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) pop {r2,r3,r4,lr} bx lr @ leave function iMagicNumber: .int 0xCCCCCCCD    
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
#Action.21
Action!
DEFINE PTR="CARD" DEFINE ENTRY_SIZE="8"   TYPE Employee=[ PTR name,id,dep ;CHAR ARRAY CARD salary]   BYTE ARRAY data(200) BYTE count=[0]   PTR FUNC GetItemAddr(INT index) PTR addr   addr=data+index*ENTRY_SIZE RETURN (addr)   PROC Append(CHAR ARRAY n,i CARD s CHAR ARRAY d) Employee POINTER dst   dst=GetItemAddr(count) dst.name=n dst.id=i dst.dep=d dst.salary=s count==+1 RETURN   PROC InitData() Append("Tyler Bennett","E10297",32000,"D101") Append("John Rappl","E21437",47000,"D050") Append("George Woltman","E00127",53500,"D101") Append("Adam Smith","E63535",18000,"D202") Append("Claire Buckman","E39876",27800,"D202") Append("David McClellan","E04242",41500,"D101") Append("Rich Holcomb","E01234",49500,"D202") Append("Nathan Adams","E41298",21900,"D050") Append("Richard Potter","E43128",15900,"D101") Append("David Motsinger","E27002",19250,"D202") Append("Tim Sampair","E03033",27000,"D101") Append("Kim Arlich","E10001",57000,"D190") Append("Timothy Grove","E16398",29900,"D190") RETURN   PROC Swap(Employee POINTER e1,e2) PTR tmp   tmp=e1.name e1.name=e2.name e2.name=tmp tmp=e1.id e1.id=e2.id e2.id=tmp tmp=e1.dep e1.dep=e2.dep e2.dep=tmp tmp=e1.salary e1.salary=e2.salary e2.salary=tmp RETURN   PROC Sort() INT i,j,minpos,comp Employee POINTER e1,e2   FOR i=0 TO count-2 DO minpos=i FOR j=i+1 TO count-1 DO e1=GetItemAddr(minpos) e2=GetItemAddr(j) comp=SCompare(e1.dep,e2.dep) IF comp>0 OR comp=0 AND e1.salary<e2.salary THEN minpos=j FI OD   IF minpos#i THEN e1=GetItemAddr(minpos) e2=GetItemAddr(i) Swap(e1,e2) FI OD RETURN   PROC TopRank(BYTE n) BYTE i,c CHAR ARRAY d Employee POINTER e   i=0 WHILE i<count DO e=GetItemAddr(i) IF i=0 OR SCompare(e.dep,d)#0 THEN d=e.dep c=0 IF i>0 THEN PutE() FI PrintF("Department %S:%E",d) c==+1 PrintF("  %U %S %S%E",e.salary,e.id,e.name) ELSEIF c<n THEN c==+1 PrintF("  %U %S %S%E",e.salary,e.id,e.name) FI i==+1 OD RETURN   PROC Main() InitData() Sort() TopRank(3) RETURN
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#ALGOL_60
ALGOL 60
begin procedure movedisk(n, f, t); integer n, f, t; begin outstring (1, "Move disk from"); outinteger(1, f); outstring (1, "to"); outinteger(1, t); outstring (1, "\n"); end;   procedure dohanoi(n, f, t, u); integer n, f, t, u; begin if n < 2 then movedisk(1, f, t) else begin dohanoi(n - 1, f, u, t); movedisk(1, f, t); dohanoi(n - 1, u, t, f); end; end;   dohanoi(4, 1, 2, 3); outstring(1,"Towers of Hanoi puzzle completed!") end
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
#8080_Assembly
8080 Assembly
org 100h ;;; Write 256 bytes of ASCII '0' starting at address 200h lxi h,200h ; The array is page-aligned so L starts at 0 mvi a,'0' ; ASCII 0 zero: mov m,a ; Write it to memory at address HL inr l ; Increment low byte of pointer, jnz zero ; until it wraps to zero. ;;; Generate the first 256 elements of the Thue-Morse sequence. gen: jpe $+4 ; If parity is even, skip next instruction inr m ; (If parity is odd,) increment byte at HL (0->1) inr l ; Increment low byte of pointer (and set parity), jnz gen ; Until it wraps again. ;;; Output using CP/M call inr h ; Increment high byte, mvi m,'$' ; and write the CP/M string terminator there. mvi c,9 ; Syscall 9 = print string lxi d,200h ; The string is at 200h jmp 5
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
#Action.21
Action!
PROC Next(CHAR ARRAY s) BYTE i,len CHAR c   IF s(0)=0 THEN s(0)=1 s(1)='0 RETURN FI   FOR i=1 TO s(0) DO IF s(i)='0 THEN c='1 ELSE c='0 FI s(s(0)+i)=c OD s(0)==*2 RETURN   PROC Main() BYTE i CHAR ARRAY s(256)   s(0)=0 FOR i=0 TO 7 DO Next(s) PrintF("T%B=%S%E%E",i,s) OD RETURN
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
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Thue_Morse is   function Replace(S: String) return String is -- replace every "0" by "01" and every "1" by "10" (if S'Length = 0 then "" else (if S(S'First) = '0' then "01" else "10") & Replace(S(S'First+1 .. S'Last)));   function Sequence (N: Natural) return String is (if N=0 then "0" else Replace(Sequence(N-1)));   begin for I in 0 .. 6 loop Ada.Text_IO.Put_Line(Integer'Image(I) & ": " & Sequence(I)); end loop; end Thue_Morse;
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
#C.23
C#
using System; using System.Collections.Generic; using System.Numerics;   namespace TonelliShanks { class Solution { private readonly BigInteger root1, root2; private readonly bool exists;   public Solution(BigInteger root1, BigInteger root2, bool exists) { this.root1 = root1; this.root2 = root2; this.exists = exists; }   public BigInteger Root1() { return root1; }   public BigInteger Root2() { return root2; }   public bool Exists() { return exists; } }   class Program { static Solution Ts(BigInteger n, BigInteger p) { if (BigInteger.ModPow(n, (p - 1) / 2, p) != 1) { return new Solution(0, 0, false); }   BigInteger q = p - 1; BigInteger ss = 0; while ((q & 1) == 0) { ss = ss + 1; q = q >> 1; }   if (ss == 1) { BigInteger r1 = BigInteger.ModPow(n, (p + 1) / 4, p); return new Solution(r1, p - r1, true); }   BigInteger z = 2; while (BigInteger.ModPow(z, (p - 1) / 2, p) != p - 1) { z = z + 1; } BigInteger c = BigInteger.ModPow(z, q, p); BigInteger r = BigInteger.ModPow(n, (q + 1) / 2, p); BigInteger t = BigInteger.ModPow(n, q, p); BigInteger m = ss;   while (true) { if (t == 1) { return new Solution(r, p - r, true); } BigInteger i = 0; BigInteger zz = t; while (zz != 1 && i < (m - 1)) { zz = zz * zz % p; i = i + 1; } BigInteger b = c; BigInteger e = m - i - 1; while (e > 0) { b = b * b % p; e = e - 1; } r = r * b % p; c = b * b % p; t = t * c % p; m = i; } }   static void Main(string[] args) { List<Tuple<long, long>> pairs = new List<Tuple<long, long>>() { new Tuple<long, long>(10, 13), new Tuple<long, long>(56, 101), new Tuple<long, long>(1030, 10009), new Tuple<long, long>(1032, 10009), new Tuple<long, long>(44402, 100049), new Tuple<long, long>(665820697, 1000000009), new Tuple<long, long>(881398088036, 1000000000039), };   foreach (var pair in pairs) { Solution sol = Ts(pair.Item1, pair.Item2); Console.WriteLine("n = {0}", pair.Item1); Console.WriteLine("p = {0}", pair.Item2); if (sol.Exists()) { Console.WriteLine("root1 = {0}", sol.Root1()); Console.WriteLine("root2 = {0}", sol.Root2()); } else { Console.WriteLine("No solution exists"); } Console.WriteLine(); }   BigInteger bn = BigInteger.Parse("41660815127637347468140745042827704103445750172002"); BigInteger bp = BigInteger.Pow(10, 50) + 577; Solution bsol = Ts(bn, bp); Console.WriteLine("n = {0}", bn); Console.WriteLine("p = {0}", bp); if (bsol.Exists()) { Console.WriteLine("root1 = {0}", bsol.Root1()); Console.WriteLine("root2 = {0}", bsol.Root2()); } else { Console.WriteLine("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
#Arturo
Arturo
tokenize: function [s sep esc][ escaping: 0   loop 0..(size s)-1 [i][ chr: get split s i   if? escaping=1 [ prints chr escaping: 0 ] else [ case [chr] when? [=sep] [print ""] when? [=esc] [escaping: 1] else [prints chr] ] ] print "" ]   str: "one^|uno||three^^^^|four^^^|^cuatro|" tokenize str "|" "^"
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
#J
J
NB. check points on a regular grid within the bounding box     N=: 400 NB. grids in each dimension. Controls accuracy.     'X Y R'=: |: XYR=: (_&".;._2~ LF&=)0 :0 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 )   bbox=: (<./@:- , >./@:+)&R BBOXX=: bbox X BBOXY=: bbox Y   grid=: 3 : 0 'MN MX N'=. y D=. MX-MN EDGE=. D%N (MN(+ -:)EDGE)+(D-EDGE)*(i. % <:)N )   assert 2.2 2.6 3 3.4 3.8 -: grid 2 4 5   GRIDDED_SAMPLES=: BBOXX {@:;&(grid@:(,&N)) BBOXY   Note '4 4{.GRIDDED_SAMPLES' NB. example ┌─────────────────┬─────────────────┬─────────────────┬─────────────────┐ │_2.59706 _2.20043│_2.59706 _2.19774│_2.59706 _2.19505│_2.59706 _2.19236│ ├─────────────────┼─────────────────┼─────────────────┼─────────────────┤ │_2.59434 _2.20043│_2.59434 _2.19774│_2.59434 _2.19505│_2.59434 _2.19236│ ├─────────────────┼─────────────────┼─────────────────┼─────────────────┤ │_2.59162 _2.20043│_2.59162 _2.19774│_2.59162 _2.19505│_2.59162 _2.19236│ ├─────────────────┼─────────────────┼─────────────────┼─────────────────┤ │_2.58891 _2.20043│_2.58891 _2.19774│_2.58891 _2.19505│_2.58891 _2.19236│ └─────────────────┴─────────────────┴─────────────────┴─────────────────┘ ) XY=: >,GRIDDED_SAMPLES NB. convert to an usual array of floats.   mp=: $:~ :(+/ .*) NB. matrix product assert (*: 5 13) -: (mp"1) 3 4,:5 12   in=: *:@:{:@:] >: [: mp (- }:) NB. logical function assert 0 0 in 1 0 2 NB. X Y in X Y R assert 0 0 (-.@:in) 44 2 3   CONTAINED=: XY in"1/XYR NB. logical table of circles containing each grid FRACTION=: CONTAINED (+/@:(+./"1)@:[ % *:@:]) N AREA=: BBOXX*&(-/)BBOXY NB. area of the bounding box. FRACTION*AREA   NB. result is 21.5645
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]
#C.23
C#
  namespace Algorithms { using System; using System.Collections.Generic; using System.Linq;   public class TopologicalSorter<ValueType> { private class Relations { public int Dependencies = 0; public HashSet<ValueType> Dependents = new HashSet<ValueType>(); }   private Dictionary<ValueType, Relations> _map = new Dictionary<ValueType, Relations>();   public void Add(ValueType obj) { if (!_map.ContainsKey(obj)) _map.Add(obj, new Relations()); }   public void Add(ValueType obj, ValueType dependency) { if (dependency.Equals(obj)) return;   if (!_map.ContainsKey(dependency)) _map.Add(dependency, new Relations());   var dependents = _map[dependency].Dependents;   if (!dependents.Contains(obj)) { dependents.Add(obj);   if (!_map.ContainsKey(obj)) _map.Add(obj, new Relations());   ++_map[obj].Dependencies; } }   public void Add(ValueType obj, IEnumerable<ValueType> dependencies) { foreach (var dependency in dependencies) Add(obj, dependency); }   public void Add(ValueType obj, params ValueType[] dependencies) { Add(obj, dependencies as IEnumerable<ValueType>); }   public Tuple<IEnumerable<ValueType>, IEnumerable<ValueType>> Sort() { List<ValueType> sorted = new List<ValueType>(), cycled = new List<ValueType>(); var map = _map.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);   sorted.AddRange(map.Where(kvp => kvp.Value.Dependencies == 0).Select(kvp => kvp.Key));   for (int idx = 0; idx < sorted.Count; ++idx) sorted.AddRange(map[sorted[idx]].Dependents.Where(k => --map[k].Dependencies == 0));   cycled.AddRange(map.Where(kvp => kvp.Value.Dependencies != 0).Select(kvp => kvp.Key));   return new Tuple<IEnumerable<ValueType>, IEnumerable<ValueType>>(sorted, cycled); }   public void Clear() { _map.Clear(); } }   }   /* Example usage with Task object */   namespace ExampleApplication { using Algorithms; using System; using System.Collections.Generic; using System.Linq;   public class Task { public string Message; }   class Program { static void Main(string[] args) { List<Task> tasks = new List<Task> { new Task{ Message = "A - depends on B and C" }, //0 new Task{ Message = "B - depends on none" }, //1 new Task{ Message = "C - depends on D and E" }, //2 new Task{ Message = "D - depends on none" }, //3 new Task{ Message = "E - depends on F, G and H" }, //4 new Task{ Message = "F - depends on I" }, //5 new Task{ Message = "G - depends on none" }, //6 new Task{ Message = "H - depends on none" }, //7 new Task{ Message = "I - depends on none" }, //8 };   TopologicalSorter<Task> resolver = new TopologicalSorter<Task>();   // now setting relations between them as described above resolver.Add(tasks[0], new[] { tasks[1], tasks[2] }); //resolver.Add(tasks[1]); // no need for this since the task was already mentioned as a dependency resolver.Add(tasks[2], new[] { tasks[3], tasks[4] }); //resolver.Add(tasks[3]); // no need for this since the task was already mentioned as a dependency resolver.Add(tasks[4], tasks[5], tasks[6], tasks[7]); resolver.Add(tasks[5], tasks[8]); //resolver.Add(tasks[6]); // no need for this since the task was already mentioned as a dependency //resolver.Add(tasks[7]); // no need for this since the task was already mentioned as a dependency   //resolver.Add(tasks[3], tasks[0]); // uncomment this line to test cycled dependency   var result = resolver.Sort(); var sorted = result.Item1; var cycled = result.Item2;   if (!cycled.Any()) { foreach (var d in sorted) Console.WriteLine(d.Message); } else { Console.Write("Cycled dependencies detected: ");   foreach (var d in cycled) Console.Write($"{d.Message[0]} ");   Console.WriteLine(); }   Console.WriteLine("exiting..."); } } }    
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.
#Fortran
Fortran
1 State 1 1,-1, 3 1,+1, 2 2 State 2 1,+1, 2 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).
#Delphi
Delphi
func totient(n) { var tot = n var i = 2 while i * i <= n { if n % i == 0 { while n % i == 0 { n /= i } tot -= tot / i } if i == 2 { i = 1 } i += 2 } if n > 1 { tot -= tot / n } return tot }   print("n\tphi\tprime") var count = 0 for n in 1..25 { var tot = totient(n) var isPrime = n - 1 == tot if isPrime { count += 1 } print("\(n)\t\(tot)\t\(isPrime)") } print("\nNumber of primes up to 25 \t= \(count)") for n in 26..100000 { var tot = totient(n) if tot == n - 1 { count += 1 } if n == 100 || n == 1000 || n % 10000 == 0 { print("Number of primes up to \(n) \t= \(count)") } }
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
#jq
jq
# "while" as defined here is included in recent versions (>1.4) of jq: def until(cond; next): def _until: if cond then . else (next|_until) end; _until;   # Generate a stream of permutations of [1, ... n]. # This implementation uses arity-0 filters for speed. def permutations: # Given a single array, insert generates a stream by inserting (length+1) at different positions def insert: # state: [m, array] .[0] as $m | (1+(.[1]|length)) as $n | .[1] | if $m >= 0 then (.[0:$m] + [$n] + .[$m:]), ([$m-1, .] | insert) else empty end;   if .==0 then [] elif . == 1 then [1] else . as $n | ($n-1) | permutations | [$n-1, .] | insert 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
#Julia
Julia
function fannkuch(n) n == 1 && return 0 n == 2 && return 1 p = [1:n] q = copy(p) s = copy(p) sign = 1; maxflips = sum = 0 while true q0 = p[1] if q0 != 1 for i = 2:n q[i] = p[i] end flips = 1 while true qq = q[q0] #?? if qq == 1 sum += sign*flips flips > maxflips && (maxflips = flips) break end q[q0] = q0 if q0 >= 4 i = 2; j = q0-1 while true t = q[i] q[i] = q[j] q[j] = t i += 1 j -= 1 i >= j && break end end q0 = qq flips += 1 end end #permute if sign == 1 t = p[2] p[2] = p[1] p[1] = t sign = -1 else t = p[2] p[2] = p[3] p[3] = t sign = 1 for i = 3:n sx = s[i] if sx != 1 s[i] = sx-1 break end i == n && return maxflips s[i] = i t = p[1] for j = 1:i p[j] = p[j+1] end p[i+1] = t end end end end
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.
#C.23
C#
using System;   namespace RosettaCode { class Program { static void Main(string[] args) { Console.WriteLine("=== radians ==="); Console.WriteLine("sin (pi/3) = {0}", Math.Sin(Math.PI / 3)); Console.WriteLine("cos (pi/3) = {0}", Math.Cos(Math.PI / 3)); Console.WriteLine("tan (pi/3) = {0}", Math.Tan(Math.PI / 3)); Console.WriteLine("arcsin (1/2) = {0}", Math.Asin(0.5)); Console.WriteLine("arccos (1/2) = {0}", Math.Acos(0.5)); Console.WriteLine("arctan (1/2) = {0}", Math.Atan(0.5)); Console.WriteLine(""); Console.WriteLine("=== degrees ==="); Console.WriteLine("sin (60) = {0}", Math.Sin(60 * Math.PI / 180)); Console.WriteLine("cos (60) = {0}", Math.Cos(60 * Math.PI / 180)); Console.WriteLine("tan (60) = {0}", Math.Tan(60 * Math.PI / 180)); Console.WriteLine("arcsin (1/2) = {0}", Math.Asin(0.5) * 180/ Math.PI); Console.WriteLine("arccos (1/2) = {0}", Math.Acos(0.5) * 180 / Math.PI); Console.WriteLine("arctan (1/2) = {0}", Math.Atan(0.5) * 180 / Math.PI);   Console.ReadLine(); } } }
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).
#Fortran
Fortran
program tpk implicit none   real, parameter :: overflow = 400.0 real :: a(11), res integer :: i   write(*,*) "Input eleven numbers:" read(*,*) a   a = a(11:1:-1) do i = 1, 11 res = f(a(i)) write(*, "(a, f0.3, a)", advance = "no") "f(", a(i), ") = " if(res > overflow) then write(*, "(a)") "overflow!" else write(*, "(f0.3)") res end if end do   contains   real function f(x) real, intent(in) :: x   f = sqrt(abs(x)) + 5.0*x**3   end function end program
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.
#Scala
Scala
class LogicPuzzle { val s = new Array[Boolean](13) var count = 0   def check2: Boolean = { var count = 0 for (k <- 7 to 12) if (s(k)) count += 1   s(2) == (count == 3) }   def check3: Boolean = { var count = 0 for (k <- 2 to 12 by 2) if (s(k)) count += 1   s(3) == (count == 2) }   def check4: Boolean = s(4) == (!s(5) || s(6) && s(7))   def check5: Boolean = s(5) == (!s(2) && !s(3) && !s(4))   def check6: Boolean = { var count = 0 for (k <- 1 to 11 by 2) if (s(k)) count += 1 s(6) == (count == 4) }   def check7: Boolean = s(7) == ((s(2) || s(3)) && !(s(2) && s(3)))   def check8: Boolean = s(8) == (!s(7) || s(5) && s(6))   def check9: Boolean = { var count = 0 for (k <- 1 to 6) if (s(k)) count += 1   s(9) == (count == 3) }   def check10: Boolean = s(10) == (s(11) && s(12))   def check11: Boolean = { var count = 0 for (k <- 7 to 9) if (s(k)) count += 1   s(11) == (count == 1) }   def check12: Boolean = { var count = 0 for (k <- 1 to 11) if (s(k)) count += 1 s(12) == (count == 4) }   def check(): Unit = { if (check2 && check3 && check4 && check5 && check6 && check7 && check8 && check9 && check10 && check11 && check12) { for (k <- 1 to 12) if (s(k)) print(k + " ") println() count += 1 } }   def recurseAll(k: Int): Unit = { if (k == 13) check() else { s(k) = false recurseAll(k + 1) s(k) = true recurseAll(k + 1) } } }   object LogicPuzzle extends App { val p = new LogicPuzzle p.s(1) = true p.recurseAll(2) println() println(s"${p.count} Solutions found.")   }
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.
#PicoLisp
PicoLisp
(de truthTable (Expr) (let Vars (uniq (make (setq Expr (recur (Expr) # Convert infix to prefix notation (cond ((atom Expr) (link Expr)) ((== 'not (car Expr)) (list 'not (recurse (cadr Expr))) ) (T (list (cadr Expr) (recurse (car Expr)) (recurse (caddr Expr)) ) ) ) ) ) ) ) (for V Vars (prin (align -7 V)) ) (prinl) (bind (mapcar cons Vars) (do (** 2 (length Vars)) (for "V" Vars (space (if (print (val "V")) 6 4)) ) (println (eval Expr)) (find '(("V") (set "V" (not (val "V")))) Vars) ) ) ) )
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
#Python
Python
# coding=UTF-8 from __future__ import print_function, division from math import sqrt   def cell(n, x, y, start=1): d, y, x = 0, y - n//2, x - (n - 1)//2 l = 2*max(abs(x), abs(y)) d = (l*3 + x + y) if y >= x else (l - x - y) return (l - 1)**2 + d + start - 1   def show_spiral(n, symbol='# ', start=1, space=None): top = start + n*n + 1 is_prime = [False,False,True] + [True,False]*(top//2) for x in range(3, 1 + int(sqrt(top))): if not is_prime[x]: continue for i in range(x*x, top, x*2): is_prime[i] = False   cell_str = lambda x: f(x) if is_prime[x] else space f = lambda _: symbol # how to show prime cells   if space == None: space = ' '*len(symbol)   if not len(symbol): # print numbers instead max_str = len(str(n*n + start - 1)) if space == None: space = '.'*max_str + ' ' f = lambda x: ('%' + str(max_str) + 'd ')%x   for y in range(n): print(''.join(cell_str(v) for v in [cell(n, x, y, start) for x in range(n)])) print()   show_spiral(10, symbol=u'♞', space=u'♘') # black are the primes show_spiral(9, symbol='', space=' - ') # for filling giant terminals #show_spiral(1001, symbol='*', start=42)
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.]
#J
J
selPrime=: #~ 1&p: seed=: selPrime digits=: 1+i.9 step=: selPrime@,@:(,&.":/&>)@{@;
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.
#ATS
ATS
#include "share/atspre_staload.hats" // (* ****** ****** *) // datatype tree (a:t@ype) = | tnil of () | tcons of (tree a, a, tree a) // (* ****** ****** *)   symintr ++ infixr (+) ++ overload ++ with list_append   (* ****** ****** *)   #define sing list_sing   (* ****** ****** *)   fun{ a:t@ype } preorder (t0: tree a): List0 a = case t0 of | tnil () => nil () | tcons (tl, x, tr) => sing(x) ++ preorder(tl) ++ preorder(tr)   (* ****** ****** *)   fun{ a:t@ype } inorder (t0: tree a): List0 a = case t0 of | tnil () => nil () | tcons (tl, x, tr) => inorder(tl) ++ sing(x) ++ inorder(tr)   (* ****** ****** *)   fun{ a:t@ype } postorder (t0: tree a): List0 a = case t0 of | tnil () => nil () | tcons (tl, x, tr) => postorder(tl) ++ postorder(tr) ++ sing(x)   (* ****** ****** *)   fun{ a:t@ype } levelorder (t0: tree a): List0 a = let // fun auxlst (ts: List (tree(a))): List0 a = case ts of | list_nil () => list_nil () | list_cons (t, ts) => ( case+ t of | tnil () => auxlst (ts) | tcons (tl, x, tr) => cons (x, auxlst (ts ++ $list{tree(a)}(tl, tr))) ) // in auxlst (sing(t0)) end // end of [levelorder]   (* ****** ****** *)   macdef tsing(x) = tcons (tnil, ,(x), tnil)   (* ****** ****** *)   implement main0 () = let // val t0 = tcons{int} ( tcons (tcons (tsing (7), 4, tnil ()), 2, tsing (5)) , 1 , tcons (tcons (tsing (8), 6, tsing (9)), 3, tnil ()) ) // in println! ("preorder:\t", preorder(t0)); println! ("inorder:\t", inorder(t0)); println! ("postorder:\t", postorder(t0)); println! ("level-order:\t", levelorder(t0)); end (* end of [main0] *)
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
#11l
11l
V text = ‘Hello,How,Are,You,Today’ V tokens = text.split(‘,’) print(tokens.join(‘.’))
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
#Ada
Ada
with Ada.Containers.Vectors; with Ada.Text_IO;   procedure Top is type Departments is (D050, D101, D190, D202); type Employee_Data is record Name  : String (1 .. 15); ID  : String (1 .. 6); Salary  : Positive; Department : Departments; end record;   package Employee_Vectors is new Ada.Containers.Vectors (Element_Type => Employee_Data, Index_Type => Positive);   function Compare_Salary (Left, Right : Employee_Data) return Boolean is begin return Left.Salary > Right.Salary; end Compare_Salary; package Salary_Sort is new Employee_Vectors.Generic_Sorting ("<" => Compare_Salary);   function Compare_Department (Left, Right : Employee_Data) return Boolean is begin return Left.Department < Right.Department; end Compare_Department; package Department_Sort is new Employee_Vectors.Generic_Sorting ("<" => Compare_Department);   Example_Data : Employee_Vectors.Vector; begin -- fill data Example_Data.Append (("Tyler Bennett ", "E10297", 32000, D101)); Example_Data.Append (("John Rappl ", "E21437", 47000, D050)); Example_Data.Append (("George Woltman ", "E00127", 53500, D101)); Example_Data.Append (("Adam Smith ", "E63535", 18000, D202)); Example_Data.Append (("Claire Buckman ", "E39876", 27800, D202)); Example_Data.Append (("David McClellan", "E04242", 41500, D101)); Example_Data.Append (("Rich Holcomb ", "E01234", 49500, D202)); Example_Data.Append (("Nathan Adams ", "E41298", 21900, D050)); Example_Data.Append (("Richard Potter ", "E43128", 15900, D101)); Example_Data.Append (("David Motsinger", "E27002", 19250, D202)); Example_Data.Append (("Tim Sampair ", "E03033", 27000, D101)); Example_Data.Append (("Kim Arlich ", "E10001", 57000, D190)); Example_Data.Append (("Timothy Grove ", "E16398", 29900, D190)); -- sort by salary Salary_Sort.Sort (Example_Data); -- output each department for Department in Departments loop declare Position : Employee_Vectors.Cursor := Example_Data.First; Employee : Employee_Data; begin Ada.Text_IO.Put_Line ("Department " & Departments'Image (Department)); for I in 1 .. 3 loop Employee := Employee_Vectors.Element (Position); while Employee.Department /= Department loop Position := Employee_Vectors.Next (Position); Employee := Employee_Vectors.Element (Position); end loop; Ada.Text_IO.Put_Line (" " & Employee.Name & " | " & Employee.ID & " | " & Positive'Image (Employee.Salary)); Position := Employee_Vectors.Next (Position); end loop; exception when Constraint_Error => null; end; end loop; end Top;
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#ALGOL_68
ALGOL 68
PROC move = (INT n, from, to, via) VOID: IF n > 0 THEN move(n - 1, from, via, to); printf(($"Move disk from pole "g" to pole "gl$, from, to)); move(n - 1, via, to, from) FI ;   main: ( move(4, 1,2,3) )
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#ALGOL_68
ALGOL 68
# "flips" the "bits" in a string (assumed to contain only "0" and "1" characters) # OP FLIP = ( STRING s )STRING: BEGIN STRING result := s; FOR char pos FROM LWB result TO UPB result DO result[ char pos ] := IF result[ char pos ] = "0" THEN "1" ELSE "0" FI OD; result END; # FLIP #   # print the first few members of the Thue-Morse sequence # STRING tm := "0"; TO 7 DO print( ( tm, newline ) ); tm +:= FLIP tm OD
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
#AppleScript
AppleScript
------------------------ THUE MORSE ----------------------   -- thueMorse :: Int -> String on thueMorse(nCycles) script concatBinaryInverse on |λ|(xs) script binaryInverse on |λ|(x) 1 - x end |λ| end script   xs & map(binaryInverse, xs) end |λ| end script   intercalate("", ¬ foldl(concatBinaryInverse, [0], ¬ enumFromTo(1, nCycles))) end thueMorse     --------------------------- TEST ------------------------- on run   thueMorse(6)   --> 0110100110010110100101100110100110010110011010010110100110010110 end run     ------------------------- GENERIC ------------------------   -- enumFromTo :: Int -> Int -> [Int] on enumFromTo(m, n) if m ≤ n then set lst to {} repeat with i from m to n set end of lst to i end repeat lst else {} end if end enumFromTo     -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl     -- intercalate :: Text -> [Text] -> Text 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     -- 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     -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn
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
#Clojure
Clojure
  (defn find-first " Finds first element of collection that satisifies predicate function pred " [pred coll] (first (filter pred coll)))   (defn modpow " b^e mod m (using Java which solves some cases the pure clojure method has to be modified to tackle--i.e. with large b & e and calculation simplications when gcd(b, m) == 1 and gcd(e, m) == 1) " [b e m] (.modPow (biginteger b) (biginteger e) (biginteger m)))   (defn legendre [a p] (modpow a (quot (dec p) 2) p) )   (defn tonelli [n p] " Following Wikipedia https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm " (assert (= (legendre n p) 1) "not a square (mod p)") (loop [q (dec p) ; Step 1 in Wikipedia s 0] (if (zero? (rem q 2)) (recur (quot q 2) (inc s)) (if (= s 1) (modpow n (quot (inc p) 4) p) (let [z (find-first #(= (dec p) (legendre % p)) (range 2 p))] ; Step 2 in Wikipedia (loop [ M s c (modpow z q p) t (modpow n q p) R (modpow n (quot (inc q) 2) p)] (if (= t 1) R (let [i (long (find-first #(= 1 (modpow t (bit-shift-left 1 %) p)) (range 1 M))) ; Step 3 b (modpow c (bit-shift-left 1 (- M i 1)) p) M i c (modpow b 2 p) t (rem (* t c) p) R (rem (* R b) p)] (recur M c t R) ) ) ) ) ) ) ) )     ; Testing--using Python examples (doseq [[n p] [[10, 13], [56, 101], [1030, 10009], [44402, 100049], [665820697, 1000000009], [881398088036, 1000000000039], [41660815127637347468140745042827704103445750172002, 100000000000000000000000000000000000000000000000577]]  :let [r (tonelli n p)]] (println (format "n: %5d p: %d \n\troots: %5d %5d" (biginteger n) (biginteger p) (biginteger r) (biginteger (- p 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
#AutoHotkey
AutoHotkey
Tokenize(s,d,e){ for i,v in x:=StrSplit(StrReplace(StrReplace(StrReplace(s,e e,Chr(0xFFFE)),e d,Chr(0xFFFF)),e),d) x[i]:=StrReplace(StrReplace(v,Chr(0xFFFE),e),Chr(0xFFFF),d) return x }
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
#BBC_BASIC
BBC BASIC
REM >tokenizer PROC_tokenize("one^|uno||three^^^^|four^^^|^cuatro|", "|", "^") END : DEF PROC_tokenize(src$, sep$, esc$) LOCAL field%, char$, escaping%, i% field% = 1 escaping% = FALSE PRINT field%; " "; FOR i% = 1 TO LEN src$ char$ = MID$(src$, i%, 1) IF escaping% THEN PRINT char$; escaping% = FALSE ELSE CASE char$ OF WHEN sep$ PRINT field% += 1 PRINT field%; " "; WHEN esc$ escaping% = TRUE OTHERWISE PRINT char$; ENDCASE ENDIF NEXT PRINT ENDPROC
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
#Java
Java
  public class CirclesTotalArea {   /* * Rectangles are given as 4-element arrays [tx, ty, w, h]. * Circles are given as 3-element arrays [cx, cy, r]. */   private static double distSq(double x1, double y1, double x2, double y2) { return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); }   private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) { double r2 = circ[2] * circ[2]; // Every corner point of rectangle must be inside the circle. return distSq(rect[0], rect[1], circ[0], circ[1]) <= r2 && distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) <= r2 && distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) <= r2 && distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) <= r2; }   private static boolean rectangleSurelyOutsideCircle(double[] rect, double[] circ) { // Circle center point inside rectangle? if(rect[0] <= circ[0] && circ[0] <= rect[0] + rect[2] && rect[1] - rect[3] <= circ[1] && circ[1] <= rect[1]) { return false; } // Otherwise, check that each corner is at least (r + Max(w, h)) away from circle center. double r2 = circ[2] + Math.max(rect[2], rect[3]); r2 = r2 * r2; return distSq(rect[0], rect[1], circ[0], circ[1]) >= r2 && distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) >= r2 && distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) >= r2 && distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) >= r2; }   private static boolean[] surelyOutside;   private static double totalArea(double[] rect, double[][] circs, int d) { // Check if we can get a quick certain answer. int surelyOutsideCount = 0; for(int i = 0; i < circs.length; i++) { if(rectangleFullyInsideCircle(rect, circs[i])) { return rect[2] * rect[3]; } if(rectangleSurelyOutsideCircle(rect, circs[i])) { surelyOutside[i] = true; surelyOutsideCount++; } else { surelyOutside[i] = false; } } // Is this rectangle surely outside all circles? if(surelyOutsideCount == circs.length) { return 0; } // Are we deep enough in the recursion? if(d < 1) { return rect[2] * rect[3] / 3; // Best guess for overlapping portion } // Throw out all circles that are surely outside this rectangle. if(surelyOutsideCount > 0) { double[][] newCircs = new double[circs.length - surelyOutsideCount][3]; int loc = 0; for(int i = 0; i < circs.length; i++) { if(!surelyOutside[i]) { newCircs[loc++] = circs[i]; } } circs = newCircs; } // Subdivide this rectangle recursively and add up the recursively computed areas. double w = rect[2] / 2; // New width double h = rect[3] / 2; // New height double[][] pieces = { { rect[0], rect[1], w, h }, // NW { rect[0] + w, rect[1], w, h }, // NE { rect[0], rect[1] - h, w, h }, // SW { rect[0] + w, rect[1] - h, w, h } // SE }; double total = 0; for(double[] piece: pieces) { total += totalArea(piece, circs, d - 1); } return total; }   public static double totalArea(double[][] circs, int d) { double maxx = Double.NEGATIVE_INFINITY; double minx = Double.POSITIVE_INFINITY; double maxy = Double.NEGATIVE_INFINITY; double miny = Double.POSITIVE_INFINITY; // Find the extremes of x and y for this set of circles. for(double[] circ: circs) { if(circ[0] + circ[2] > maxx) { maxx = circ[0] + circ[2]; } if(circ[0] - circ[2] < minx) { minx = circ[0] - circ[2]; } if(circ[1] + circ[2] > maxy) { maxy = circ[1] + circ[2]; } if(circ[1] - circ[2] < miny) { miny = circ[1] - circ[2]; } } double[] rect = { minx, maxy, maxx - minx, maxy - miny }; surelyOutside = new boolean[circs.length]; return totalArea(rect, circs, d); }   public static void main(String[] args) { double[][] circs = { { 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 } }; double ans = totalArea(circs, 24); System.out.println("Approx. area is " + ans); System.out.println("Error is " + Math.abs(21.56503660 - ans)); } }
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]
#C.2B.2B
C++
#include <map> #include <set>   template<typename Goal> class topological_sorter { protected: struct relations { std::size_t dependencies; std::set<Goal> dependents; }; std::map<Goal, relations> map; public: void add_goal(Goal const &goal) { map[goal]; } void add_dependency(Goal const &goal, Goal const &dependency) { if (dependency == goal) return; auto &dependents = map[dependency].dependents; if (dependents.find(goal) == dependents.end()) { dependents.insert(goal); ++map[goal].dependencies; } } template<typename Container> void add_dependencies(Goal const &goal, Container const &dependencies) { for (auto const &dependency : dependencies) add_dependency(goal, dependency); } template<typename ResultContainer, typename CyclicContainer> void destructive_sort(ResultContainer &sorted, CyclicContainer &unsortable) { sorted.clear(); unsortable.clear(); for (auto const &lookup : map) { auto const &goal = lookup.first; auto const &relations = lookup.second; if (relations.dependencies == 0) sorted.push_back(goal); } for (std::size_t index = 0; index < sorted.size(); ++index) for (auto const &goal : map[sorted[index]].dependents) if (--map[goal].dependencies == 0) sorted.push_back(goal); for (auto const &lookup : map) { auto const &goal = lookup.first; auto const &relations = lookup.second; if (relations.dependencies != 0) unsortable.push_back(goal); } } template<typename ResultContainer, typename CyclicContainer> void sort(ResultContainer &sorted, CyclicContainer &unsortable) { topological_sorter<Goal> temporary = *this; temporary.destructive_sort(sorted, unsortable); } void clear() { map.clear(); } };   /* Example usage with text strings */   #include <fstream> #include <sstream> #include <iostream> #include <string> #include <vector>   using namespace std;   void display_heading(string const &message) { cout << endl << "~ " << message << " ~" << endl; } void display_results(string const &input) { topological_sorter<string> sorter; vector<string> sorted, unsortable; stringstream lines(input); string line; while (getline(lines, line)) { stringstream buffer(line); string goal, dependency; buffer >> goal; sorter.add_goal(goal); while (buffer >> dependency) sorter.add_dependency(goal, dependency); } sorter.destructive_sort(sorted, unsortable); if (sorted.size() == 0) display_heading("Error: no independent variables found!"); else { display_heading("Result"); for (auto const &goal : sorted) cout << goal << endl; } if (unsortable.size() != 0) { display_heading("Error: cyclic dependencies detected!"); for (auto const &goal : unsortable) cout << goal << endl; } } int main(int argc, char **argv) { if (argc == 1) { string example = "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n" "dw01 ieee dw01 dware gtech\n" "dw02 ieee dw02 dware\n" "dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n" "dw04 dw04 ieee dw01 dware gtech\n" "dw05 dw05 ieee dware\n" "dw06 dw06 ieee dware\n" "dw07 ieee dware\n" "dware ieee dware\n" "gtech ieee gtech\n" "ramlib std ieee\n" "std_cell_lib ieee std_cell_lib\n" "synopsys\n" "cycle_11 cycle_12\n" "cycle_12 cycle_11\n" "cycle_21 dw01 cycle_22 dw02 dw03\n" "cycle_22 cycle_21 dw01 dw04"; display_heading("Example: each line starts with a goal followed by it's dependencies"); cout << example << endl; display_results(example); display_heading("Enter lines of data (press enter when finished)"); string line, data; while (getline(cin, line) && !line.empty()) data += line + '\n'; if (!data.empty()) display_results(data); } else while (*(++argv)) { ifstream file(*argv); typedef istreambuf_iterator<char> iterator; display_results(string(iterator(file), iterator())); } }
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.
#F.C5.8Drmul.C3.A6
Fōrmulæ
package turing   type Symbol byte   type Motion byte   const ( Left Motion = 'L' Right Motion = 'R' Stay Motion = 'N' )   type Tape struct { data []Symbol pos, left int blank Symbol }   // NewTape returns a new tape filled with 'data' and position set to 'start'. // 'start' does not need to be range, the tape will be extended if required. func NewTape(blank Symbol, start int, data []Symbol) *Tape { t := &Tape{ data: data, blank: blank, } if start < 0 { t.Left(-start) } t.Right(start) return t }   func (t *Tape) Stay() {} func (t *Tape) Data() []Symbol { return t.data[t.left:] } func (t *Tape) Read() Symbol { return t.data[t.pos] } func (t *Tape) Write(s Symbol) { t.data[t.pos] = s }   func (t *Tape) Dup() *Tape { t2 := &Tape{ data: make([]Symbol, len(t.Data())), blank: t.blank, } copy(t2.data, t.Data()) t2.pos = t.pos - t.left return t2 }   func (t *Tape) String() string { s := "" for i := t.left; i < len(t.data); i++ { b := t.data[i] if i == t.pos { s += "[" + string(b) + "]" } else { s += " " + string(b) + " " } } return s }   func (t *Tape) Move(a Motion) { switch a { case Left: t.Left(1) case Right: t.Right(1) case Stay: t.Stay() } }   const minSz = 16   func (t *Tape) Left(n int) { t.pos -= n if t.pos < 0 { // Extend left var sz int for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 { } newd := make([]Symbol, sz) newl := len(newd) - cap(t.data[t.left:]) n := copy(newd[newl:], t.data[t.left:]) t.data = newd[:newl+n] t.pos += newl - t.left t.left = newl } if t.pos < t.left { if t.blank != 0 { for i := t.pos; i < t.left; i++ { t.data[i] = t.blank } } t.left = t.pos } }   func (t *Tape) Right(n int) { t.pos += n if t.pos >= cap(t.data) { // Extend right var sz int for sz = minSz; t.pos >= sz; sz <<= 1 { } newd := make([]Symbol, sz) n := copy(newd[t.left:], t.data[t.left:]) t.data = newd[:t.left+n] } if i := len(t.data); t.pos >= i { t.data = t.data[:t.pos+1] if t.blank != 0 { for ; i < len(t.data); i++ { t.data[i] = t.blank } } } }   type State string   type Rule struct { State Symbol Write Symbol Motion Next State }   func (i *Rule) key() key { return key{i.State, i.Symbol} } func (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }   type key struct { State Symbol }   type action struct { write Symbol Motion next State }   type Machine struct { tape *Tape start, state State transition map[key]action l func(string, ...interface{}) // XXX }   func NewMachine(rules []Rule) *Machine { m := &Machine{transition: make(map[key]action, len(rules))} if len(rules) > 0 { m.start = rules[0].State } for _, r := range rules { m.transition[r.key()] = r.action() } return m }   func (m *Machine) Run(input *Tape) (int, *Tape) { m.tape = input.Dup() m.state = m.start for cnt := 0; ; cnt++ { if m.l != nil { m.l("%3d %4s: %v\n", cnt, m.state, m.tape) } sym := m.tape.Read() act, ok := m.transition[key{m.state, sym}] if !ok { return cnt, m.tape } m.tape.Write(act.write) m.tape.Move(act.Motion) m.state = act.next } }
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).
#Dyalect
Dyalect
func totient(n) { var tot = n var i = 2 while i * i <= n { if n % i == 0 { while n % i == 0 { n /= i } tot -= tot / i } if i == 2 { i = 1 } i += 2 } if n > 1 { tot -= tot / n } return tot }   print("n\tphi\tprime") var count = 0 for n in 1..25 { var tot = totient(n) var isPrime = n - 1 == tot if isPrime { count += 1 } print("\(n)\t\(tot)\t\(isPrime)") } print("\nNumber of primes up to 25 \t= \(count)") for n in 26..100000 { var tot = totient(n) if tot == n - 1 { count += 1 } if n == 100 || n == 1000 || n % 10000 == 0 { print("Number of primes up to \(n) \t= \(count)") } }
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
#Kotlin
Kotlin
// version 1.1.2   val best = IntArray(32)   fun trySwaps(deck: IntArray, f: Int, d: Int, n: Int) { if (d > best[n]) best[n] = d for (i in n - 1 downTo 0) { if (deck[i] == -1 || deck[i] == i) break if (d + best[i] <= best[n]) return } val deck2 = deck.copyOf() for (i in 1 until n) { val k = 1 shl i if (deck2[i] == -1) { if ((f and k) != 0) continue } else if (deck2[i] != i) continue deck2[0] = i for (j in i - 1 downTo 0) deck2[i - j] = deck[j] trySwaps(deck2, f or k, d + 1, n) } }   fun topswops(n: Int): Int { require(n > 0 && n < best.size) best[n] = 0 val deck0 = IntArray(n + 1) for (i in 1 until n) deck0[i] = -1 trySwaps(deck0, 1, 0, n) return best[n] }   fun main(args: Array<String>) { for (i in 1..10) println("${"%2d".format(i)} : ${topswops(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.
#C.2B.2B
C++
#include <iostream> #include <cmath>   #ifdef M_PI // defined by all POSIX systems and some non-POSIX ones double const pi = M_PI; #else double const pi = 4*std::atan(1); #endif   double const degree = pi/180;   int main() { std::cout << "=== radians ===\n"; std::cout << "sin(pi/3) = " << std::sin(pi/3) << "\n"; std::cout << "cos(pi/3) = " << std::cos(pi/3) << "\n"; std::cout << "tan(pi/3) = " << std::tan(pi/3) << "\n"; std::cout << "arcsin(1/2) = " << std::asin(0.5) << "\n"; std::cout << "arccos(1/2) = " << std::acos(0.5) << "\n"; std::cout << "arctan(1/2) = " << std::atan(0.5) << "\n";   std::cout << "\n=== degrees ===\n"; std::cout << "sin(60°) = " << std::sin(60*degree) << "\n"; std::cout << "cos(60°) = " << std::cos(60*degree) << "\n"; std::cout << "tan(60°) = " << std::tan(60*degree) << "\n"; std::cout << "arcsin(1/2) = " << std::asin(0.5)/degree << "°\n"; std::cout << "arccos(1/2) = " << std::acos(0.5)/degree << "°\n"; std::cout << "arctan(1/2) = " << std::atan(0.5)/degree << "°\n";   return 0; }
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).
#FreeBASIC
FreeBASIC
' version 22-07-2017 ' compile with: fbc -s console   Function f(n As Double) As Double return Sqr(Abs(n)) + 5 * n ^ 3 End Function   ' ------=< MAIN >=------   Dim As Double x, s(1 To 11) Dim As Long i   For i = 1 To 11 Print Str(i); Input " => ", s(i) Next   Print Print String(20,"-")   i -= 1 Do Print "f(" + Str(s(i)) + ") = "; x = f(s(i)) If x > 400 Then Print "-=< overflow >=-" Else Print x End If i -= 1 Loop Until i < 1   ' empty keyboard buffer While InKey <> "" : Wend Print : Print "hit any key to end program" Sleep End
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm. From the wikipedia entry: ask for 11 numbers to be read into a sequence S reverse sequence S for each item in sequence S result := call a function to do an operation if result overflows alert user else print result The task is to implement the algorithm: Use the function:     f ( x ) = | x | 0.5 + 5 x 3 {\displaystyle f(x)=|x|^{0.5}+5x^{3}} The overflow condition is an answer of greater than 400. The 'user alert' should not stop processing of other items of the sequence. Print a prompt before accepting eleven, textual, numeric inputs. You may optionally print the item as well as its associated result, but the results must be in reverse order of input. The sequence   S   may be 'implied' and so not shown explicitly. Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#Go
Go
package main   import ( "fmt" "log" "math" )   func main() { // prompt fmt.Print("Enter 11 numbers: ") // accept sequence var s [11]float64 for i := 0; i < 11; { if n, _ := fmt.Scan(&s[i]); n > 0 { i++ } } // reverse sequence for i, item := range s[:5] { s[i], s[10-i] = s[10-i], item } // iterate for _, item := range s { if result, overflow := f(item); overflow { // send alerts to stderr log.Printf("f(%g) overflow", item) } else { // send normal results to stdout fmt.Printf("f(%g) = %g\n", item, result) } } }   func f(x float64) (float64, bool) { result := math.Sqrt(math.Abs(x)) + 5*x*x*x return result, result > 400 }
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.
#Sidef
Sidef
var conditions = [ { false }, {|a| a.len == 13 }, {|a| [a[7..12]].count(true) == 3 }, {|a| [a[2..12 `by` 2]].count(true) == 2 }, {|a| a[5] ? (a[6] && a[7]) : true }, {|a| !a[2] && !a[3] && !a[4] }, {|a| [a[1..11 `by` 2]].count(true) == 4 }, {|a| a[2] == true^a[3] }, {|a| a[7] ? (a[5] && a[6]) : true }, {|a| [a[1..6]].count(true) == 3 }, {|a| [a[11,12]].count(true) == 2 }, {|a| [a[7..9]].count(true) == 1 }, {|a| [a[1..11]].count(true) == 4 }, ]   func miss(args) { 1..12 -> grep {|i| conditions[i](args) != args[i] } }   for k in (^(1<<12)) { var t = ("0%012b" % k -> chars.map {|bit| bit == '1' }) var no = miss(t) no.len == 0 && say "Solution: true statements are #{1..12->grep{t[_]}.join(' ')}" no.len == 1 && say "1 miss (#{no[0]}): true statements are #{1..12->grep{t[_]}.join(' ')}" }
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.
#Prolog
Prolog
/* To evaluate the truth table a line of text is inputted and then there are three steps Let's say the expression is: 'not a and (b or c)'   Step 1: tokenize into atoms and brackets eg: Tokenized = [ not, a, and, '(', b, or, c, ')' ].   Step 2: convert to a term that can be evaluated, and get out the variables eg: Expression = op(and, op(not, a), op(or, b, c)), Variables = [ a, b, c ]   Step 3: permeate over the variables, substituting the values for each var, and evaluate the expression for each permutation eg: [ 0, 0, 0] op(and, op(not, 0), op(or, 0, 0)) op(and, 1, op(or, 0, 0)) op(and, 1, 0) 0   [ 0, 0, 1] op(and, op(not, 0), op(or, 0, 1)) op(and, 1, op(or, 0, 0)) op(and, 1, 1) 1 */ truth_table :- current_input(In), read_line_to_codes(In, Line), atom_codes(A, Line), atom_chars(A, Chars),   % parse everything into the form we want phrase(tok(Tok), Chars, _), phrase(expr(Expr,Vars), Tok, _), list_to_set(Vars,VarSet),   % evaluate print_expr(Expr, VarSet), !.   print_expr(Expr, Vars) :- % write the header (once) maplist(format('~p '), Vars), format('~n'),   % write the results for as many times as there are rows eval_expr(Expr, Vars, Tvals, R), maplist(format('~p '), Tvals), format('~p~n', R), fail. print_expr(_, _).     % Step 1 - tokenize the input into spaces, brackets and atoms tok([A|As]) --> spaces(_), chars([X|Xs]), {atom_codes(A, [X|Xs])}, spaces(_), tok(As). tok([A|As]) --> spaces(_), bracket(A), spaces(_), tok(As). tok([]) --> []. chars([X|Xs]) --> char(X), { dif(X, ')'), dif(X, '(') }, !, chars(Xs). chars([]) --> []. spaces([X|Xs]) --> space(X), !, spaces(Xs). spaces([]) --> []. bracket('(') --> ['(']. bracket(')') --> [')'].     % Step 2 - Parse the expression into an evaluable term expr(op(I, E, E2), V) --> starter(E, V1), infix(I), expr(E2, V2), { append(V1, V2, V) }. expr(E, V) --> starter(E, V).   starter(op(not, E),V) --> [not], expr(E, V). starter(E,V) --> ['('], expr(E,V), [')']. starter(V,[V]) --> variable(V).   infix(or) --> [or]. infix(and) --> [and]. infix(xor) --> [xor]. infix(nand) --> [nand].   variable(V) --> [V], \+ infix(V), \+ bracket(V). space(' ') --> [' ']. char(X) --> [X], { dif(X, ' ') }.     % Step 3 - evaluate the parsed expression eval_expr(Expr, Vars, Tvals, R) :- length(Vars,Len), length(Tvals, Len), maplist(truth_val, Tvals), eval(Expr, [Tvals,Vars],R).   eval(X, [Vals,Vars], R) :- nth1(N,Vars,X), nth1(N,Vals,R). eval(op(Op,A,B), V, R) :- eval(A,V,Ae), eval(B,V,Be), e(Op,Ae,Be,R). eval(op(not,A), V, R) :- eval(A,V,Ae), e(not,Ae,R).   truth_val(0). truth_val(1).   e(or,0,0,0). e(or,0,1,1). e(or,1,0,1). e(or,1,1,1). e(and,0,0,0). e(and,0,1,0). e(and,1,0,0). e(and,1,1,1). e(xor,0,0,0). e(xor,0,1,1). e(xor,1,0,1). e(xor,1,1,0). e(nand,0,0,1). e(nand,0,1,1). e(nand,1,0,1). e(nand,1,1,0). e(not, 1, 0). e(not, 0, 1).
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
#R
R
  ## Plotting Ulam spiral (for primes) 2/12/17 aev ## plotulamspirR(n, clr, fn, ttl, psz=600), where: n - initial size; ## clr - color; fn - file name; ttl - plot title; psz - picture size. ## require(numbers); plotulamspirR <- function(n, clr, fn, ttl, psz=600) { cat(" *** START:", date(), "n=",n, "clr=",clr, "psz=", psz, "\n"); if (n%%2==0) {n=n+1}; n2=n*n; x=y=floor(n/2); xmx=ymx=cnt=1; dir="R"; ttl= paste(c(ttl, n,"x",n," matrix."), sep="", collapse=""); cat(" ***", ttl, "\n"); M <- matrix(c(0), ncol=n, nrow=n, byrow=TRUE); for (i in 1:n2) { if(isPrime(i)) {M[x,y]=1}; if(dir=="R") {if(xmx>0) {x=x+1;xmx=xmx-1} else {dir="U";ymx=cnt;y=y-1;ymx=ymx-1}; next}; if(dir=="U") {if(ymx>0) {y=y-1;ymx=ymx-1} else {dir="L";cnt=cnt+1;xmx=cnt;x=x-1;xmx=xmx-1}; next}; if(dir=="L") {if(xmx>0) {x=x-1;xmx=xmx-1} else {dir="D";ymx=cnt;y=y+1;ymx=ymx-1}; next}; if(dir=="D") {if(ymx>0) {y=y+1;ymx=ymx-1} else {dir="R";cnt=cnt+1;xmx=cnt;x=x+1;xmx=xmx-1}; next}; }; plotmat(M, fn, clr, ttl,,psz); cat(" *** END:",date(),"\n"); }   ## Executing: plotulamspirR(100, "red", "UlamSpiralR1", "Ulam Spiral: "); plotulamspirR(200, "red", "UlamSpiralR2", "Ulam Spiral: ",1240);  
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.]
#Java
Java
import java.util.BitSet;   public class Main {   public static void main(String[] args){   final int MAX = 1000000;   //Sieve of Eratosthenes (using BitSet only for odd numbers) BitSet primeList = new BitSet(MAX>>1); primeList.set(0,primeList.size(),true);   int sqroot = (int) Math.sqrt(MAX); primeList.clear(0); for(int num = 3; num <= sqroot; num+=2) { if( primeList.get(num >> 1) ) { int inc = num << 1; for(int factor = num * num; factor < MAX; factor += inc) { //if( ((factor) & 1) == 1) //{ primeList.clear(factor >> 1); //} } } } //Sieve ends...   //Find Largest Truncatable Prime. (so we start from 1000000 - 1 int rightTrunc = -1, leftTrunc = -1; for(int prime = (MAX - 1) | 1; prime >= 3; prime -= 2) { if(primeList.get(prime>>1)) { //Already found Right Truncatable Prime? if(rightTrunc == -1) { int right = prime; while(right > 0 && right % 2 != 0 && primeList.get(right >> 1)) right /= 10; if(right == 0) rightTrunc = prime; }   //Already found Left Truncatable Prime? if(leftTrunc == -1 ) { //Left Truncation String left = Integer.toString(prime); if(!left.contains("0")) { while( left.length() > 0 ){ int iLeft = Integer.parseInt(left); if(!primeList.get( iLeft >> 1)) break; left = left.substring(1); } if(left.length() == 0) leftTrunc = prime; } } if(leftTrunc != -1 && rightTrunc != -1) //Found both? then Stop loop { break; } } } System.out.println("Left Truncatable : " + leftTrunc); System.out.println("Right Truncatable : " + rightTrunc); } }  
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.
#AutoHotkey
AutoHotkey
AddNode(Tree,1,2,3,1) ; Build global Tree AddNode(Tree,2,4,5,2) AddNode(Tree,3,6,0,3) AddNode(Tree,4,7,0,4) AddNode(Tree,5,0,0,5) AddNode(Tree,6,8,9,6) AddNode(Tree,7,0,0,7) AddNode(Tree,8,0,0,8) AddNode(Tree,9,0,0,9)   MsgBox % "Preorder: " PreOrder(Tree,1) ; 1 2 4 7 5 3 6 8 9 MsgBox % "Inorder: " InOrder(Tree,1) ; 7 4 2 5 1 8 6 9 3 MsgBox % "postorder: " PostOrder(Tree,1) ; 7 4 5 2 8 9 6 3 1 MsgBox % "levelorder: " LevOrder(Tree,1) ; 1 2 3 4 5 6 7 8 9   AddNode(ByRef Tree,Node,Left,Right,Value) { if !isobject(Tree) Tree := object()   Tree[Node, "L"] := Left Tree[Node, "R"] := Right Tree[Node, "V"] := Value }   PreOrder(Tree,Node) { ptree := Tree[Node, "V"] " " . ((L:=Tree[Node, "L"]) ? PreOrder(Tree,L) : "") . ((R:=Tree[Node, "R"]) ? PreOrder(Tree,R) : "") return ptree } InOrder(Tree,Node) { Return itree := ((L:=Tree[Node, "L"]) ? InOrder(Tree,L) : "") . Tree[Node, "V"] " " . ((R:=Tree[Node, "R"]) ? InOrder(Tree,R) : "") } PostOrder(Tree,Node) { Return ptree := ((L:=Tree[Node, "L"]) ? PostOrder(Tree,L) : "") . ((R:=Tree[Node, "R"]) ? PostOrder(Tree,R) : "") . Tree[Node, "V"] " " } LevOrder(Tree,Node,Lev=1) { Static ; make node lists static i%Lev% .= Tree[Node, "V"] " " ; build node lists in every level If (L:=Tree[Node, "L"]) LevOrder(Tree,L,Lev+1) If (R:=Tree[Node, "R"]) LevOrder(Tree,R,Lev+1) If (Lev > 1) Return While i%Lev% ; concatenate node lists from all levels t .= i%Lev%, Lev++ Return t }