task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle). For the inverse functions,   use the same number and convert its answer to radians and degrees. If your language does not have trigonometric functions available or only has some available,   write functions to calculate the functions based on any   known approximation or identity.
#F.23
F#
open NUnit.Framework open FsUnit   // radian   [<Test>] let ``Verify that sin pi returns 0`` () = let x = System.Math.Sin System.Math.PI System.Math.Round(x,5) |> should equal 0   [<Test>] let ``Verify that cos pi returns -1`` () = let x = System.Math.Cos System.Math.PI System.Math.Round(x,5) |> should equal -1   [<Test>] let ``Verify that tan pi returns 0`` () = let x = System.Math.Tan System.Math.PI System.Math.Round(x,5) |> should equal 0   [<Test>] let ``Verify that sin pi/2 returns 1`` () = let x = System.Math.Sin (System.Math.PI / 2.0) System.Math.Round(x,5) |> should equal 1   [<Test>] let ``Verify that cos pi/2 returns -1`` () = let x = System.Math.Cos (System.Math.PI / 2.0) System.Math.Round(x,5) |> should equal 0   [<Test>] let ``Verify that sin pi/3 returns sqrt 3/2`` () = let actual = System.Math.Sin (System.Math.PI / 3.0) let expected = System.Math.Round((System.Math.Sqrt 3.0) / 2.0, 5) System.Math.Round(actual,5) |> should equal expected   [<Test>] let ``Verify that cos pi/3 returns -1`` () = let x = System.Math.Cos (System.Math.PI / 3.0) System.Math.Round(x,5) |> should equal 0.5   [<Test>] let ``Verify that cos and sin of pi/4 return same value`` () = let c = System.Math.Cos (System.Math.PI / 4.0) let s = System.Math.Sin (System.Math.PI / 4.0) System.Math.Round(c,5) = System.Math.Round(s,5) |> should be True   [<Test>] let ``Verify that acos pi/3 returns 1/2`` () = let actual = System.Math.Acos 0.5 let expected = System.Math.Round((System.Math.PI / 3.0),5) System.Math.Round(actual,5) |> should equal expected   [<Test>] let ``Verify that asin 1 returns pi/2`` () = let actual = System.Math.Asin 1.0 let expected = System.Math.Round((System.Math.PI / 2.0),5) System.Math.Round(actual,5) |> should equal expected   [<Test>] let ``Verify that atan 0 returns 0`` () = let actual = System.Math.Atan 0.0 let expected = System.Math.Round(0.0,5) System.Math.Round(actual,5) |> should equal expected   // degree   let toRadians d = d * System.Math.PI / 180.0   [<Test>] let ``Verify that pi is 180 degrees`` () = toRadians 180.0 |> should equal System.Math.PI   [<Test>] let ``Verify that pi/2 is 90 degrees`` () = toRadians 90.0 |> should equal (System.Math.PI / 2.0)   [<Test>] let ``Verify that pi/3 is 60 degrees`` () = toRadians 60.0 |> should equal (System.Math.PI / 3.0)   [<Test>] let ``Verify that sin 180 returns 0`` () = let x = System.Math.Sin (toRadians 180.0) System.Math.Round(x,5) |> should equal 0   [<Test>] let ``Verify that cos 180 returns -1`` () = let x = System.Math.Cos (toRadians 180.0) System.Math.Round(x,5) |> should equal -1   [<Test>] let ``Verify that tan 180 returns 0`` () = let x = System.Math.Tan (toRadians 180.0) System.Math.Round(x,5) |> should equal 0   [<Test>] let ``Verify that sin 90 returns 1`` () = let x = System.Math.Sin (toRadians 90.0) System.Math.Round(x,5) |> should equal 1   [<Test>] let ``Verify that cos 90 returns -1`` () = let x = System.Math.Cos (toRadians 90.0) System.Math.Round(x,5) |> should equal 0   [<Test>] let ``Verify that sin 60 returns sqrt 3/2`` () = let actual = System.Math.Sin (toRadians 60.0) let expected = System.Math.Round((System.Math.Sqrt 3.0) / 2.0, 5) System.Math.Round(actual,5) |> should equal expected   [<Test>] let ``Verify that cos 60 returns -1`` () = let x = System.Math.Cos (toRadians 60.0) System.Math.Round(x,5) |> should equal 0.5   [<Test>] let ``Verify that cos and sin of 45 return same value`` () = let c = System.Math.Cos (toRadians 45.0) let s = System.Math.Sin (toRadians 45.0) System.Math.Round(c,5) = System.Math.Round(s,5) |> should be True
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm. From the wikipedia entry: ask for 11 numbers to be read into a sequence S reverse sequence S for each item in sequence S result := call a function to do an operation if result overflows alert user else print result The task is to implement the algorithm: Use the function:     f ( x ) = | x | 0.5 + 5 x 3 {\displaystyle f(x)=|x|^{0.5}+5x^{3}} The overflow condition is an answer of greater than 400. The 'user alert' should not stop processing of other items of the sequence. Print a prompt before accepting eleven, textual, numeric inputs. You may optionally print the item as well as its associated result, but the results must be in reverse order of input. The sequence   S   may be 'implied' and so not shown explicitly. Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#min
min
((0 <) (-1 *) when) :abs (((abs 0.5 pow) (3 pow 5 * +)) cleave) :fn "Enter 11 numbers:" puts! (gets float) 11 times (fn (400 <=) (pop "Overflow") unless puts!) 11 times
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).
#Nascom_BASIC
Nascom BASIC
  10 REM Trabb Pardo-Knuth algorithm 20 REM Used "magic numbers" because of strict 30 REM specification of the algorithm. 40 DEF FNF(N)=SQR(ABS(N))+5*N*N*N 50 DIM S(10) 60 PRINT "Enter 11 numbers." 70 FOR I=0 TO 10 80 PRINT STR$(I+1); 90 INPUT S(I) 100 NEXT I 110 PRINT 120 REM ** Reverse 130 FOR I=0 TO 10/2 140 TMP=S(I) 150 S(I)=S(10-I) 160 S(10-I)=TMP 170 NEXT I 180 REM ** Results 190 FOR I=0 TO 10 200 PRINT "f(";STR$(S(I));") ="; 210 R=FNF(S(I)) 220 IF R>400 THEN PRINT " overflow":GOTO 240 230 PRINT R 240 NEXT I 250 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.
#Sidef
Sidef
loop { var expr = Sys.readln("\nBoolean expression (e.g. 'a & b'): ").strip.lc break if expr.is_empty;   var vars = expr.scan(/[[:alpha:]]+/) if (vars.is_empty) { say "no variables detected in your boolean expression" next }   var prefix = []; var suffix = [];   vars.each { |v| print "#{v}\t" prefix << "[false, true].each { |#{v}|" suffix << "}" } say "| #{expr}"   var body = ("say (" + vars.map{|v| v+",'\t'," }.join + " '| ', #{expr})") eval(prefix + [body] + suffix -> join("\n")) }
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
#VBScript
VBScript
  Function build_spiral(n) 'declare a two dimentional array Dim matrix() ReDim matrix(n-1,n-1) 'determine starting point x = (n-1)/2 : y = (n-1)/2 'set the initial iterations x_max = 1 : y_max = 1 : count = 1 'set initial direction dir = "R" 'populate the array For i = 1 To n*n l = Len(n*n) If IsPrime(i) Then matrix(x,y) = Right("000" & i,l) Else matrix(x,y) = String(l,"-") End If Select Case dir Case "R" If x_max > 0 Then x = x + 1 : x_max = x_max - 1 Else dir = "U" : y_max = count y = y - 1 : y_max = y_max - 1 End If Case "U" If y_max > 0 Then y = y - 1 : y_max = y_max - 1 Else dir = "L" : count = count + 1 : x_max = count x = x - 1 : x_max = x_max - 1 End If Case "L" If x_max > 0 Then x = x - 1 : x_max = x_max - 1 Else dir = "D" : y_max = count y = y + 1 : y_max = y_max - 1 End If Case "D" If y_max > 0 Then y = y + 1 : y_max = y_max - 1 Else dir = "R" : count = count + 1 : x_max = count x = x + 1 : x_max = x_max - 1 End If End Select Next 'print the matrix For y = 0 To n - 1 For x = 0 To n - 1 If x = n - 1 Then WScript.StdOut.Write matrix(x,y) Else WScript.StdOut.Write matrix(x,y) & vbTab End If Next WScript.StdOut.WriteLine Next End Function   Function IsPrime(n) If n = 2 Then IsPrime = True ElseIf n <= 1 Or n Mod 2 = 0 Then IsPrime = False Else IsPrime = True For i = 3 To Int(Sqr(n)) Step 2 If n Mod i = 0 Then IsPrime = False Exit For End If Next End If End Function   'test with 9 build_spiral(9)  
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.]
#OpenEdge.2FProgress
OpenEdge/Progress
FUNCTION isPrime RETURNS LOGICAL ( i_i AS INT ):   DEF VAR ii AS INT.   DO ii = 2 TO SQRT( i_i ):   IF i_i MODULO ii = 0 THEN RETURN FALSE.   END.   RETURN TRUE AND i_i > 1.   END FUNCTION. /* isPrime */   FUNCTION isLeftTruncatablePrime RETURNS LOGICAL ( i_i AS INT ):   DEF VAR ii AS INT. DEF VAR cc AS CHAR. DEF VAR lresult AS LOGICAL INITIAL TRUE.   cc = STRING( i_i ).   DO WHILE cc > "": lresult = lresult AND isPrime( INTEGER( cc ) ). cc = SUBSTRING( cc, 2 ). END.   RETURN lresult.   END FUNCTION. /* isLeftTruncatablePrime */   FUNCTION isRightTruncatablePrime RETURNS LOGICAL ( i_i AS INT ):   DEF VAR ii AS INT. DEF VAR cc AS CHAR. DEF VAR lresult AS LOGICAL INITIAL TRUE.   cc = STRING( i_i ).   DO WHILE cc > "": lresult = lresult AND isPrime( INTEGER( cc ) ). cc = SUBSTRING( cc, 1, LENGTH( cc ) - 1 ). END.   RETURN lresult.   END FUNCTION. /* isRightTruncatablePrime */   FUNCTION getHighestTruncatablePrimes RETURNS CHARACTER ( i_imax AS INTEGER ):   DEF VAR ii AS INT. DEF VAR ileft AS INT. DEF VAR iright AS INT.   DO ii = i_imax TO 1 BY -1 WHILE ileft = 0 OR iright = 0:   IF INDEX( STRING( ii ), "0" ) = 0 THEN DO: IF ileft = 0 AND isLeftTruncatablePrime( ii ) THEN ileft = ii. IF iright = 0 AND isRightTruncatablePrime( ii ) THEN iright = ii. END.   END.   RETURN SUBSTITUTE("Left: &1~nRight: &2", ileft, iright ).   END FUNCTION. /* getHighestTruncatablePrimes */   MESSAGE getHighestTruncatablePrimes( 1000000 ) VIEW-AS ALERT-BOX.  
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.
#CoffeeScript
CoffeeScript
  # In this example, we don't encapsulate binary trees as objects; instead, we have a # convention on how to store them as arrays, and we namespace the functions that # operate on those data structures. binary_tree = preorder: (tree, visit) -> return unless tree? [node, left, right] = tree visit node binary_tree.preorder left, visit binary_tree.preorder right, visit   inorder: (tree, visit) -> return unless tree? [node, left, right] = tree binary_tree.inorder left, visit visit node binary_tree.inorder right, visit   postorder: (tree, visit) -> return unless tree? [node, left, right] = tree binary_tree.postorder left, visit binary_tree.postorder right, visit visit node   levelorder: (tree, visit) -> q = [] q.push tree while q.length > 0 t = q.shift() continue unless t? [node, left, right] = t visit node q.push left q.push right   do -> tree = [1, [2, [4, [7]], [5]], [3, [6, [8],[9]]]] test_walk = (walk_function_name) -> output = [] binary_tree[walk_function_name] tree, output.push.bind(output) console.log walk_function_name, output.join ' ' test_walk "preorder" test_walk "inorder" test_walk "postorder" test_walk "levelorder"  
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
#Arturo
Arturo
str: "Hello,How,Are,You,Today"   print join.with:"." split.by:"," str
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
#Astro
Astro
let text = 'Hello,How,Are,You,Today' let tokens = text.split(||,||) print tokens.join(with: '.')
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program fcttime.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall   .equ N1, 1000000 @ loop number .equ NBMEASURE, 10 @ measure number   /*********************************/ /* Initialized data */ /*********************************/ .data szMessError: .asciz "Error detected !!!!. \n" szMessSep: .asciz "****************************\n" szMessTemps: .ascii "Function time : " sSecondes: .fill 10,1,' ' .ascii " s " sMicroS: .fill 10,1,' ' .asciz " micros\n"   szCarriageReturn: .asciz "\n" /*********************************/ /* UnInitialized data */ /*********************************/ .bss .align 4 dwDebut: .skip 8 dwFin: .skip 8 /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program adr r0,mult @ function address to measure mov r1,#1 @ parameter 1 function mov r2,#2 @ parameter 2 function bl timeMesure cmp r0,#0 blt 99f adr r0,sum @ function address to measure mov r1,#1 mov r2,#2 bl timeMesure cmp r0,#0 blt 99f b 100f 99: @ error ldr r0,iAdrszMessError bl affichageMess 100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call   iAdrszMessError: .int szMessError iAdrszCarriageReturn: .int szCarriageReturn /**************************************************************/ /* examble function sum */ /**************************************************************/ /* r0 contains op 1 */ /* r1 contains op 2 */ sum: push {lr} @ save registres add r0,r1 100: pop {lr} @ restaur registers bx lr @ function return   /**************************************************************/ /* exemple execution multiplication */ /**************************************************************/ /* r0 contains op 1 */ /* r1 contains op 2 */ mult: push {lr} @ save registres mul r0,r1,r0 100: pop {lr} @ restaur registers bx lr @ function return   /**************************************************************/ /* Procedure for measuring the execution time of a routine */ /**************************************************************/ /* r0 contains the function address */ timeMesure: push {r1-r8,lr} @ save registres mov r4,r0 @ save function address mov r5,r1 @ save param 1 mov r6,r2 @ save param 2 mov r8,#0 1: ldr r0,iAdrdwDebut @ start time area mov r1,#0 mov r7, #0x4e @ call system gettimeofday svc #0 cmp r0,#0 @ error ? blt 100f @ return error ldr r7,iMax @ run number mov r0,r5 @ param function 1 mov r1,r6 @ param function 2 2: @ loop blx r4 @ call of the function to be measured subs r7,#1 @ decrement run bge 2b @ loop if not zero @ ldr r0,iAdrdwFin @ end time area mov r1,#0 mov r7, #0x4e @ call system gettimeofday svc #0 cmp r0,#0 @ error ? blt 100f @ return error @ compute time ldr r0,iAdrdwDebut @ start time area //vidmemtit mesure r0 2 ldr r2,[r0] @ secondes ldr r3,[r0,#4] @ micro secondes ldr r0,iAdrdwFin @ end time area ldr r1,[r0] @ secondes ldr r0,[r0,#4] @ micro secondes sub r2,r1,r2 @ secondes number subs r3,r0,r3 @ microsecondes number sublt r2,#1 @ if negative sub 1 seconde to secondes ldr r1,iSecMicro addlt r3,r1 @ and add 1000000 to microsecondes number mov r0,r2 @ conversion secondes ldr r1,iAdrsSecondes bl conversion10 mov r0,r3 @ conversion microsecondes ldr r1,iAdrsMicroS bl conversion10 ldr r0,iAdrszMessTemps bl affichageMess @ display message add r8,#1 cmp r8,#NBMEASURE ble 1b ldr r0,iAdrszMessSep @ display separator bl affichageMess 100: pop {r1-r8,lr} @ restaur registers bx lr @ function return iMax: .int N1 iAdrdwDebut: .int dwDebut iAdrdwFin: .int dwFin iSecMicro: .int 1000000 iAdrsSecondes: .int sSecondes iAdrsMicroS: .int sMicroS iAdrszMessTemps: .int szMessTemps iAdrszMessSep: .int szMessSep   /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {r0,r1,r2,r7,lr} @ save registres mov r2,#0 @ counter length 1: @ loop length calculation ldrb r1,[r0,r2] @ read octet start position + index cmp r1,#0 @ if 0 its over addne r2,r2,#1 @ else add 1 in the length bne 1b @ and loop @ so here r2 contains the length of the message mov r1,r0 @ address message in r1 mov r0,#STDOUT @ code to write to the standard output Linux mov r7, #WRITE @ code call system "write" svc #0 @ call systeme pop {r0,r1,r2,r7,lr} @ restaur registers */ bx lr @ return /******************************************************************/ /* Converting a register to a decimal */ /******************************************************************/ /* r0 contains value and r1 address area */ .equ LGZONECAL, 10 conversion10: push {r1-r4,lr} @ save registers mov r3,r1 mov r2,#LGZONECAL 1: @ start loop bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1 add r1,#48 @ digit strb r1,[r3,r2] @ store digit on area cmp r0,#0 @ stop if quotient = 0 subne r2,#1 @ previous position bne 1b @ else loop @ end replaces digit in front of area mov r4,#0 2: ldrb r1,[r3,r2] strb r1,[r3,r4] @ store in area begin add r4,#1 add r2,#1 @ previous position cmp r2,#LGZONECAL @ end ble 2b @ loop mov r1,#' ' 3: strb r1,[r3,r4] add r4,#1 cmp r4,#LGZONECAL @ end ble 3b 100: pop {r1-r4,lr} @ restaur registres bx lr @return /***************************************************/ /* division par 10 signé */ /* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/* /* and http://www.hackersdelight.org/ */ /***************************************************/ /* r0 dividende */ /* r0 quotient */ /* r1 remainder */ divisionpar10: /* r0 contains the argument to be divided by 10 */ push {r2-r4} @ save registers */ mov r4,r0 mov r3,#0x6667 @ r3 <- magic_number lower movt r3,#0x6666 @ r3 <- magic_number upper smull r1, r2, r3, r0 @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) mov r2, r2, ASR #2 @ r2 <- r2 >> 2 mov r1, r0, LSR #31 @ r1 <- r0 >> 31 add r0, r2, r1 @ r0 <- r2 + r1 add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) pop {r2-r4} bx lr @ return  
http://rosettacode.org/wiki/Top_rank_per_group
Top rank per group
Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190
#Ceylon
Ceylon
class Employee(name, id, salary, dept) { shared String name; shared String id; shared Integer salary; shared String dept;   string => "``name`` ``id`` $``salary``.00 ``dept``"; }   Employee[] employees = [ Employee("Tyler Bennett", "E10297", 32000, "D101"), Employee("John Rappl", "E21437", 47000, "D050"), Employee("George Woltman", "E00127", 53500, "D101"), Employee("Adam Smith", "E63535", 18000, "D202"), Employee("Claire Buckman", "E39876", 27800, "D202"), Employee("David McClellan", "E04242", 41500, "D101"), Employee("Rich Holcomb", "E01234", 49500, "D202"), Employee("Nathan Adams", "E41298", 21900, "D050"), Employee("Richard Potter", "E43128", 15900, "D101"), Employee("David Motsinger", "E27002", 19250, "D202"), Employee("Tim Sampair", "E03033", 27000, "D101"), Employee("Kim Arlich", "E10001", 57000, "D190"), Employee("Timothy Grove", "E16398", 29900, "D190") ];   "This is the main function." shared void run() {   value topRanked = topSalaries(employees, 3);   for (dept -> staff in topRanked) { print(dept); for (employee in staff) { print("\t``employee``"); } } }   Map<String, {Employee*}> topSalaries({Employee*} employees, Integer n) => map { for (dept -> staff in employees.group(Employee.dept)) dept -> staff.sort(byDecreasing(Employee.salary)).take(n) };
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedia tic-tac-toe.
#AppleScript
AppleScript
property OMask : missing value property XMask : missing value property winningNumbers : {7, 56, 73, 84, 146, 273, 292, 448} property difficulty : missing value   repeat set OMask to 0 set XMask to 0   if button returned of (display dialog "Who should start?" buttons {"I shoud", "CPU"}) = "CPU" then set OMask to npcGet() set difficulty to button returned of (display dialog "Please choose your difficulty" buttons {"Hard", "Normal"})   repeat set XMask to XMask + 2 ^ (nGet() - 1) if winnerForMask(XMask) or OMask + XMask = 511 then exit repeat set OMask to npcGet() if winnerForMask(OMask) or OMask + XMask = 511 then exit repeat end repeat   if winnerForMask(OMask) then set msg to "CPU Wins!" else if winnerForMask(XMask) then set msg to "You WON!!!" else set msg to "It's a draw" end if   display dialog msg & return & return & drawGrid() & return & return & "Do you want to play again?" end repeat   on nGet() set theMessage to "It's your turn Player 1, please fill in the number for X" & return & return & drawGrid() repeat set value to text returned of (display dialog theMessage default answer "") if (offset of value in "123456789") is not 0 then if not positionIsUsed(value as integer) then exit repeat end if end repeat return value as integer end nGet   on npcGet() --first get the free positions set freeSpots to {} repeat with s from 1 to 9 if not positionIsUsed(s) then set end of freeSpots to 2 ^ (s - 1) end repeat --second check if 1 move can make the CPU win repeat with spot in freeSpots if winnerForMask(OMask + spot) then return OMask + spot end repeat   if difficulty is "Hard" and OMask is 0 then if XMask = 1 or XMask = 4 then return 2 if XMask = 64 or XMask = 256 then return 128 end if --third check if a user can make make it win (defensive) place it on position repeat with spot in freeSpots if winnerForMask(XMask + spot) then return OMask + spot end repeat   --fourth check if CPU can win in two moves repeat with spot1 in freeSpots repeat with spot2 in freeSpots if winnerForMask(OMask + spot1 + spot2) then return OMask + spot2 end repeat end repeat --fifth check if player can win in two moves repeat with spot1 in freeSpots repeat with spot2 in reverse of freeSpots if winnerForMask(XMask + spot1 + spot2) then return OMask + spot1 end repeat end repeat --at last pick a random spot if XMask + OMask = 0 and difficulty = "Hard" then return 1   return OMask + (some item of freeSpots) end npcGet   on winnerForMask(mask) repeat with winLine in winningNumbers if BWAND(winLine, mask) = contents of winLine then return true end repeat return false end winnerForMask   on drawGrid() set grid to "" repeat with o from 0 to 8 if BWAND(OMask, 2 ^ o) = 2 ^ o then set grid to grid & "O" else if BWAND(XMask, 2 ^ o) = 2 ^ o then set grid to grid & "X" else set grid to grid & o + 1 end if if o is in {2, 5} then set grid to grid & return end repeat return grid end drawGrid   on positionIsUsed(pos) return BWAND(OMask + XMask, 2 ^ (pos - 1)) = 2 ^ (pos - 1) end positionIsUsed   on BWAND(n1, n2) set theResult to 0 repeat with o from 0 to 8 if (n1 mod 2) = 1 and (n2 mod 2) = 1 then set theResult to theResult + 2 ^ o set {n1, n2} to {n1 div 2, n2 div 2} end repeat return theResult as integer end BWAND
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#AutoIt
AutoIt
Func move($n, $from, $to, $via) If ($n = 1) Then ConsoleWrite(StringFormat("Move disk from pole "&$from&" To pole "&$to&"\n")) Else move($n - 1, $from, $via, $to) move(1, $from, $to, $via) move($n - 1, $via, $to, $from) EndIf EndFunc   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
#Excel
Excel
thueMorse =LAMBDA(n, APPLYN(n)( LAMBDA(bits, APPENDCOLS(bits)( LAMBDA(x, IF(0 < x, 0, 1) )(bits) ) ) )(0) )
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
#Perl
Perl
use bigint; use ntheory qw(is_prime powmod kronecker);   sub tonelli_shanks { my($n,$p) = @_; return if kronecker($n,$p) <= 0; my $Q = $p - 1; my $S = 0; $Q >>= 1 and $S++ while 0 == $Q%2; return powmod($n,int(($p+1)/4), $p) if $S == 1;   my $c; for $n (2..$p) { next if kronecker($n,$p) >= 0; $c = powmod($n, $Q, $p); last; }   my $R = powmod($n, ($Q+1) >> 1, $p ); # ? my $t = powmod($n, $Q, $p ); while (($t-1) % $p) { my $b; my $t2 = $t**2 % $p; for (1 .. $S) { if (0 == ($t2-1)%$p) { $b = powmod($c, 1 << ($S-1-$_), $p); $S = $_; last; } $t2 = $t2**2 % $p; } $R = ($R * $b) % $p; $c = $b**2 % $p; $t = ($t * $c) % $p; } $R; }   my @tests = ( (10, 13), (56, 101), (1030, 10009), (1032, 10009), (44402, 100049), (665820697, 1000000009), (881398088036, 1000000000039), );   while (@tests) { $n = shift @tests; $p = shift @tests; my $t = tonelli_shanks($n, $p); if (!$t or ($t**2 - $n) % $p) { printf "No solution for (%d, %d)\n", $n, $p; } else { printf "Roots of %d are (%d, %d) mod %d\n", $n, $t, $p-$t, $p; } }
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were 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
#FreeBASIC
FreeBASIC
Sub tokenize(cadena As String, separador As String, escape As String) Dim As Integer campo = 1 Dim As Boolean escapando = false Dim As String char Print ""; campo; " ";   For i As Integer = 1 To Len(cadena) char = Mid(cadena, i, 1) If escapando Then Print char; escapando = false Else Select Case char Case separador Print campo += 1 Print ""; campo; " "; Case escape escapando = true Case Else Print char; End Select End If Next i Print End Sub   tokenize("one^|uno||three^^^^|four^^^|^cuatro|", "|", "^") Sleep
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
#REXX
REXX
/*REXX program calculates the total area of (possibly overlapping) circles. */ parse arg box dig . /*obtain optional argument from the CL.*/ if box=='' | box==',' then box= 500 /*Not specified? Then use the default.*/ if dig=='' | dig==',' then dig= 12 /* " " " " " " */ numeric digits dig /*have enough decimal digits for points*/ data = ' 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' circles= words(data) % 3 /* ══x══ ══y══ ══radius══ */ parse var data minX minY . 1 maxX maxY . /*assign minimum & maximum values.*/ do j=1 for circles; _= j * 3 - 2 /*assign some circles with datum. */ @x.j= word(data,_); @y.j= word(data, _ + 1) @r.j= word(data,_+2); @rr.j= @r.j**2 minX= min(minX, @x.j - @r.j); maxX= max(maxX, @x.j + @r.j) minY= min(minY, @y.j - @r.j); maxY= max(maxY, @y.j + @r.j) end /*j*/ dx= (maxX-minX) / box dy= (maxY-minY) / box #= 0 /*count of sample points (so far).*/ do row=0 to box; y= minY + row*dy /*process each of the grid rows. */ do col=0 to box; x= minX + col*dx /* " " " " " column.*/ do k=1 for circles /*now process each new circle. */ if (x - @x.k)**2 + (y - @y.k)**2 <= @rr.k then do; #= # + 1; leave; end end /*k*/ end /*col*/ end /*row*/ /*stick a fork in it, we're done. */ say 'Using ' box " boxes (which have " box**2 ' points) and ' dig " decimal digits," say 'the approximate area is: ' # * dx * dy
http://rosettacode.org/wiki/Topological_sort
Topological sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon. The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on. A tool exists that extracts library dependencies. Task Write a function that will return a valid compile order of VHDL libraries from their dependencies. Assume library names are single words. Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given. Any self dependencies should be ignored. Any un-orderable dependencies should be flagged. Use the following data as an example: LIBRARY LIBRARY DEPENDENCIES ======= ==================== des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee dw01 ieee dw01 dware gtech dw02 ieee dw02 dware dw03 std synopsys dware dw03 dw02 dw01 ieee gtech dw04 dw04 ieee dw01 dware gtech dw05 dw05 ieee dware dw06 dw06 ieee dware dw07 ieee dware dware ieee dware gtech ieee gtech ramlib std ieee std_cell_lib ieee std_cell_lib synopsys Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01. C.f.   Topological sort/Extracted top item. There are two popular algorithms for topological sorting:   Kahn's 1962 topological sort [1]   depth-first search [2] [3]
#Forth
Forth
variable nodes 0 nodes ! \ linked list of nodes   : node. ( body -- ) body> >name name>string type ;   : nodeps ( body -- ) \ the word referenced by body has no (more) dependencies to resolve ['] drop over ! node. space ;   : processing ( body1 ... bodyn body -- body1 ... bodyn ) \ the word referenced by body is in the middle of resolving dependencies 2dup <> if \ unless it is a self-reference (see task description) ['] drop over ! ." (cycle: " dup node. >r 1 begin \ print the cycle dup pick dup r@ <> while space node. 1+ repeat ." ) " 2drop r> then drop ;   : >processing ( body -- body ) ['] processing over ! ;   : node ( "name" -- ) \ define node "name" and initialize it to having no dependences create ['] nodeps , \ on definition, a node has no dependencies nodes @ , lastxt nodes ! \ linked list of nodes does> ( -- ) dup @ execute ; \ perform xt associated with node   : define-nodes ( "names" <newline> -- ) \ define all the names that don't exist yet as nodes begin parse-name dup while 2dup find-name 0= if 2dup nextname node then 2drop repeat 2drop ;   : deps ( "name" "deps" <newline> -- ) \ name is after deps. Implementation: Define missing nodes, then \ define a colon definition for >in @ define-nodes >in ! ' :noname ]] >processing [[ source >in @ /string evaluate ]] nodeps ; [[ swap >body ! 0 parse 2drop ;   : all-nodes ( -- ) \ call all nodes, and they then print their dependences and themselves nodes begin @ dup while dup execute >body cell+ repeat drop ;   deps des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee deps dw01 ieee dw01 dware gtech deps dw02 ieee dw02 dware deps dw03 std synopsys dware dw03 dw02 dw01 ieee gtech deps dw04 dw04 ieee dw01 dware gtech deps dw05 dw05 ieee dware deps dw06 dw06 ieee dware deps dw07 ieee dware deps dware ieee dware deps gtech ieee gtech deps ramlib std ieee deps std_cell_lib ieee std_cell_lib deps synopsys \ to test the cycle recognition (overwrites dependences for dw1 above) deps dw01 ieee dw01 dware gtech dw04   all-nodes
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.
#Lua
Lua
-- Machine definitions local incrementer = { name = "Simple incrementer", initState = "q0", endState = "qf", blank = "B", rules = { {"q0", "1", "1", "right", "q0"}, {"q0", "B", "1", "stay", "qf"} } }   local threeStateBB = { name = "Three-state busy beaver", initState = "a", endState = "halt", blank = "0", rules = { {"a", "0", "1", "right", "b"}, {"a", "1", "1", "left", "c"}, {"b", "0", "1", "left", "a"}, {"b", "1", "1", "right", "b"}, {"c", "0", "1", "left", "b"}, {"c", "1", "1", "stay", "halt"} } }   local fiveStateBB = { name = "Five-state busy beaver", initState = "A", endState = "H", blank = "0", rules = { {"A", "0", "1", "right", "B"}, {"A", "1", "1", "left", "C"}, {"B", "0", "1", "right", "C"}, {"B", "1", "1", "right", "B"}, {"C", "0", "1", "right", "D"}, {"C", "1", "0", "left", "E"}, {"D", "0", "1", "left", "A"}, {"D", "1", "1", "left", "D"}, {"E", "0", "1", "stay", "H"}, {"E", "1", "0", "left", "A"} } }   -- Display a representation of the tape and machine state on the screen function show (state, headPos, tape) local leftEdge = 1 while tape[leftEdge - 1] do leftEdge = leftEdge - 1 end io.write(" " .. state .. "\t| ") for pos = leftEdge, #tape do if pos == headPos then io.write("[" .. tape[pos] .. "] ") else io.write(" " .. tape[pos] .. " ") end end print() end   -- Simulate a turing machine function UTM (machine, tape, countOnly) local state, headPos, counter = machine.initState, 1, 0 print("\n\n" .. machine.name) print(string.rep("=", #machine.name) .. "\n") if not countOnly then print(" State", "| Tape [head]\n---------------------") end repeat if not tape[headPos] then tape[headPos] = machine.blank end if not countOnly then show(state, headPos, tape) end for _, rule in ipairs(machine.rules) do if rule[1] == state and rule[2] == tape[headPos] then tape[headPos] = rule[3] if rule[4] == "left" then headPos = headPos - 1 end if rule[4] == "right" then headPos = headPos + 1 end state = rule[5] break end end counter = counter + 1 until state == machine.endState if countOnly then print("Steps taken: " .. counter) else show(state, headPos, tape) end end   -- Main procedure UTM(incrementer, {"1", "1", "1"}) UTM(threeStateBB, {}) UTM(fiveStateBB, {}, "countOnly")
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).
#Julia
Julia
φ(n) = sum(1 for k in 1:n if gcd(n, k) == 1)   is_prime(n) = φ(n) == n - 1   function runphitests() for n in 1:25 println(" φ($n) == $(φ(n))", is_prime(n) ? ", is prime" : "") end count = 0 for n in 1:100_000 count += is_prime(n) if n in [100, 1000, 10_000, 100_000] println("Primes up to $n: $count") end end end   runphitests()  
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
#Raku
Raku
sub swops(@a is copy) { my int $count = 0; until @a[0] == 1 { @a[ ^@a[0] ] .= reverse; ++$count; } $count }   sub topswops($n) { max (1..$n).permutations.race.map: &swops }   say "$_ {topswops $_}" for 1 .. 10;
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.
#Factor
Factor
USING: kernel math math.constants math.functions math.trig prettyprint ;   pi 4 / 45 deg>rad [ sin ] [ cos ] [ tan ] [ [ . ] compose dup compose ] tri@ 2tri   .5 [ asin ] [ acos ] [ atan ] tri [ dup rad>deg [ . ] bi@ ] tri@
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).
#Nim
Nim
import math, rdstdin, strutils, algorithm, sequtils   proc f(x: float): float = x.abs.pow(0.5) + 5 * x.pow(3)   proc ask: seq[float] = readLineFromStdin("11 numbers: ").strip.split[0..10].map(parseFloat)   var s = ask() reverse s for x in s: let result = f(x) echo x, ": ", if result > 400: "TOO LARGE!" else: $result
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).
#Objective-C
Objective-C
// // TPKA.m // RosettaCode // // Created by Alexander Alvonellos on 5/26/12. // Trabb Pardo-Knuth algorithm //   #import <Foundation/Foundation.h> double f(double x);   double f(double x) { return pow(abs(x), 0.5) + 5*(pow(x, 3)); }   int main (int argc, const char * argv[]) { @autoreleasepool { NSMutableArray *input = [[NSMutableArray alloc] initWithCapacity:0];   printf("%s", "Instructions: please enter 11 numbers.\n"); for(int i = 0; i < 11; i++) { double userInput = 0.0; printf("%s", "Please enter a number: "); scanf("%lf", &userInput); [input addObject: @(userInput)]; }   for(int i = 10; i >= 0; i--) { double x = [input[i] doubleValue]; double y = f(x); printf("f(%.2f) \t=\t", x); if(y < 400.0) { printf("%.2f\n", y); } else { printf("%s\n", "TOO LARGE"); } } } return 0; }  
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.
#Smalltalk
Smalltalk
[:repeat | expr := Stdin request:'Enter boolean expression (name variables a,b,c...):' defaultAnswer:'a|b'. ast := Parser parseExpression:expr inNameSpace:nil onError:repeat. " ensure that only boolean logic operations are inside (sandbox) " (ast messageSelectors asSet conform:[:each | #( '|' '&' 'not' 'xor:' '==>' ) includes:each]) ifFalse:repeat. ] valueWithRestart.   " extract variables from the AST as a collection (i.e. if user entered 'a & (b | x)', we get #('a' 'b' 'x') " varNames := StringCollection streamContents:[:s | ast variableNodesDo:[:each | s nextPut:each name]].   " generate code for a block (aka lambda) to evaluate it; this makes a string like: [:a :b :x | a & (b | x) ] " code := '[' , ((varNames collect:[:nm | ':',nm]) asString), ' | ' , expr , ']'.   " eval the code, to get the block " func := Parser evaluate:code.   'Truth table for %s:\n' printf:{expr} on:Stdout. '===================\n' printf:{} on:Stdout. (varNames,{' result'}) do:[:each | '|%6s' printf:{each} on:Stdout]. Stdout cr. Stdout next:(varNames size + 1)*7 put:$-. Stdout cr.   " now print with all combinations " allCombinationsDo := [:remainingVars :valuesIn :func | remainingVars isEmpty ifTrue:[ valuesIn do:[:each | '|%6s' printf:{each}on:Stdout]. '|%6s\n' printf:{ func valueWithArguments:valuesIn} on:Stdout. ] ifFalse:[ #(false true) do:[:each | allCombinationsDo value:(remainingVars from:2) value:(valuesIn copyWith:each) value:func. ]. ]. ].   allCombinationsDo value:varNames value:#() value:func
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
#Wren
Wren
import "/dynamic" for Enum import "/math" for Int import "/str" for Char import "/fmt" for Fmt   var Direction = Enum.create("Direction", ["right", "up", "left", "down"])   class Ulam { static generate(n, i, c) { if (n <= 1) Fiber.abort ("'n' must be more than 1.") var s = List.filled(n, null) for (i in 0...n) s[i] = List.filled(n, "") var dir = Direction.right var y = (n/2).floor var x = (n % 2 == 0) ? y - 1 : y // shift left for even n's for (j in i..n * n - 1 + i) { s[y][x] = Int.isPrime(j) ? (Char.isDigit(c) ? Fmt.d(4, j) : "  %(c) ") : " ---" if (dir == Direction.right) { if (x <= n - 1 && s[y - 1][x] == "" && j > i) dir = Direction.up } else if (dir == Direction.up) { if (s[y][x - 1] == "") dir = Direction.left } else if (dir == Direction.left) { if (x == 0 || s[y + 1][x] == "") dir = Direction.down } else if (dir == Direction.down) { if (s[y][x + 1] == "") dir = Direction.right }   if (dir == Direction.right) { x = x + 1 } else if (dir == Direction.up) { y = y - 1 } else if (dir == Direction.left) { x = x - 1 } else if (dir == Direction.down) { y = y + 1 } }   for (row in s) Fmt.print("$s", row) System.print() } }   Ulam.generate(9, 1, "0") // with digits Ulam.generate(9, 1, "*") // with *
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.]
#PARI.2FGP
PARI/GP
left(n)={ my(v=[2,3,5,7],u,t=1,out=0); for(i=1,n, t*=10; u=[]; for(j=1,#v, forstep(a=t,t*9,t, if(isprime(a+v[j]),u=concat(u,a+v[j])) ) ); out=v[#v]; v=vecsort(u) ); out }; right(n)={ my(v=[2,3,5,7],u,out=0); for(i=1,n, u=[]; for(j=1,#v, forstep(a=1,9,[2,4], if(isprime(10*v[j]+a),u=concat(u,10*v[j]+a)) ) ); out=v[#v]; v=u ); out }; [left(6),right(6)]
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.
#Common_Lisp
Common Lisp
(defun preorder (node f) (when node (funcall f (first node)) (preorder (second node) f) (preorder (third node) f)))   (defun inorder (node f) (when node (inorder (second node) f) (funcall f (first node)) (inorder (third node) f)))   (defun postorder (node f) (when node (postorder (second node) f) (postorder (third node) f) (funcall f (first node))))   (defun level-order (node f) (loop with level = (list node) while level do (setf level (loop for node in level when node do (funcall f (first node)) and collect (second node) and collect (third node)))))   (defparameter *tree* '(1 (2 (4 (7)) (5)) (3 (6 (8) (9)))))   (defun show (traversal-function) (format t "~&~(~A~):~12,0T" traversal-function) (funcall traversal-function *tree* (lambda (value) (format t " ~A" value))))   (map nil #'show '(preorder inorder postorder level-order))
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
#AutoHotkey
AutoHotkey
string := "Hello,How,Are,You,Today" stringsplit, string, string, `, loop, % string0 { msgbox % string%A_Index% }
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
#AWK
AWK
BEGIN { s = "Hello,How,Are,You,Today" split(s, arr, ",") for(i=1; i < length(arr); i++) { printf arr[i] "." } print }
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Arturo
Arturo
benchmark [ print "starting function" pause 2000 print "function ended" ]
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#AutoHotkey
AutoHotkey
MsgBox % time("fx") Return   fx() { Sleep, 1000 }   time(function, parameter=0) { SetBatchLines -1 ; don't sleep for other green threads StartTime := A_TickCount %function%(parameter) Return ElapsedTime := A_TickCount - StartTime . " milliseconds" }
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
#Clojure
Clojure
(use '[clojure.contrib.seq-utils :only (group-by)])   (defstruct employee :Name :ID :Salary :Department)   (def 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)) (map #(apply (partial struct employee) %))))     (doseq [[dep emps] (group-by :Department data)] (println "Department:" dep) (doseq [e (take 3 (reverse (sort-by :Salary emps)))] (println e)))  
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedia tic-tac-toe.
#AutoHotkey
AutoHotkey
Gui, Add, Button, x12 y12 w30 h30 vB1 gButtonHandler, Gui, Add, Button, x52 y12 w30 h30 vB2 gButtonHandler, Gui, Add, Button, x92 y12 w30 h30 vB3 gButtonHandler, Gui, Add, Button, x12 y52 w30 h30 vB4 gButtonHandler, Gui, Add, Button, x52 y52 w30 h30 vB5 gButtonHandler, Gui, Add, Button, x92 y52 w30 h30 vB6 gButtonHandler, Gui, Add, Button, x12 y92 w30 h30 vB7 gButtonHandler, Gui, Add, Button, x52 y92 w30 h30 vB8 gButtonHandler, Gui, Add, Button, x92 y92 w30 h30 vB9 gButtonHandler, ; Generated using SmartGUI Creator 4.0 Gui, Show, x127 y87 h150 w141, Tic-Tac-Toe Winning_Moves := "123,456,789,147,258,369,159,357" Return   ButtonHandler: ; Fired whenever the user clicks on an enabled button Go(A_GuiControl,"X") GoSub MyMove Return   MyMove: ; Loops through winning moves. First attempts to win, then to block, then a random move Went=0 Loop, parse, Winning_Moves,`, { Current_Set := A_LoopField X:=O:=0 Loop, parse, Current_Set { GuiControlGet, Char,,Button%A_LoopField% If ( Char = "O" ) O++ If ( Char = "X" ) X++ } If ( O = 2 and X = 0 ) or ( X = 2 and O = 0 ){ Finish_Line(Current_Set) Went = 1 Break ; out of the Winning_Moves Loop to ensure the computer goes only once } } If (!Went) GoSub RandomMove Return   Go(Control,chr){ GuiControl,,%Control%, %chr% GuiControl,Disable,%Control% GoSub, CheckWin }   CheckWin: Loop, parse, Winning_Moves,`, { Current_Set := A_LoopField X:=O:=0 Loop, parse, Current_Set { GuiControlGet, Char,,Button%A_LoopField% If ( Char = "O" ) O++ If ( Char = "X" ) X++ } If ( O = 3 ){ Msgbox O Wins! GoSub DisableAll Break } If ( X = 3 ){ MsgBox X Wins! GoSub DisableAll Break } } return   DisableAll: Loop, 9 GuiControl, Disable, Button%A_Index% return   Finish_Line(Set){ ; Finish_Line is called when a line exists with 2 of the same character. It goes in the remaining spot, thereby blocking or winning. Loop, parse, set { GuiControlGet, IsEnabled, Enabled, Button%A_LoopField% Control=Button%A_LoopField% If IsEnabled Go(Control,"O") } }   RandomMove: Loop{ Random, rnd, 1, 9 GuiControlGet, IsEnabled, Enabled, Button%rnd% If IsEnabled { Control=Button%rnd% Go(Control,"O") Break } } return   GuiClose: ExitApp  
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#AWK
AWK
$ awk 'func hanoi(n,f,t,v){if(n>0){hanoi(n-1,f,v,t);print(f,"->",t);hanoi(n-1,v,t,f)}} BEGIN{hanoi(4,"left","middle","right")}'
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
#Factor
Factor
USING: io kernel math math.parser sequences ;   : thue-morse ( seq n -- seq' ) [ [ ] [ [ 1 bitxor ] map ] bi append ] times ;   : print-tm ( seq -- ) [ number>string ] map "" join print ;   7 <iota> [ { 0 } swap thue-morse print-tm ] each
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
#Fortran
Fortran
program thue_morse implicit none logical :: f(32) = .false. integer :: n = 1   do write(*,*) f(1:n) if (n > size(f)/2) exit f(n+1:2*n) = .not. f(1:n) n = n * 2 end do   end program 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
#Phix
Phix
with javascript_semantics include mpfr.e function ts(string ns, ps) mpz n = mpz_init(ns), p = mpz_init(ps), t = mpz_init(), r = mpz_init(), pm1 = mpz_init(), pm2 = mpz_init() mpz_sub_ui(pm1,p,1) -- pm1 = p-1 mpz_fdiv_q_2exp(pm2,pm1,1) -- pm2 = pm1/2 mpz_powm(t,n,pm2,p) -- t = mod(n^pm2,p) if mpz_cmp_si(t,1)!=0 then return "No solution exists" end if mpz q = mpz_init_set(pm1) integer ss = 0 while mpz_even(q) do ss += 1 mpz_fdiv_q_2exp(q,q,1) -- q/=2 end while if ss=1 then mpz_add_ui(t,p,1) mpz_fdiv_q_2exp(t,t,2) mpz_powm(r,n,t,p) -- r = mod(n^((p+1)/4),p) else mpz z = mpz_init(2) while true do mpz_powm(t,z,pm2,p) -- t = mod(z^pm2,p) if mpz_cmp(t,pm1)=0 then exit end if mpz_add_ui(z,z,1) -- z+= 1 end while mpz {b,c,zz} = mpz_inits(3) mpz_powm(c,z,q,p) -- c = mod(z^q,p) mpz_add_ui(t,q,1) mpz_fdiv_q_2exp(t,t,1) mpz_powm(r,n,t,p) -- r = mod(n^((q+1)/2),p) mpz_powm(t,n,q,p) -- t = mod(n^q,p) integer m = ss while mpz_cmp_si(t,1) do -- t!=1 integer i = 0 mpz_set(zz,t) while mpz_cmp_si(zz,1)!=0 and i<m-1 do mpz_powm_ui(zz,zz,2,p) -- zz = mod(zz^2,p) i += 1 end while mpz_set(b,c) integer e = m-i-1 while e>0 do mpz_powm_ui(b,b,2,p) -- b = mod(b^2,p) e -= 1 end while mpz_mul(r,r,b) mpz_mod(r,r,p) -- r = mod(r*b,p) mpz_powm_ui(c,b,2,p) -- c = mod(b^2,p) mpz_mul(t,t,c) mpz_mod(t,t,p) -- t = mod(t*c,p) m = i end while end if mpz_sub(p,p,r) return mpz_get_str(r)&" and "&mpz_get_str(p) end function constant tests = {{"10","13"}, {"56","101"}, {"1030","10009"}, {"1032","10009"}, {"44402","100049"}, {"665820697","1000000009"}, {"881398088036","1000000000039"}, {"41660815127637347468140745042827704103445750172002", sprintf("1%s577",repeat('0',47))}} -- 10^50+577 for i=1 to length(tests) do string {p1,p2} = tests[i] printf(1,"For n = %s and p = %s, %s\n",{p1,p2,ts(p1,p2)}) end for
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were separated by the separators, become the elements of the output list. Empty fields should be preserved, even at the start and end. Rules for escaping: "Escaped" means preceded by an occurrence of the escape character that is not already escaped itself. When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special). Each occurrence of the escape character that was used to escape something, should not become part of the output. Test case Demonstrate that your function satisfies the following test-case: Input Output string: one^|uno||three^^^^|four^^^|^cuatro| separator character: | escape character: ^ one|uno three^^ four^|cuatro (Print the output list in any format you like, as long as it is it easy to see what the fields are.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Go
Go
package main   import ( "errors" "fmt" )   func TokenizeString(s string, sep, escape rune) (tokens []string, err error) { var runes []rune inEscape := false for _, r := range s { switch { case inEscape: inEscape = false fallthrough default: runes = append(runes, r) case r == escape: inEscape = true case r == sep: tokens = append(tokens, string(runes)) runes = runes[:0] } } tokens = append(tokens, string(runes)) if inEscape { err = errors.New("invalid terminal escape") } return tokens, err }   func main() { const sample = "one^|uno||three^^^^|four^^^|^cuatro|" const separator = '|' const escape = '^'   fmt.Printf("Input:  %q\n", sample) tokens, err := TokenizeString(sample, separator, escape) if err != nil { fmt.Println("error:", err) } else { fmt.Printf("Tokens: %q\n", tokens) } }
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
#Ruby
Ruby
circles = [ [ 1.6417233788, 1.6121789534, 0.0848270516], [-1.4944608174, 1.2077959613, 1.1039549836], [ 0.6110294452, -0.6907087527, 0.9089162485], [ 0.3844862411, 0.2923344616, 0.2375743054], [-0.2495892950, -0.3832854473, 1.0845181219], [ 1.7813504266, 1.6178237031, 0.8162655711], [-0.1985249206, -0.8343333301, 0.0538864941], [-1.7011985145, -0.1263820964, 0.4776976918], [-0.4319462812, 1.4104420482, 0.7886291537], [ 0.2178372997, -0.9499557344, 0.0357871187], [-0.6294854565, -1.3078893852, 0.7653357688], [ 1.7952608455, 0.6281269104, 0.2727652452], [ 1.4168575317, 1.0683357171, 1.1016025378], [ 1.4637371396, 0.9463877418, 1.1846214562], [-0.5263668798, 1.7315156631, 1.4428514068], [-1.2197352481, 0.9144146579, 1.0727263474], [-0.1389358881, 0.1092805780, 0.7350208828], [ 1.5293954595, 0.0030278255, 1.2472867347], [-0.5258728625, 1.3782633069, 1.3495508831], [-0.1403562064, 0.2437382535, 1.3804956588], [ 0.8055826339, -0.0482092025, 0.3327165165], [-0.6311979224, 0.7184578971, 0.2491045282], [ 1.4685857879, -0.8347049536, 1.3670667538], [-0.6855727502, 1.6465021616, 1.0593087096], [ 0.0152957411, 0.0638919221, 0.9771215985], ]   def minmax_circle(circles) xmin = circles.map {|xc, yc, radius| xc - radius}.min xmax = circles.map {|xc, yc, radius| xc + radius}.max ymin = circles.map {|xc, yc, radius| yc - radius}.min ymax = circles.map {|xc, yc, radius| yc + radius}.max [xmin, xmax, ymin, ymax] end   # remove internal circle def select_circle(circles) circles = circles.sort_by{|cx,cy,r| -r} size = circles.size select = [*0...size] for i in 0...size-1 xi,yi,ri = circles[i].to_a for j in i+1...size xj,yj,rj = circles[j].to_a select -= [j] if (xi-xj)**2 + (yi-yj)**2 <= (ri-rj)**2 end end circles.values_at(*select) end circles = select_circle(circles)
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]
#Fortran
Fortran
SUBROUTINE TSORT(NL,ND,IDEP,IORD,IPOS,NO) IMPLICIT NONE INTEGER NL,ND,NO,IDEP(ND,2),IORD(NL),IPOS(NL),I,J,K,IL,IR,IPL,IPR DO 10 I=1,NL IORD(I)=I 10 IPOS(I)=I K=1 20 J=K K=NL+1 DO 30 I=1,ND IL=IDEP(I,1) IR=IDEP(I,2) IPL=IPOS(IL) IPR=IPOS(IR) IF(IL.EQ.IR .OR. IPL.GE.K .OR. IPL.LT.J .OR. IPR.LT.J) GO TO 30 K=K-1 IPOS(IORD(K))=IPL IPOS(IL)=K IORD(IPL)=IORD(K) IORD(K)=IL 30 CONTINUE IF(K.GT.J) GO TO 20 NO=J-1 END
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
  left = 1; right = -1; stay = 0; cmp[s_] := ToExpression[StringSplit[s, ","]]; utm[rules_, initial_, head_] := Module[{tape = initial, rh = head, n = 1}, Clear[nxt]; nxt[state_, field_] := nxt[state, field] = Position[rules, {rules[[state, 5]], field, _, _, _}][[1, 1]]; n = Position[rules, {rules[[n, 1]], BitGet[tape, rh], _, _, _}][[1,1]]; While[rules[[n, 4]] != 0, If[rules[[n, 3]] != BitGet[tape, rh], If[rules[[n, 3]] == 1, tape = BitSet[tape, rh], tape = BitClear[tape, rh]]]; rh = rh + rules[[n, 4]]; If[rh < 0, rh = 0; tape = 2*tape]; n = nxt[n, BitGet[tape, rh]]; ]; {tape, rh} ]; ];
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).
#Kotlin
Kotlin
// Version 1.3.21   fun totient(n: Int): Int { var tot = n var nn = n var i = 2 while (i * i <= nn) { if (nn % i == 0) { while (nn % i == 0) nn /= i tot -= tot / i } if (i == 2) i = 1 i += 2 } if (nn > 1) tot -= tot / nn return tot }   fun main() { println(" n phi prime") println("---------------") var count = 0 for (n in 1..25) { val tot = totient(n) val isPrime = n - 1 == tot if (isPrime) count++ System.out.printf("%2d  %2d  %b\n", n, tot, isPrime) } println("\nNumber of primes up to 25 = $count") for (n in 26..100_000) { val tot = totient(n) if (tot == n-1) count++ if (n == 100 || n == 1000 || n % 10_000 == 0) { System.out.printf("\nNumber of primes up to %-6d = %d\n", 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
#REXX
REXX
/*REXX program generates N decks of numbered cards and finds the maximum "swops". */ parse arg things .; if things=='' then things= 10   do n=1 for things; #= decks(n, n) /*create a (things) number of "decks". */ mx= n\==1 /*handle the case of a one-card deck.*/ do i=1 for #; p= swops(!.i) /*compute the SWOPS for this iteration.*/ if p>mx then mx= p /*This a new maximum? Use a new max. */ end /*i*/ say '──────── maximum swops for a deck of' right(n,2) ' cards is' right(mx,4) end /*n*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ decks: procedure expose !.; parse arg x,y,,$ @. /* X things taken Y at a time. */ #= 0; call .decks 1 /* [↑] initialize $ & @. to null.*/ return # /*return number of permutations (decks)*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ .decks: procedure expose !. @. x y $ #; parse arg ? if ?>y then do; [email protected]; do j=2 for y-1; _= _ @.j; end /*j*/; #= #+1;  !.#=_ end else do; qm= ? - 1 if ?==1 then qs= 2 /*don't use 1-swops that start with 1 */ else if @.1==? then qs=2 /*skip the 1-swops: 3 x 1 x ···*/ else qs=1 do q=qs to x /*build the permutations recursively. */ do k=1 for qm; if @.k==q then iterate q end /*k*/ @.?=q ; call .decks ? + 1 end /*q*/ end return /*──────────────────────────────────────────────────────────────────────────────────────*/ swops: parse arg z; do u=1; parse var z t .; if \datatype(t, 'W') then t= x2d(t) if word(z, t)==1 then return u /*found unity at T. */ do h=10 to things; if pos(h, z)==0 then iterate z= changestr(h, z, d2x(h) ) /* [↑] any H's in Z?*/ end /*h*/ z= reverse( subword(z, 1, t) ) subword(z, t + 1) end /*u*/
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.
#Fantom
Fantom
  class Main { public static Void main () { Float r := Float.pi / 4 echo (r.sin) echo (r.cos) echo (r.tan) echo (r.asin) echo (r.acos) echo (r.atan) // and from degrees echo (45.0f.toRadians.sin) echo (45.0f.toRadians.cos) echo (45.0f.toRadians.tan) echo (45.0f.toRadians.asin) echo (45.0f.toRadians.acos) echo (45.0f.toRadians.atan) } }  
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm. From the wikipedia entry: ask for 11 numbers to be read into a sequence S reverse sequence S for each item in sequence S result := call a function to do an operation if result overflows alert user else print result The task is to implement the algorithm: Use the function:     f ( x ) = | x | 0.5 + 5 x 3 {\displaystyle f(x)=|x|^{0.5}+5x^{3}} The overflow condition is an answer of greater than 400. The 'user alert' should not stop processing of other items of the sequence. Print a prompt before accepting eleven, textual, numeric inputs. You may optionally print the item as well as its associated result, but the results must be in reverse order of input. The sequence   S   may be 'implied' and so not shown explicitly. Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#OCaml
OCaml
let f x = sqrt x +. 5.0 *. (x ** 3.0) let p x = x < 400.0   let () = print_endline "Please enter 11 Numbers:"; let lst = Array.to_list (Array.init 11 (fun _ -> read_float ())) in List.iter (fun x -> let res = f x in if p res then Printf.printf "f(%g) = %g\n%!" x res else Printf.eprintf "f(%g) :: Overflow\n%!" x ) (List.rev lst)
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).
#PARI.2FGP
PARI/GP
{ print("11 numbers: "); v=vector(11, n, eval(input())); v=apply(x->x=sqrt(abs(x))+5*x^3;if(x>400,"overflow",x), v); vector(11, i, v[12-i]) }
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.
#Tcl
Tcl
package require Tcl 8.5   puts -nonewline "Enter a boolean expression: " flush stdout set exp [gets stdin]   # Generate the nested loops as the body of a lambda term. set vars [lsort -unique [regexp -inline -all {\$\w+} $exp]] set cmd [list format [string repeat "%s\t" [llength $vars]]%s] append cmd " {*}\[[list subst $vars]\] \[[list expr $exp]\]" set cmd "puts \[$cmd\]" foreach v [lreverse $vars] { set cmd [list foreach [string range $v 1 end] {0 1} $cmd] }   puts [join $vars \t]\tResult apply [list {} $cmd]
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
#XPL0
XPL0
func IsPrime(N); \Return 'true' if N is prime int N, I; [if N <= 2 then return N = 2; if (N&1) = 0 then \even >2\ return false; for I:= 3 to sqrt(N) do [if rem(N/I) = 0 then return false; I:= I+1; ]; return true; ];   int N, X, Y, Len, Dir, DX, DY, Side, Step; [SetVid($13); X:= 320/2; Y:= 200/2; N:= 1; Len:= 1; Dir:= 0; \Rt, Up, Lt, Dn DX:= [1, 0, -1, 0]; DY:= [0, -1, 0, 1]; repeat for Side:= 1 to 2 do [for Step:= 1 to Len do [if IsPrime(N) then Point(X, Y, $F); N:= N+1; X:= X + DX(Dir); \move in current direction Y:= Y + DY(Dir); ]; Dir:= (Dir+1) & 3; \set next direction ]; Len:= Len+1; until Y = 0; \reached top ]
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.]
#Perl
Perl
use ntheory ":all"; sub isltrunc { my $n = shift; return (is_prime($n) && $n !~ /0/ && ($n < 10 || isltrunc(substr($n,1)))); } sub isrtrunc { my $n = shift; return (is_prime($n) && $n !~ /0/ && ($n < 10 || isrtrunc(substr($n,0,-1)))); } for (reverse @{primes(1e6)}) { if (isltrunc($_)) { print "ltrunc: $_\n"; last; } } for (reverse @{primes(1e6)}) { if (isrtrunc($_)) { print "rtrunc: $_\n"; last; } }
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.
#Coq
Coq
Require Import Utf8. Require Import List.   Unset Elimination Schemes.   (* Rose tree, with numbers on nodes *) Inductive tree := Tree { value : nat ; children : list tree }.   Fixpoint height (t: tree) : nat := 1 + fold_left (λ n t, max n (height t)) (children t) 0.   Example leaf n : tree := {| value := n ; children := nil |}.   Example t2 : tree := {| value := 2 ; children := {| value := 4 ; children := leaf 7 :: nil |} :: leaf 5 :: nil |}.   Example t3 : tree := {| value := 3 ; children := {| value := 6 ; children := leaf 8 :: leaf 9 :: nil |} :: nil |}.   Example t9 : tree := {| value := 1 ; children := t2 :: t3 :: nil |}.   Fixpoint preorder (t: tree) : list nat := let '{| value := n ; children := c |} := t in n :: flat_map preorder c.   Fixpoint inorder (t: tree) : list nat := let '{| value := n ; children := c |} := t in match c with | nil => n :: nil | ℓ :: r => inorder ℓ ++ n :: flat_map inorder r end.   Fixpoint postorder (t: tree) : list nat := let '{| value := n ; children := c |} := t in flat_map postorder c ++ n :: nil.   (* Auxiliary function for levelorder, which operates on forests *) (* Since the recursion is tricky, it relies on a fuel parameter which obviously decreases. *) Fixpoint levelorder_forest (fuel: nat) (f: list tree) : list nat:= match fuel with | O => nil | S fuel' => let '(p, f) := fold_right (λ t r, let '(x, f) := r in (value t :: x, children t ++ f) ) (nil, nil) f in p ++ levelorder_forest fuel' f end.   Definition levelorder (t: tree) : list nat := levelorder_forest (height t) (t :: nil).   Compute preorder t9. Compute inorder t9. Compute postorder t9. Compute levelorder t9.  
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
#BASIC
BASIC
100 T$ = "HELLO,HOW,ARE,YOU,TODAY" 110 GOSUB 200"TOKENIZE 120 FOR I = 1 TO N 130 PRINT A$(I) "." ; 140 NEXT 150 PRINT 160 END   200 IF N = 0 THEN DIM A$(256) 210 N = 1 220 A$(N) = " 230 FOR TI = 1 TO LEN(T$) 240 C$ = MID$(T$, TI, 1) 250 T = C$ = "," 260 IF T THEN C$ = " 270 N = N + T 280 IF T THEN A$(N) = C$ 290 A$(N) = A$(N) + C$ 300 NEXT TI 310 RETURN
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
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion call :tokenize %1 res echo %res% goto :eof   :tokenize set str=%~1 :loop for %%i in (%str%) do set %2=!%2!.%%i set %2=!%2:~1! goto :eof
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#BaCon
BaCon
' Time a function SUB timed() SLEEP 7000 END SUB   st = TIMER timed() et = TIMER PRINT st, ", ", et
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#BASIC
BASIC
DIM timestart AS SINGLE, timedone AS SINGLE, timeelapsed AS SINGLE   timestart = TIMER SLEEP 1 'code or function to execute goes here timedone = TIMER   'midnight check: IF timedone < timestart THEN timedone = timedone + 86400 timeelapsed = timedone - timestart
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
#Common_Lisp
Common Lisp
(defun top-n-by-group (n data value-key group-key predicate &key (group-test 'eql)) (let ((not-pred (complement predicate)) (group-data (make-hash-table :test group-test))) (labels ((value (datum) (funcall value-key datum)) (insert (x list) (merge 'list (list x) list not-pred :key #'value)) (entry (group) "Return the entry for the group, creating it if necessary. An entry is a list whose first element is k, the number of items currently associated with the group (out of n total), and whose second element is the list of the k current top items for the group." (multiple-value-bind (entry presentp) (gethash group group-data) (if presentp entry (setf (gethash group group-data) (list 0 '()))))) (update-entry (entry datum) "Update the entry using datum. If there are already n items associated with the entry, then when datum's value is greater than the current least item, data is merged into the items, and the list (minus the first element) is stored in entry. Otherwise, if there are fewer than n items in the entry, datum is merged in, and the entry's k is increased by 1." (if (= n (first entry)) (when (funcall predicate (value datum) (value (first (second entry)))) (setf (second entry) (cdr (insert datum (second entry))))) (setf (first entry) (1+ (first entry)) (second entry) (insert datum (second entry)))))) (dolist (datum data group-data) (update-entry (entry (funcall group-key datum)) datum)))))
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedia tic-tac-toe.
#AWK
AWK
  # syntax: GAWK -f TIC-TAC-TOE.AWK BEGIN { move[12] = "3 7 4 6 8"; move[13] = "2 8 6 4 7"; move[14] = "7 3 2 8 6" move[16] = "8 2 3 7 4"; move[17] = "4 6 8 2 3"; move[18] = "6 4 7 3 2" move[19] = "8 2 3 7 4"; move[23] = "1 9 6 4 8"; move[24] = "1 9 3 7 8" move[25] = "8 3 7 4 0"; move[26] = "3 7 1 9 8"; move[27] = "6 4 1 9 8" move[28] = "1 9 7 3 4"; move[29] = "4 6 3 7 8"; move[35] = "7 4 6 8 2" move[45] = "6 7 3 2 0"; move[56] = "4 7 3 2 8"; move[57] = "3 2 8 4 6" move[58] = "2 3 7 4 6"; move[59] = "3 2 8 4 6" split("7 4 1 8 5 2 9 6 3",rotate) n = split("253 280 457 254 257 350 452 453 570 590",special) i = 0 while (i < 9) { s[++i] = " " } print("") print("You move first, use the keypad:") board = "\n7 * 8 * 9\n*********\n4 * 5 * 6\n*********\n1 * 2 * 3\n\n? " printf(board) } state < 7 { x = $0 if (s[x] != " ") { printf("? ") next } s[x] = "X" ++state print("") if (state > 1) { for (i=0; i<r; ++i) { x = rotate[x] } } } state == 1 { for (r=0; x>2 && x!=5; ++r) { x = rotate[x] } k = x if (x == 5) { d = 1 } else { d = 5 } } state == 2 { c = 5.5 * (k + x) - 4.5 * abs(k - x) split(move[c],t) d = t[1] e = t[2] f = t[3] g = t[4] h = t[5] } state == 3 { k = x / 2. c = c * 10 d = f if (abs(c-350) == 100) { if (x != 9) { d = 10 - x } if (int(k) == k) { g = f } h = 10 - g if (x+0 == e+0) { h = g g = 9 } } else if (x+0 != e+0) { d = e state = 6 } } state == 4 { if (x+0 == g+0) { d = h } else { d = g state = 6 } x = 6 for (i=1; i<=n; ++i) { b = special[i] if (b == 254) { x = 4 } if (k+0 == abs(b-c-k)) { state = x } } } state < 7 { if (state != 5) { for (i=0; i<4-r; ++i) { d = rotate[d] } s[d] = "O" } for (b=7; b>0; b-=5) { printf("%s * %s * %s\n",s[b++],s[b++],s[b]) if (b > 3) { print("*********") } } print("") } state < 5 { printf("? ") } state == 5 { printf("tie game") state = 7 } state == 6 { printf("you lost") state = 7 } state == 7 { printf(", play again? ") ++state next } state == 8 { if ($1 !~ /^[yY]$/) { exit(0) } i = 0 while (i < 9) { s[++i] = " " } printf(board) state = 0 } function abs(x) { if (x >= 0) { return x } else { return -x } }  
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#BASIC
BASIC
SUB move (n AS Integer, fromPeg AS Integer, toPeg AS Integer, viaPeg AS Integer) IF n>0 THEN move n-1, fromPeg, viaPeg, toPeg PRINT "Move disk from "; fromPeg; " to "; toPeg move n-1, viaPeg, toPeg, fromPeg END IF END SUB   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
#FreeBASIC
FreeBASIC
  Dim As String tm = "0"   Function Thue_Morse(s As String) As String Dim As String k = "" For i As Integer = 1 To Len(s) If Mid(s, i, 1) = "1" Then k += "0" Else k += "1" End If Next i Thue_Morse = s + k End Function   Print tm For j As Integer = 1 To 7 tm = Thue_Morse(tm) Print tm Next j 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
#F.C5.8Drmul.C3.A6
Fōrmulæ
// prints the first few members of the Thue-Morse sequence   package main   import ( "fmt" "bytes" )   // sets tmBuffer to the next member of the Thue-Morse sequence // tmBuffer must contain a valid Thue-Morse sequence member before the call func nextTMSequenceMember( tmBuffer * bytes.Buffer ) { // "flip" the bytes, adding them to the buffer for b, currLength, currBytes := 0, tmBuffer.Len(), tmBuffer.Bytes() ; b < currLength; b ++ { if currBytes[ b ] == '1' { tmBuffer.WriteByte( '0' ) } else { tmBuffer.WriteByte( '1' ) } } }   func main() { var tmBuffer bytes.Buffer // initial sequence member is "0" tmBuffer.WriteByte( '0' ) fmt.Println( tmBuffer.String() ) for i := 2; i <= 7; i ++ { nextTMSequenceMember( & tmBuffer ) fmt.Println( tmBuffer.String() ) } }
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
#PicoLisp
PicoLisp
# from @lib/rsa.l (de **Mod (X Y N) (let M 1 (loop (when (bit? 1 Y) (setq M (% (* M X) N)) ) (T (=0 (setq Y (>> 1 Y))) M ) (setq X (% (* X X) N)) ) ) ) (de legendre (N P) (**Mod N (/ (dec P) 2) P) ) (de ts (N P) (and (=1 (legendre N P)) (let (Q (dec P) S 0 Z 0 C 0 R 0 D 0 M 0 B 0 I 0 ) (until (bit? 1 Q) (setq Q (>> 1 Q)) (inc 'S) ) (if (=1 S) (list (setq @@ (**Mod N (/ (inc P) 4) P)) (- P @@) ) (setq Z 2) (until (= (legendre Z P) (dec P)) (inc 'Z) ) (setq C (**Mod Z Q P) R (**Mod N (/ (inc Q) 2) P) D (**Mod N Q P) M S ) (until (=1 D) (zero I) (for (Z D (and (<> Z 1) (< I (dec M))) (setq Z (% (* Z Z) P)) ) (inc 'I) ) (setq B C) (for (Z (- M I 1) (> Z 0) (dec Z) ) (setq B (% (* B B) P)) ) (setq R (% (* R B) P) C (% (* B B) P) D (% (* D C) P) M I ) ) (list R (- P R)) ) ) ) )   (println (ts 10 13)) (println (ts 56 101)) (println (ts 1030 10009)) (println (ts 1032 10009)) (println (ts 44402 100049)) (println (ts 665820697 1000000009)) (println (ts 881398088036 1000000000039)) (println (ts 41660815127637347468140745042827704103445750172002 (+ (** 10 50) 577)))
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
#Python
Python
def legendre(a, p): return pow(a, (p - 1) // 2, p)   def tonelli(n, p): assert legendre(n, p) == 1, "not a square (mod p)" q = p - 1 s = 0 while q % 2 == 0: q //= 2 s += 1 if s == 1: return pow(n, (p + 1) // 4, p) for z in range(2, p): if p - 1 == legendre(z, p): break c = pow(z, q, p) r = pow(n, (q + 1) // 2, p) t = pow(n, q, p) m = s t2 = 0 while (t - 1) % p != 0: t2 = (t * t) % p for i in range(1, m): if (t2 - 1) % p == 0: break t2 = (t2 * t2) % p b = pow(c, 1 << (m - i - 1), p) r = (r * b) % p c = (b * b) % p t = (t * c) % p m = i return r   if __name__ == '__main__': ttest = [(10, 13), (56, 101), (1030, 10009), (44402, 100049), (665820697, 1000000009), (881398088036, 1000000000039), (41660815127637347468140745042827704103445750172002, 10**50 + 577)] for n, p in ttest: r = tonelli(n, p) assert (r * r - n) % p == 0 print("n = %d p = %d" % (n, p)) print("\t roots : %d %d" % (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
#Haskell
Haskell
splitEsc :: (Foldable t1, Eq t) => t -> t -> t1 t -> [[t]] splitEsc sep esc = reverse . map reverse . snd . foldl process (0, [[]]) where process (st, r:rs) ch | st == 0 && ch == esc = (1, r:rs) | st == 0 && ch == sep = (0, []:r:rs) | st == 1 && sep == esc && ch /= sep = (0, [ch]:r:rs) | otherwise = (0, (ch:r):rs)
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
#Tcl
Tcl
set circles { 1.6417233788 1.6121789534 0.0848270516 -1.4944608174 1.2077959613 1.1039549836 0.6110294452 -0.6907087527 0.9089162485 0.3844862411 0.2923344616 0.2375743054 -0.2495892950 -0.3832854473 1.0845181219 1.7813504266 1.6178237031 0.8162655711 -0.1985249206 -0.8343333301 0.0538864941 -1.7011985145 -0.1263820964 0.4776976918 -0.4319462812 1.4104420482 0.7886291537 0.2178372997 -0.9499557344 0.0357871187 -0.6294854565 -1.3078893852 0.7653357688 1.7952608455 0.6281269104 0.2727652452 1.4168575317 1.0683357171 1.1016025378 1.4637371396 0.9463877418 1.1846214562 -0.5263668798 1.7315156631 1.4428514068 -1.2197352481 0.9144146579 1.0727263474 -0.1389358881 0.1092805780 0.7350208828 1.5293954595 0.0030278255 1.2472867347 -0.5258728625 1.3782633069 1.3495508831 -0.1403562064 0.2437382535 1.3804956588 0.8055826339 -0.0482092025 0.3327165165 -0.6311979224 0.7184578971 0.2491045282 1.4685857879 -0.8347049536 1.3670667538 -0.6855727502 1.6465021616 1.0593087096 0.0152957411 0.0638919221 0.9771215985 }   proc init {} { upvar 1 circles circles set xMin [set yMin inf] set xMax [set yMax -inf] set i -1 foreach {xc yc rad} $circles { set xMin [expr {min($xMin, $xc-$rad)}] set xMax [expr {max($xMax, $xc+$rad)}] set yMin [expr {min($yMin, $yc-$rad)}] set yMax [expr {max($yMax, $yc+$rad)}] lset circles [incr i 3] [expr {$rad**2}] } return [list $xMin $xMax $yMin $yMax] }   proc sampleGrid {circles steps} { lassign [init] xMin xMax yMin yMax set dx [expr {($xMax-$xMin)/$steps}] set dy [expr {($yMax-$yMin)/$steps}] set n 0 for {set i 0} {$i < $steps} {incr i} { set x [expr {$xMin + $i * $dx}] for {set j 0} {$j < $steps} {incr j} { set y [expr {$yMin + $j * $dy}] foreach {xc yc rad2} $circles { if {($x-$xc)**2 + ($y-$yc)**2 <= $rad2} { incr n break } } } } return [expr {$dx * $dy * $n}] }   proc sampleMC {circles samples} { lassign [init] xMin xMax yMin yMax set n 0 for {set i 0} {$i < $samples} {incr i} { set x [expr {$xMin+rand()*($xMax-$xMin)}] set y [expr {$yMin+rand()*($yMax-$yMin)}] foreach {xc yc rad2} $circles { if {($x-$xc)**2 + ($y-$yc)**2 <= $rad2} { incr n break } } } return [expr {($xMax-$xMin) * ($yMax-$yMin) * $n / $samples}] }   proc samplePerturb {circles steps votes} { lassign [init] xMin xMax yMin yMax set dx [expr {($xMax-$xMin)/$steps}] set dy [expr {($yMax-$yMin)/$steps}] set n 0 for {set i 0} {$i < $steps} {incr i} { set x [expr {$xMin + $i * $dx}] for {set j 0} {$j < $steps} {incr j} { set y [expr {$yMin + $j * $dy}] foreach {xc yc rad2} $circles { set in 0 for {set v 0} {$v < $votes} {incr v} { set xr [expr {$x + (rand()-0.5)*$dx}] set yr [expr {$y + (rand()-0.5)*$dy}] if {($xr-$xc)**2 + ($yr-$yc)**2 <= $rad2} { incr in } } if {$in*2 >= $votes} { incr n break } } } } return [expr {$dx * $dy * $n}] }   puts [format "estimated area (grid): %.4f" [sampleGrid $circles 500]] puts [format "estimated area (monte carlo): %.2f" [sampleMC $circles 1000000]] puts [format "estimated area (perturbed sample): %.4f" [samplePerturb $circles 500 5]]
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]
#FunL
FunL
def topsort( graph ) = val L = seq() val S = seq() val g = dict( graph )   for (v, es) <- g g(v) = seq( es )   for (v, es) <- g if es.isEmpty() S.append( v )   while not S.isEmpty() val n = S.remove( 0 ) L.append( n )   for (m, es) <- g if n in es if (es -= n).isEmpty() S.append( m )   for (v, es) <- g if not es.isEmpty() return None   Some( L.toList() )   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 '''   // convert dependencies data into a directed graph graph = dict() deps = set()   for l <- WrappedString( dependencies ).lines() if l.trim() != '' case list(l.trim().split('\\s+')) of [a] -> graph(a) = [] h:t -> d = set( t ) d -= h // remove self dependencies graph(h) = d deps ++= t   // add graph vertices for dependencies not appearing in left column for e <- deps if e not in graph graph(e) = []   case topsort( graph ) of None -> println( 'un-orderable' ) Some( ordering ) -> println( ordering )
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.
#MATLAB
MATLAB
function tape=turing(rules,tape,initial,terminal) %"rules" is cell array of cell arrays of the following form: %First element is number representing initial state %Second element is number representing input from the tape %Third element is number representing output printed onto the tape %Fourth element is 'l', 'r', or 's' representing whether to go right, %left, or stay. Treats any input other than 'l' or 'r' as 's'. %Final value is state we go to %0 is always blank symbol term=0; ind=1; while term==0 a=[]; for i=1:numel(rules) if rules{i}{1}==initial a=[a i]; end end   possible=rules(a); n=numel(possible);   while numel(tape)<ind tape=[tape, 0]; %#ok<AGROW> end   for i=1:n if(tape(ind)==possible{i}{2}) break; end end instruction=possible{i}; tape(ind)=instruction{3}; if instruction{4}=='r' ind=ind+1; elseif instruction{4}=='l' if ind==1 tape=[0,tape]; %#ok<AGROW> else ind=ind-1; end end if terminal==instruction{5} term=1; else initial=instruction{5}; end end 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).
#Lua
Lua
-- Return the greatest common denominator of x and y function gcd (x, y) return y == 0 and math.abs(x) or gcd(y, x % y) end   -- Return the totient number for n function totient (n) local count = 0 for k = 1, n do if gcd(n, k) == 1 then count = count + 1 end end return count end   -- Determine (inefficiently) whether p is prime function isPrime (p) return totient(p) == p - 1 end   -- Output totient and primality for the first 25 integers print("n", string.char(237), "prime") print(string.rep("-", 21)) for i = 1, 25 do print(i, totient(i), isPrime(i)) end   -- Count the primes up to 100, 1000 and 10000 local pCount, i, limit = 0, 1 for power = 2, 4 do limit = 10 ^ power repeat i = i + 1 if isPrime(i) then pCount = pCount + 1 end until i == limit print("\nThere are " .. pCount .. " primes below " .. limit) 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
#Ruby
Ruby
def f1(a) i = 0 while (a0 = a[0]) > 1 a[0...a0] = a[0...a0].reverse i += 1 end i end   def fannkuch(n) [*1..n].permutation.map{|a| f1(a)}.max end   for n in 1..10 puts "%2d : %d" % [n, fannkuch(n)] 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.
#Forth
Forth
45e pi f* 180e f/ \ radians   cr fdup fsin f. \ also available: fsincos ( r -- sin cos ) cr fdup fcos f. cr fdup ftan f. cr fdup fasin f. cr fdup facos f. cr fatan f. \ also available: fatan2 ( r1 r2 -- atan[r1/r2] )
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.
#Fortran
Fortran
PROGRAM Trig   REAL pi, dtor, rtod, radians, degrees   pi = 4.0 * ATAN(1.0) dtor = pi / 180.0 rtod = 180.0 / pi radians = pi / 4.0 degrees = 45.0   WRITE(*,*) SIN(radians), SIN(degrees*dtor) WRITE(*,*) COS(radians), COS(degrees*dtor) WRITE(*,*) TAN(radians), TAN(degrees*dtor) WRITE(*,*) ASIN(SIN(radians)), ASIN(SIN(degrees*dtor))*rtod WRITE(*,*) ACOS(COS(radians)), ACOS(COS(degrees*dtor))*rtod WRITE(*,*) ATAN(TAN(radians)), ATAN(TAN(degrees*dtor))*rtod   END PROGRAM Trig
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).
#Perl
Perl
print "Enter 11 numbers:\n"; for ( 1..11 ) { $number = <STDIN>; chomp $number; push @sequence, $number; }   for $n (reverse @sequence) { my $result = sqrt( abs($n) ) + 5 * $n**3; printf "f( %6.2f ) %s\n", $n, $result > 400 ? " too large!" : sprintf "= %6.2f", $result }
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).
#Phix
Phix
function f(atom x) return sqrt(abs(x))+5*power(x,3) end function procedure test(string s, bool fake_prompt=true) if fake_prompt then printf(1,"Enter 11 numbers:%s\n",{s}) end if s = substitute(s,","," ") sequence S = scanf(s,"%f %f %f %f %f %f %f %f %f %f %f") if length(S)!=1 then puts(1,"not 11 numbers") abort(0) end if S = reverse(S[1]) for i=1 to length(S) do atom result = f(S[i]) if result>400 then printf(1,"f(%g):overflow\n",{S[i]}) else printf(1,"f(%g):%g\n",{S[i],result}) end if end for puts(1,"\n") end procedure --test(prompt_string("Enter 11 numbers:"),false) constant tests = {"10 -1 1 2 3 4 4.3 4.305 4.303 4.302 4.301","1,2,3,4,5,6,7,8,9,10,11", "0.470145,1.18367,2.36984,4.86759,2.40274,5.48793,3.30256,5.34393,4.21944,2.23501,-0.0200707"} papply(tests,test)
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.
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Text   Module Module1 Structure Operator_ Public ReadOnly Symbol As Char Public ReadOnly Precedence As Integer Public ReadOnly Arity As Integer Public ReadOnly Fun As Func(Of Boolean, Boolean, Boolean)   Public Sub New(symbol As Char, precedence As Integer, f As Func(Of Boolean, Boolean)) Me.New(symbol, precedence, 1, Function(l, r) f(r)) End Sub   Public Sub New(symbol As Char, precedence As Integer, f As Func(Of Boolean, Boolean, Boolean)) Me.New(symbol, precedence, 2, f) End Sub   Public Sub New(symbol As Char, precedence As Integer, arity As Integer, fun As Func(Of Boolean, Boolean, Boolean)) Me.Symbol = symbol Me.Precedence = precedence Me.Arity = arity Me.Fun = fun End Sub End Structure   Public Class OperatorCollection Implements IEnumerable(Of Operator_)   ReadOnly operators As IDictionary(Of Char, Operator_)   Public Sub New(operators As IDictionary(Of Char, Operator_)) Me.operators = operators End Sub   Public Sub Add(symbol As Char, precedence As Integer, fun As Func(Of Boolean, Boolean)) operators.Add(symbol, New Operator_(symbol, precedence, fun)) End Sub Public Sub Add(symbol As Char, precedence As Integer, fun As Func(Of Boolean, Boolean, Boolean)) operators.Add(symbol, New Operator_(symbol, precedence, fun)) End Sub   Public Sub Remove(symbol As Char) operators.Remove(symbol) End Sub   Public Function GetEnumerator() As IEnumerator(Of Operator_) Implements IEnumerable(Of Operator_).GetEnumerator Return operators.Values.GetEnumerator End Function   Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return GetEnumerator() End Function End Class   Structure BitSet Private ReadOnly bits As Integer   Public Sub New(bits As Integer) Me.bits = bits End Sub   Public Shared Operator +(bs As BitSet, v As Integer) As BitSet Return New BitSet(bs.bits + v) End Operator   Default Public ReadOnly Property Test(index As Integer) As Boolean Get Return (bits And (1 << index)) <> 0 End Get End Property End Structure   Public Class TruthTable Enum TokenType Unknown WhiteSpace Constant Operand Operator_ LeftParenthesis RightParenthesis End Enum   ReadOnly falseConstant As Char ReadOnly trueConstant As Char ReadOnly operatorDict As New Dictionary(Of Char, Operator_)   Public ReadOnly Operators As OperatorCollection   Sub New(falseConstant As Char, trueConstant As Char) Me.falseConstant = falseConstant Me.trueConstant = trueConstant Operators = New OperatorCollection(operatorDict) End Sub   Private Function TypeOfToken(c As Char) As TokenType If Char.IsWhiteSpace(c) Then Return TokenType.WhiteSpace End If If c = "("c Then Return TokenType.LeftParenthesis End If If c = ")"c Then Return TokenType.RightParenthesis End If If c = trueConstant OrElse c = falseConstant Then Return TokenType.Constant End If If operatorDict.ContainsKey(c) Then Return TokenType.Operator_ End If If Char.IsLetter(c) Then Return TokenType.Operand End If   Return TokenType.Unknown End Function   Private Function Precedence(op As Char) As Integer Dim o As New Operator_ If operatorDict.TryGetValue(op, o) Then Return o.Precedence Else Return Integer.MinValue End If End Function   Public Function ConvertToPostfix(infix As String) As String Dim stack As New Stack(Of Char) Dim postfix As New StringBuilder() For Each c In infix Dim type = TypeOfToken(c) Select Case type Case TokenType.WhiteSpace Continue For Case TokenType.Constant, TokenType.Operand postfix.Append(c) Case TokenType.Operator_ Dim precedence_ = Precedence(c) While stack.Count > 0 AndAlso Precedence(stack.Peek()) > precedence_ postfix.Append(stack.Pop()) End While stack.Push(c) Case TokenType.LeftParenthesis stack.Push(c) Case TokenType.RightParenthesis Dim top As Char While stack.Count > 0 top = stack.Pop() If top = "("c Then Exit While Else postfix.Append(top) End If End While If top <> "("c Then Throw New ArgumentException("No matching left parenthesis.") End If Case Else Throw New ArgumentException("Invalid character: " + c) End Select Next While stack.Count > 0 Dim top = stack.Pop() If top = "("c Then Throw New ArgumentException("No matching right parenthesis.") End If postfix.Append(top) End While Return postfix.ToString End Function   Private Function Evaluate(expression As Stack(Of Char), values As BitSet, parameters As IDictionary(Of Char, Integer)) As Boolean If expression.Count = 0 Then Throw New ArgumentException("Invalid expression.") End If Dim c = expression.Pop() Dim type = TypeOfToken(c) While type = TokenType.WhiteSpace c = expression.Pop() type = TypeOfToken(c) End While Select Case type Case TokenType.Constant Return c = trueConstant Case TokenType.Operand Return values(parameters(c)) Case TokenType.Operator_ Dim right = Evaluate(expression, values, parameters) Dim op = operatorDict(c) If op.Arity = 1 Then Return op.Fun(right, right) End If   Dim left = Evaluate(expression, values, parameters) Return op.Fun(left, right) Case Else Throw New ArgumentException("Invalid character: " + c) End Select   Return False End Function   Public Iterator Function GetTruthTable(expression As String, Optional isPostfix As Boolean = False) As IEnumerable(Of String) If String.IsNullOrWhiteSpace(expression) Then Throw New ArgumentException("Invalid expression.") End If REM Maps parameters to an index in BitSet REM Makes sure they appear in the truth table in the order they first appear in the expression Dim parameters = expression _ .Where(Function(c) TypeOfToken(c) = TokenType.Operand) _ .Distinct() _ .Reverse() _ .Select(Function(c, i) Tuple.Create(c, i)) _ .ToDictionary(Function(p) p.Item1, Function(p) p.Item2)   Dim count = parameters.Count If count > 32 Then Throw New ArgumentException("Cannot have more than 32 parameters.") End If Dim header = If(count = 0, expression, String.Join(" ", parameters.OrderByDescending(Function(p) p.Value).Select(Function(p) p.Key)) & " " & expression) If Not isPostfix Then expression = ConvertToPostfix(expression) End If   Dim values As BitSet Dim stack As New Stack(Of Char)(expression.Length)   Dim loopy = 1 << count While loopy > 0 For Each token In expression stack.Push(token) Next Dim result = Evaluate(stack, values, parameters) If Not IsNothing(header) Then If stack.Count > 0 Then Throw New ArgumentException("Invalid expression.") End If Yield header header = Nothing End If   Dim line = If(count = 0, "", " ") + If(result, trueConstant, falseConstant) line = String.Join(" ", Enumerable.Range(0, count).Select(Function(i) If(values(count - i - 1), trueConstant, falseConstant))) + line Yield line values += 1 '''''''''''''''''''''''''''' loopy -= 1 End While End Function   Public Sub PrintTruthTable(expression As String, Optional isPostfix As Boolean = False) Try For Each line In GetTruthTable(expression, isPostfix) Console.WriteLine(line) Next Catch ex As ArgumentException Console.WriteLine(expression + " " + ex.Message) End Try End Sub End Class   Sub Main() Dim tt As New TruthTable("F"c, "T"c) tt.Operators.Add("!"c, 6, Function(r) Not r) tt.Operators.Add("&"c, 5, Function(l, r) l And r) tt.Operators.Add("^"c, 4, Function(l, r) l Xor r) tt.Operators.Add("|"c, 3, Function(l, r) l Or r) REM add a crazy operator Dim rng As New Random tt.Operators.Add("?"c, 6, Function(r) rng.NextDouble() < 0.5) Dim expressions() = { "!!!T", "?T", "F & x | T", "F & (x | T", "F & x | T)", "a ! (a & a)", "a | (a * a)", "a ^ T & (b & !c)" } For Each expression In expressions tt.PrintTruthTable(expression) Console.WriteLine() Next   REM Define a different language tt = New TruthTable("0"c, "1"c) tt.Operators.Add("-"c, 6, Function(r) Not r) tt.Operators.Add("^"c, 5, Function(l, r) l And r) tt.Operators.Add("v"c, 3, Function(l, r) l Or r) tt.Operators.Add(">"c, 2, Function(l, r) Not l Or r) tt.Operators.Add("="c, 1, Function(l, r) l = r) expressions = { "-X v 0 = X ^ 1", "(H > M) ^ (S > H) > (S > M)" } For Each expression In expressions tt.PrintTruthTable(expression) Console.WriteLine() Next End Sub   End Module
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
#Yabasic
Yabasic
sub is_prime(n) local p   for p=2 to n if p*p>n break if mod(n,p)=0 return false next return n>=2 end sub   sub spiral(w, h, x, y) if y then return w+spiral(h-1,w,y-1,w-x-1) else return x end if end sub   w = 9 : h = 9 for i=h-1 to 0 step -1 for j=w-1 to 0 step -1 p = w*h-spiral(w,h,j,i) print mid$(" o", is_prime(p) + 1, 1); next print next
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.]
#Phix
Phix
with javascript_semantics constant N = 6, limit = power(10,N) -- standard sieve: enum L,R -- (with primes[i] as mini bit-field) sequence primes = repeat(L+R, limit) primes[1] = 0 for i=2 to floor(sqrt(limit)) do if primes[i] then for k=i*i to limit by i do primes[k] = 0 end for end if end for -- propagate non-truncateables up the prime table: for p=1 to N-1 do integer p10 = power(10,p) -- ie 10, 100, .. 100_000 for i=p10+1 to p10*10-1 by 2 do -- to 99, 999, .. 999_999 if primes[i] then integer l = remainder(i,p10), r = floor(i/10) integer pi = and_bits(primes[l],L)+and_bits(primes[r],R) if pi and find('0',sprint(i)) then pi = 0 end if primes[i] = pi end if end for end for integer maxl=0, maxr=0 for i=limit-1 to 1 by -2 do integer pi = primes[i] if pi then if maxl=0 and and_bits(pi,L) then maxl = i end if if maxr=0 and and_bits(pi,R) then maxr = i end if if maxl!=0 and maxr!=0 then exit end if end if end for ?{maxl,maxr}
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.
#Crystal
Crystal
  class Node(T) property left : Nil | Node(T) property right : Nil | Node(T) property data : T   def initialize(@data, @left = nil, @right = nil) end   def preorder_traverse print " #{data}" if left = @left left.preorder_traverse end if right = @right right.preorder_traverse end end   def inorder_traverse if left = @left left.inorder_traverse end print " #{data}" if right = @right right.inorder_traverse end end   def postorder_traverse if left = @left left.postorder_traverse end if right = @right right.postorder_traverse end print " #{data}" end   def levelorder_traverse queue = Array(Node(T)).new queue << self   until queue.size <= 0 node = queue.shift   unless node next end   print " #{node.data}"   if left = node.left queue << left end if right = node.right queue << right end end end end   tree = Node(Int32).new(1, Node(Int32).new(2, Node(Int32).new(4, Node(Int32).new(7)), Node(Int32).new(5)), Node(Int32).new(3, Node(Int32).new(6, Node(Int32).new(8), Node(Int32).new(9))))   print "preorder: " tree.preorder_traverse print "\ninorder: " tree.inorder_traverse print "\npostorder: " tree.postorder_traverse print "\nlevelorder: " tree.levelorder_traverse puts    
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
#Bracmat
Bracmat
( "Hello,How,Are,You,Today":?String & :?ReverseList & whl ' ( @(!String:?element "," ?String) & !element !ReverseList:?ReverseList ) & !String:?List & whl ' ( !ReverseList:%?element ?ReverseList & (!element.!List):?List ) & out$!List )
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
#C
C
#include<string.h> #include<stdio.h> #include<stdlib.h>   int main(void) { char *a[5]; const char *s="Hello,How,Are,You,Today"; int n=0, nn;   char *ds=strdup(s);   a[n]=strtok(ds, ","); while(a[n] && n<4) a[++n]=strtok(NULL, ",");   for(nn=0; nn<=n; ++nn) printf("%s.", a[nn]); putchar('\n');   free(ds);   return 0; }
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#BASIC256
BASIC256
call cont(10000000) print msec; " milliseconds"   t0 = msec call cont(10000000) print msec+t0; " milliseconds" end   subroutine cont(n) sum = 0 for i = 1 to n sum += 1 next i end subroutine
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Batch_File
Batch File
  @echo off Setlocal EnableDelayedExpansion   call :clock   ::timed function:fibonacci series..................................... set /a a=0 ,b=1,c=1 :loop if %c% lss 2000000000 echo %c% & set /a c=a+b,a=b, b=c & goto loop ::....................................................................   call :clock   echo Function executed in %timed% hundredths of second goto:eof   :clock if not defined timed set timed=0 for /F "tokens=1-4 delims=:.," %%a in ("%time%") do ( set /A timed = "(((1%%a - 100) * 60 + (1%%b - 100)) * 60 + (1%%c - 100)) * 100 + (1%%d - 100)- %timed%" ) goto:eof  
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
#D
D
import std.stdio, std.algorithm, std.conv, std.range;   struct Employee { string name, id; uint salary; string department; }   immutable Employee[] data = [ {"Tyler Bennett", "E10297", 32_000, "D101"}, {"John Rappl", "E21437", 47_000, "D050"}, {"George Woltman", "E00127", 53_500, "D101"}, {"Adam Smith", "E63535", 18_000, "D202"}, {"Claire Buckman", "E39876", 27_800, "D202"}, {"David McClellan", "E04242", 41_500, "D101"}, {"Rich Holcomb", "E01234", 49_500, "D202"}, {"Nathan Adams", "E41298", 21_900, "D050"}, {"Richard Potter", "E43128", 15_900, "D101"}, {"David Motsinger", "E27002", 19_250, "D202"}, {"Tim Sampair", "E03033", 27_000, "D101"}, {"Kim Arlich", "E10001", 57_000, "D190"}, {"Timothy Grove", "E16398", 29_900, "D190"}];   void main(in string[] args) { immutable n = (args.length == 2) ? to!int(args[1]) : 3;   Employee[][string] departments; foreach (immutable rec; data) departments[rec.department] ~= rec;   foreach (dep, recs; departments) { recs.topN!q{a.salary > b.salary}(n); writefln("Department %s\n  %(%s\n  %)\n", dep, recs.take(n)); } }
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedia tic-tac-toe.
#Bash
Bash
  #!/bin/bash declare -a B=( e e e e e e e e e ) # Board   function show(){ # show B - underline first 2 rows; highlight position; number empty positoins local -i p POS=${1:-9}; local UL BOLD="\e[1m" GREEN="\e[32m" DIM="\e[2m" OFF="\e[m" ULC="\e[4m" for p in 0 1 2 3 4 5 6 7 8; do [[ p%3 -eq 0 ]] && printf " " # indent boards UL=""; [[ p/3 -lt 2 ]] && UL=$ULC # underline first 2 rows [[ p -eq POS ]] && printf "$BOLD$GREEN" # bold and colour for this position [[ ${B[p]} = e ]] && printf "$UL$DIM%d$OFF" $p || printf "$UL%s$OFF" ${B[p]} # num or UL { [[ p%3 -lt 2 ]] && printf "$UL | $OFF"; } || printf "\n" # underline vertical bars or NL done };   function win(){ # win 'X' 3 return true if X wins after move in position 3 local ME=$1; local -i p=$2 [[ ${B[p/3*3]} = $ME && ${B[p/3*3+1]} = $ME && ${B[p/3*3+2]} = $ME ]] && return 0 # row [[ ${B[p]} = $ME && ${B[(p+3)%9]} = $ME && ${B[(p+6)%9]} = $ME ]] && return 0 # col [[ ${B[4]} != $ME ]] && return 1 # don't test diags [[ p%4 -eq 0 && ${B[0]} = $ME && ${B[8]} = $ME ]] && return 0 # TL - BR diag [[ p%4 -eq 2 || p -eq 4 ]] && [[ ${B[2]} = $ME && ${B[6]} = $ME ]] # TR - BL diag };   function bestMove(){ # return best move or 9 if none possible local ME=$1 OP=$2; local -i o s p local -ia S=( -9 -9 -9 -9 -9 -9 -9 -9 -9 ) # score board local -a SB # save board [[ ${B[*]//[!e]} = "" ]] && return 9 # game over SB=( ${B[*]} ) # save Board for p in 0 1 2 3 4 5 6 7 8; do # for each board position [[ ${B[p]} != e ]] && continue # skip occupied positions B[p]=$ME # occupy position win $ME $p && { S[p]=2; B=( ${SB[*]} ); return $p; } # ME wins so this is best move bestMove $OP $ME; o=$? # what will opponent do [[ o -le 8 ]] && { B[o]=$OP; win $OP $o; s=$?; } # opponent can make a legal move S[p]=${s:-1} # save result of opponent move B=( ${SB[*]} ) # restore board after each trial run done local -i best=-1; local -ia MOV=() for p in 0 1 2 3 4 5 6 7 8; do # find all best moves [[ S[p] -lt 0 ]] && continue # dont bother with occupied positions [[ S[p] -eq S[best] ]] && { MOV+=(p); best=p; } # add this move to current list [[ S[p] -gt S[best] ]] && { MOV=(p); best=p; } # a better move so scrap list and start again done return ${MOV[ RANDOM%${#MOV[*]} ]} # pick one at random };   function getMove(){ # getMove from opponent [[ $ME = X ]] && { bestMove $ME $OP; return $?; } # pick X move automatically read -p "O move: " -n 1; printf "\n"; return $REPLY # get opponents move };   function turn(){ # turn starts or continues a game. It is ME's turn local -i p; local ME=$1 OP=$2 getMove; p=$?; [[ p -gt 8 ]] && { printf "Draw!\n"; show; return 1; } # no move so a draw B[p]=$ME; printf "%s moves %d\n" $ME $p # mark board win $ME $p && { printf "%s wins!\n" $ME; show $p; [[ $ME = X ]] && return 2; return 0; } [[ ${B[*]//[!e]} = "" ]] && { printf "Draw!\n"; show; return 1; } # no move so a draw show $p; turn $OP $ME # opponent moves };   printf "Bic Bash Bow\n" show; [[ RANDOM%2 -eq 0 ]] && { turn O X; exit $?; } || turn X O    
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#BASIC256
BASIC256
call move(4,1,2,3) print "Towers of Hanoi puzzle completed!" end   subroutine move (n, fromPeg, toPeg, viaPeg) if n>0 then call move(n-1, fromPeg, viaPeg, toPeg) print "Move disk from "+fromPeg+" to "+toPeg call move(n-1, viaPeg, toPeg, fromPeg) end if end subroutine
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
#Go
Go
// prints the first few members of the Thue-Morse sequence   package main   import ( "fmt" "bytes" )   // sets tmBuffer to the next member of the Thue-Morse sequence // tmBuffer must contain a valid Thue-Morse sequence member before the call func nextTMSequenceMember( tmBuffer * bytes.Buffer ) { // "flip" the bytes, adding them to the buffer for b, currLength, currBytes := 0, tmBuffer.Len(), tmBuffer.Bytes() ; b < currLength; b ++ { if currBytes[ b ] == '1' { tmBuffer.WriteByte( '0' ) } else { tmBuffer.WriteByte( '1' ) } } }   func main() { var tmBuffer bytes.Buffer // initial sequence member is "0" tmBuffer.WriteByte( '0' ) fmt.Println( tmBuffer.String() ) for i := 2; i <= 7; i ++ { nextTMSequenceMember( & tmBuffer ) fmt.Println( tmBuffer.String() ) } }
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
#Haskell
Haskell
thueMorsePxs :: [[Int]] thueMorsePxs = iterate ((++) <*> map (1 -)) [0]   {- = Control.Monad.ap (++) (map (1-)) `iterate` [0] = iterate (\ xs -> (++) xs (map (1-) xs)) [0] = iterate (\ xs -> xs ++ map (1-) xs) [0] -} main :: IO () main = print $ thueMorsePxs !! 5
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
#Racket
Racket
#lang racket   (require math/number-theory)   (define (Legendre a p) (modexpt a (quotient (sub1 p) 2)))   (define (Tonelli n p (err (λ (n p) (error "not a square (mod p)" (list n p))))) (with-modulus p (unless (= 1 (Legendre n p)) (err n p))   (define-values (q s) (let even?-q-loop ((q (sub1 p)) (s 0)) (if (even? q) (even?-q-loop (quotient q 2) (add1 s)) (values q s))))   (cond [(= s 1) (modexpt n (/ (add1 p) 4))] [else (define z (for/first ((z (in-range 2 p)) #:when (= (sub1 p) (Legendre z p))) z)) (let loop ((c (modexpt z q)) (r (modexpt n (quotient (add1 q) 2))) (t (modexpt n q)) (m s)) (cond [(mod= 1 t) r] [else (define-values (t2 m′) (for/fold ((t2 (modsqr t)) (i 1)) ((j (in-range 1 m)) #:final (mod= t2 1)) (values (modsqr t2) j))) (define b (modexpt c (expt 2 (- m m′ 1)))) (define c′ (modsqr b)) (loop c′ (mod* r b) (mod* t c′) m′)]))])))   (module+ test (require rackunit)   (define ttest `((10 13) (56 101) (1030 10009) (44402 100049) (665820697 1000000009) (881398088036 1000000000039) (41660815127637347468140745042827704103445750172002 ,(+ #e1e50 577))))   (define (task ttest) (for ((test ttest)) (define n (first test)) (define p (second test)) (define r (Tonelli n p)) (printf "n = ~a p = ~a~% roots : ~a ~a~%" n p r (- p r))))   (task ttest)   (check-exn exn:fail? (λ () (Tonelli 1032 1009))))
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
#Raku
Raku
# Legendre operator (𝑛│𝑝) sub infix:<│> (Int \𝑛, Int \𝑝 where 𝑝.is-prime && (𝑝 != 2)) { given 𝑛.expmod( (𝑝-1) div 2, 𝑝 ) { when 0 { 0 } when 1 { 1 } default { -1 } } }   sub tonelli-shanks ( \𝑛, \𝑝 where (𝑛│𝑝) > 0 ) { my $𝑄 = 𝑝 - 1; my $𝑆 = 0; $𝑄 +>= 1 and $𝑆++ while $𝑄 %% 2; return 𝑛.expmod((𝑝+1) div 4, 𝑝) if $𝑆 == 1; my $𝑐 = ((2..𝑝).first: (*│𝑝) < 0).expmod($𝑄, 𝑝); my $𝑅 = 𝑛.expmod( ($𝑄+1) +> 1, 𝑝 ); my $𝑡 = 𝑛.expmod( $𝑄, 𝑝 ); while ($𝑡-1) % 𝑝 { my $b; my $𝑡2 = $𝑡² % 𝑝; for 1 .. $𝑆 { if ($𝑡2-1) %% 𝑝 { $b = $𝑐.expmod(1 +< ($𝑆-1-$_), 𝑝); $𝑆 = $_; last; } $𝑡2 = $𝑡2² % 𝑝; } $𝑅 = ($𝑅 * $b) % 𝑝; $𝑐 = $b² % 𝑝; $𝑡 = ($𝑡 * $𝑐) % 𝑝; } $𝑅; }   my @tests = ( (10, 13), (56, 101), (1030, 10009), (1032, 10009), (44402, 100049), (665820697, 1000000009), (881398088036, 1000000000039), (41660815127637347468140745042827704103445750172002, 100000000000000000000000000000000000000000000000577) );   for @tests -> ($n, $p) { try my $t = tonelli-shanks($n, $p); say "No solution for ({$n}, {$p})." and next if !$t or ($t² - $n) % $p; say "Roots of $n are ($t, {$p-$t}) mod $p"; }
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were 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
#J
J
  tokenize1=: tokenize =: '^|'&$: :(4 : 0) 'ESC SEP' =. x STATE =. 0 RESULT =. 0 $ a: TOKEN =. '' for_C. y do. if. STATE do. TOKEN =. TOKEN , C STATE =. 0 else. if. C = ESC do. STATE =. 1 elseif. C = SEP do. RESULT =. RESULT , < TOKEN TOKEN =. '' elseif. do. TOKEN =. TOKEN , C end. end. end. RESULT =. RESULT , < TOKEN )  
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were separated by the separators, become the elements of the output list. Empty fields should be preserved, even at the start and end. Rules for escaping: "Escaped" means preceded by an occurrence of the escape character that is not already escaped itself. When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special). Each occurrence of the escape character that was used to escape something, should not become part of the output. Test case Demonstrate that your function satisfies the following test-case: Input Output string: one^|uno||three^^^^|four^^^|^cuatro| separator character: | escape character: ^ one|uno three^^ four^|cuatro (Print the output list in any format you like, as long as it is it easy to see what the fields are.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Java
Java
import java.util.*;   public class TokenizeStringWithEscaping {   public static void main(String[] args) { String sample = "one^|uno||three^^^^|four^^^|^cuatro|"; char separator = '|'; char escape = '^';   System.out.println(sample); try { System.out.println(tokenizeString(sample, separator, escape)); } catch (Exception e) { System.out.println(e); } }   public static List<String> tokenizeString(String s, char sep, char escape) throws Exception { List<String> tokens = new ArrayList<>(); StringBuilder sb = new StringBuilder();   boolean inEscape = false; for (char c : s.toCharArray()) { if (inEscape) { inEscape = false; } else if (c == escape) { inEscape = true; continue; } else if (c == sep) { tokens.add(sb.toString()); sb.setLength(0); continue; } sb.append(c); } if (inEscape) throw new Exception("Invalid terminal escape");   tokens.add(sb.toString());   return tokens; } }
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
#VBA
VBA
Public c As Variant Public pi As Double Dim arclists() As Variant Public Enum circles_ xc = 0 yc rc End Enum Public Enum arclists_ rho x_ y_ i_ End Enum Public Enum shoelace_axis u = 0 v End Enum Private Sub give_a_list_of_circles() c = Array(Array(1.6417233788, 1.6121789534, 0.0848270516), _ Array(-1.4944608174, 1.2077959613, 1.1039549836), _ Array(0.6110294452, -0.6907087527, 0.9089162485), _ Array(0.3844862411, 0.2923344616, 0.2375743054), _ Array(-0.249589295, -0.3832854473, 1.0845181219), _ Array(1.7813504266, 1.6178237031, 0.8162655711), _ Array(-0.1985249206, -0.8343333301, 0.0538864941), _ Array(-1.7011985145, -0.1263820964, 0.4776976918), _ Array(-0.4319462812, 1.4104420482, 0.7886291537), _ Array(0.2178372997, -0.9499557344, 0.0357871187), _ Array(-0.6294854565, -1.3078893852, 0.7653357688), _ Array(1.7952608455, 0.6281269104, 0.2727652452), _ Array(1.4168575317, 1.0683357171, 1.1016025378), _ Array(1.4637371396, 0.9463877418, 1.1846214562), _ Array(-0.5263668798, 1.7315156631, 1.4428514068), _ Array(-1.2197352481, 0.9144146579, 1.0727263474), _ Array(-0.1389358881, 0.109280578, 0.7350208828), _ Array(1.5293954595, 0.0030278255, 1.2472867347), _ Array(-0.5258728625, 1.3782633069, 1.3495508831), _ Array(-0.1403562064, 0.2437382535, 1.3804956588), _ Array(0.8055826339, -0.0482092025, 0.3327165165), _ Array(-0.6311979224, 0.7184578971, 0.2491045282), _ Array(1.4685857879, -0.8347049536, 1.3670667538), _ Array(-0.6855727502, 1.6465021616, 1.0593087096), _ Array(0.0152957411, 0.0638919221, 0.9771215985)) pi = WorksheetFunction.pi() End Sub Private Function shoelace(s As Collection) As Double 's is a collection of coordinate pairs (x, y), 'in clockwise order for positive result. 'The last pair is identical to the first pair. 'These pairs map a polygonal area. 'The area is computed with the shoelace algoritm. 'see the Rosetta Code task. Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i + 1)(u) * s(i)(v) - s(i)(u) * s(i + 1)(v) Next i End If shoelace = t / 2 End Function Private Sub arc_sub(acol As Collection, f0 As Double, u0 As Double, v0 As Double, _ f1 As Double, u1 As Double, v1 As Double, this As Integer, j As Integer) 'subtract the arc from f0 to f1 from the arclist acol 'complicated to deal with edge cases If acol.Count = 0 Then Exit Sub 'nothing to subtract from Debug.Assert acol.Count Mod 2 = 0 Debug.Assert f0 <> f1 If f1 = pi Or f1 + pi < 5E-16 Then f1 = -f1 If f0 = pi Or f0 + pi < 5E-16 Then f0 = -f0 If f0 < f1 Then 'the arc does not pass the negative x-axis 'find a such that acol(a)(0)<f0<acol(a+1)(0) ' and b such that acol(b)(0)<f1<acol(b+1)(0) If f1 < acol(1)(rho) Or f0 > acol(acol.Count)(rho) Then Exit Sub 'nothing to subtract i = acol.Count + 1 start = 1 Do i = i - 1 Loop Until f1 > acol(i)(rho) If i Mod 2 = start Then acol.Add Array(f1, u1, v1, j), after:=i End If i = 0 Do i = i + 1 Loop Until f0 < acol(i)(rho) If i Mod 2 = 1 - start Then acol.Add Array(f0, u0, v0, j), before:=i i = i + 1 End If Do While acol(i)(rho) < f1 acol.Remove i If i > acol.Count Then Exit Do Loop Else start = 1 If f0 > acol(1)(rho) Then i = acol.Count + 1 Do i = i - 1 Loop While f0 < acol(i)(0) If f0 = pi Then acol.Add Array(f0, u0, v0, j), before:=i Else If i Mod 2 = start Then acol.Add Array(f0, u0, v0, j), after:=i End If End If End If If f1 <= acol(acol.Count)(rho) Then i = 0 Do i = i + 1 Loop While f1 > acol(i)(rho) If f1 + pi < 5E-16 Then acol.Add Array(f1, u1, v1, j), after:=i Else If i Mod 2 = 1 - start Then acol.Add Array(f1, u1, v1, j), before:=i End If End If End If Do While acol(acol.Count)(rho) > f0 Or acol(acol.Count)(i_) = -1 acol.Remove acol.Count If acol.Count = 0 Then Exit Do Loop If acol.Count > 0 Then Do While acol(1)(rho) < f1 Or (f1 = -pi And acol(1)(i_) = this) acol.Remove 1 If acol.Count = 0 Then Exit Do Loop End If End If End Sub Private Sub circle_cross() ReDim arclists(LBound(c) To UBound(c)) Dim alpha As Double, beta As Double Dim x3 As Double, x4 As Double, y3 As Double, y4 As Double Dim i As Integer, j As Integer For i = LBound(c) To UBound(c) Dim arccol As New Collection 'arccol is a collection or surviving arcs of circle i. 'It starts with the full circle. The collection 'alternates between start and ending angles of the arcs. 'This winds counter clockwise. 'Noted are angle, x coordinate, y coordinate and 'index number of circles with which circle i 'intersects at that angle and -1 marks visited. This defines 'ultimately a double linked list. So winding 'clockwise in the end is easy. arccol.Add Array(-pi, c(i)(xc) - c(i)(r), c(i)(yc), i) arccol.Add Array(pi, c(i)(xc) - c(i)(r), c(i)(yc), -1) For j = LBound(c) To UBound(c) If i <> j Then x0 = c(i)(xc) y0 = c(i)(yc) r0 = c(i)(rc) x1 = c(j)(xc) y1 = c(j)(yc) r1 = c(j)(rc) d = Sqr((x0 - x1) ^ 2 + (y0 - y1) ^ 2) 'Ignore 0 and 1, we need only the 2 case. If d >= r0 + r1 Or d <= Abs(r0 - r1) Then 'no intersections Else a = (r0 ^ 2 - r1 ^ 2 + d ^ 2) / (2 * d) h = Sqr(r0 ^ 2 - a ^ 2) x2 = x0 + a * (x1 - x0) / d y2 = y0 + a * (y1 - y0) / d x3 = x2 + h * (y1 - y0) / d y3 = y2 - h * (x1 - x0) / d alpha = WorksheetFunction.Atan2(x3 - x0, y3 - y0) x4 = x2 - h * (y1 - y0) / d y4 = y2 + h * (x1 - x0) / d beta = WorksheetFunction.Atan2(x4 - x0, y4 - y0) 'alpha is counterclockwise positioned w.r.t beta 'so the arc from beta to alpha (ccw) has to be 'subtracted from the list of surviving arcs as 'this arc lies fully in circle j arc_sub arccol, alpha, x3, y3, beta, x4, y4, i, j End If End If Next j Set arclists(i) = arccol Set arccol = Nothing Next i End Sub Private Sub make_path() Dim pathcol As New Collection, arcsum As Double i0 = UBound(arclists) finished = False Do While True arcsum = 0 Do While arclists(i0).Count = 0 i0 = i0 - 1 Loop j0 = arclists(i0).Count next_i = i0 next_j = j0 Do While True x = arclists(next_i)(next_j)(x_) y = arclists(next_i)(next_j)(y_) pathcol.Add Array(x, y) prev_i = next_i prev_j = next_j If arclists(next_i)(next_j - 1)(i_) = next_i Then 'skip the join point at the negative x-axis next_j = arclists(next_i).Count - 1 If next_j = 1 Then Exit Do 'loose full circle arc Else next_j = next_j - 1 End If '------------------------------ r = c(next_i)(rc) a1 = arclists(next_i)(prev_j)(rho) a2 = arclists(next_i)(next_j)(rho) If a1 > a2 Then alpha = a1 - a2 Else alpha = 2 * pi - a2 + a1 End If arcsum = arcsum + r * r * (alpha - Sin(alpha)) / 2 '------------------------------ next_i = arclists(next_i)(next_j)(i_) next_j = arclists(next_i).Count If next_j = 0 Then Exit Do 'skip loose arcs Do While arclists(next_i)(next_j)(i_) <> prev_i 'find the matching item next_j = next_j - 1 Loop If next_i = i0 And next_j = j0 Then finished = True Exit Do End If Loop If finished Then Exit Do i0 = i0 - 1 Set pathcol = Nothing Loop Debug.Print shoelace(pathcol) + arcsum End Sub Public Sub total_circles() give_a_list_of_circles circle_cross make_path End Sub
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]
#Go
Go
package main   import ( "fmt" "strings" )   var data = ` 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 `   func main() { g, in, err := parseLibComp(data) if err != nil { fmt.Println(err) return } order, cyclic := topSortKahn(g, in) if cyclic != nil { fmt.Println("Cyclic:", cyclic) return } fmt.Println("Order:", order) }   type graph map[string][]string type inDegree map[string]int   // parseLibComp parses the text format of the task and returns a graph // representation and a list of the in-degrees of each node. The returned graph // represents compile order rather than dependency order. That is, for each map // map key n, the map elements are libraries that depend on n being compiled // first. func parseLibComp(data string) (g graph, in inDegree, err error) { // small sanity check on input lines := strings.Split(data, "\n") if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") { return nil, nil, fmt.Errorf("data format") } // toss header lines lines = lines[3:] // scan and interpret input, build graph g = graph{} in = inDegree{} for _, line := range lines { libs := strings.Fields(line) if len(libs) == 0 { continue // allow blank lines } lib := libs[0] g[lib] = g[lib] for _, dep := range libs[1:] { in[dep] = in[dep] if dep == lib { continue // ignore self dependencies } successors := g[dep] for i := 0; ; i++ { if i == len(successors) { g[dep] = append(successors, lib) in[lib]++ break } if dep == successors[i] { break // ignore duplicate dependencies } } } } return g, in, nil }   // General purpose topological sort, not specific to the application of // library dependencies. Adapted from Wikipedia pseudo code, one main // difference here is that this function does not consume the input graph. // WP refers to incoming edges, but does not really need them fully represented. // A count of incoming edges, or the in-degree of each node is enough. Also, // WP stops at cycle detection and doesn't output information about the cycle. // A little extra code at the end of this function recovers the cyclic nodes. func topSortKahn(g graph, in inDegree) (order, cyclic []string) { var L, S []string // rem for "remaining edges," this function makes a local copy of the // in-degrees and consumes that instead of consuming an input. rem := inDegree{} for n, d := range in { if d == 0 { // accumulate "set of all nodes with no incoming edges" S = append(S, n) } else { // initialize rem from in-degree rem[n] = d } } for len(S) > 0 { last := len(S) - 1 // "remove a node n from S" n := S[last] S = S[:last] L = append(L, n) // "add n to tail of L" for _, m := range g[n] { // WP pseudo code reads "for each node m..." but it means for each // node m *remaining in the graph.* We consume rem rather than // the graph, so "remaining in the graph" for us means rem[m] > 0. if rem[m] > 0 { rem[m]-- // "remove edge from the graph" if rem[m] == 0 { // if "m has no other incoming edges" S = append(S, m) // "insert m into S" } } } } // "If graph has edges," for us means a value in rem is > 0. for c, in := range rem { if in > 0 { // recover cyclic nodes for _, nb := range g[c] { if rem[nb] > 0 { cyclic = append(cyclic, c) break } } } } if len(cyclic) > 0 { return nil, cyclic } return L, nil }
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.
#Mercury
Mercury
:- module turing.   :- interface.   :- import_module list. :- import_module set.   :- type config(State, Symbol) ---> config(initial_state  :: State, halting_states :: set(State), blank  :: Symbol ).   :- type action ---> left ; stay ; right.   :- func turing(config(State, Symbol), pred(State, Symbol, Symbol, action, State), list(Symbol)) = list(Symbol). :- mode turing(in, pred(in, in, out, out, out) is semidet, in) = out is det.   :- implementation.   :- import_module pair. :- import_module require.   turing(Config@config(Start, _, _), Rules, Input) = Output :- (Left-Right) = perform(Config, Rules, Start, ([]-Input)), Output = append(reverse(Left), Right).   :- func perform(config(State, Symbol), pred(State, Symbol, Symbol, action, State), State, pair(list(Symbol))) = pair(list(Symbol)). :- mode perform(in, pred(in, in, out, out, out) is semidet, in, in) = out is det. perform(Config@config(_, Halts, Blank), Rules, State, Input@(LeftInput-RightInput)) = Output :- symbol(RightInput, Blank, RightNew, Symbol), ( set.member(State, Halts) -> Output = Input  ; Rules(State, Symbol, NewSymbol, Action, NewState) -> NewLeft = pair(LeftInput, [NewSymbol|RightNew]), NewRight = action(Action, Blank, NewLeft), Output = perform(Config, Rules, NewState, NewRight)  ; error("an impossible state has apparently become possible") ).   :- pred symbol(list(Symbol), Symbol, list(Symbol), Symbol). :- mode symbol(in, in, out, out) is det. symbol([], Blank, [], Blank). symbol([Sym|Rem], _, Rem, Sym).   :- func action(action, State, pair(list(State))) = pair(list(State)). action(left, Blank, ([]-Right)) = ([]-[Blank|Right]). action(left, _, ([Left|Lefts]-Rights)) = (Lefts-[Left|Rights]). action(stay, _, Tape) = Tape. action(right, Blank, (Left-[])) = ([Blank|Left]-[]). action(right, _, (Left-[Right|Rights])) = ([Right|Left]-Rights).
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).
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Do[ tmp = EulerPhi[i]; If[i - 1 == tmp, Print["\[CurlyPhi](", i, ")=", tmp, ", is prime"] , Print["\[CurlyPhi](", i, ")=", tmp] ] , {i, 25} ] Count[EulerPhi[Range[100]] - Range[100], -1] Count[EulerPhi[Range[1000]] - Range[1000], -1] Count[EulerPhi[Range[10000]] - Range[10000], -1] Count[EulerPhi[Range[100000]] - Range[100000], -1] (*Alternative much faster way of findings the number primes up to a number*) (*PrimePi[100]*) (*PrimePi[1000]*) (*PrimePi[10000]*) (*PrimePi[100000]*)
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
#Rust
Rust
  use itertools::Itertools;   fn solve(deck: &[usize]) -> usize { let mut counter = 0_usize; let mut shuffle = deck.to_vec(); loop { let p0 = shuffle[0]; if p0 == 1 { break; } shuffle[..p0].reverse(); counter += 1; }   counter }   // this is a naive method which tries all permutations and works up to ~12 cards fn topswops(number: usize) -> usize { (1..=number) .permutations(number) .fold(0_usize, |mut acc, p| { let steps = solve(&p); if steps > acc { acc = steps; } acc }) } fn main() { (1_usize..=10).for_each(|x| println!("{}: {}", x, topswops(x))); }  
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
#Scala
Scala
object Fannkuch extends App {   def fannkuchen(l: List[Int], n: Int, i: Int, acc: Int): Int = { def flips(l: List[Int]): Int = (l: @unchecked) match { case 1 :: ls => 0 case (n :: ls) => val splitted = l.splitAt(n) flips(splitted._2.reverse_:::(splitted._1)) + 1 }   def rotateLeft(l: List[Int]) = l match { case Nil => List() case x :: xs => xs ::: List(x) }   if (i >= n) acc else { if (n == 1) acc.max(flips(l)) else { val split = l.splitAt(n) fannkuchen(rotateLeft(split._1) ::: split._2, n, i + 1, fannkuchen(l, n - 1, 0, acc)) } } } // def fannkuchen(   val result = (1 to 10).map(i => (i, fannkuchen(List.range(1, i + 1), i, 0, 0))) println("Computing results...") result.foreach(x => println(s"Pfannkuchen(${x._1})\t= ${x._2}")) assert(result == Vector((1, 0), (2, 1), (3, 2), (4, 4), (5, 7), (6, 10), (7, 16), (8, 22), (9, 30), (10, 38)), "Bad results") println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]") }
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.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Const pi As Double = 4 * Atn(1) Dim As Double radians = pi / 4 Dim As Double degrees = 45.0 '' equivalent in degrees Dim As Double temp   Print "Radians  : "; radians, " "; Print "Degrees  : "; degrees Print Print "Sine  : "; Sin(radians), Sin(degrees * pi / 180) Print "Cosine  : "; Cos(radians), Cos(degrees * pi / 180) Print "Tangent  : "; Tan(radians), Tan(degrees * pi / 180) Print temp = ASin(Sin(radians)) Print "Arc Sine  : "; temp, temp * 180 / pi temp = ACos(Cos(radians)) Print "Arc Cosine  : "; temp, temp * 180 / pi temp = Atn(Tan(radians)) Print "Arc Tangent : "; temp, temp * 180 / pi Sleep
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).
#Picat
Picat
import util.   go => L = [I.parse_term() : I in split(read_line())], S = [[I,cond(F<=400,F,'TOO LARGE')] : I in L.len..-1..1, F=f(L[I])], println(S), nl.   f(T) = sqrt(abs(T)) + 5*T**3.
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm. From the wikipedia entry: ask for 11 numbers to be read into a sequence S reverse sequence S for each item in sequence S result := call a function to do an operation if result overflows alert user else print result The task is to implement the algorithm: Use the function:     f ( x ) = | x | 0.5 + 5 x 3 {\displaystyle f(x)=|x|^{0.5}+5x^{3}} The overflow condition is an answer of greater than 400. The 'user alert' should not stop processing of other items of the sequence. Print a prompt before accepting eleven, textual, numeric inputs. You may optionally print the item as well as its associated result, but the results must be in reverse order of input. The sequence   S   may be 'implied' and so not shown explicitly. Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#PicoLisp
PicoLisp
(de f (X) (+ (sqrt (abs X)) (* 5 X X X)) )   (trace 'f)   (in NIL (prin "Input 11 numbers: ") (for X (reverse (make (do 11 (link (read))))) (when (> (f X) 400) (prinl "TOO LARGE") ) ) )
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.
#Wren
Wren
import "/dynamic" for Struct import "/ioutil" for Input import "/seq" for Stack import "/str" for Str   var Variable = Struct.create("Variable", ["name", "value"])   // use integer constants as bools don't support bitwise operators var FALSE = 0 var TRUE = 1   var expr = "" var variables = []   var isOperator = Fn.new { |op| "&|!^".contains(op) }   var isVariable = Fn.new { |s| variables.map { |v| v.name }.contains(s) }   var evalExpression = Fn.new { var stack = Stack.new() for (e in expr) { var v if (e == "T") { v = TRUE } else if (e == "F") { v = FALSE } else if (isVariable.call(e)) { var vs = variables.where { |v| v.name == e }.toList if (vs.count != 1) Fiber.abort("Can only be one variable with name %(e).") v = vs[0].value } else if (e == "&") { v = stack.pop() & stack.pop() } else if (e == "|") { v = stack.pop() | stack.pop() } else if (e == "!") { v = (stack.pop() == TRUE) ? FALSE : TRUE } else if (e == "^") { v = stack.pop() ^ stack.pop() } else { Fiber.abort("Non-conformant character %(e) in expression") } stack.push(v) } if (stack.count != 1) Fiber.abort("Something went wrong!") return stack.peek() }   var setVariables // recursive setVariables = Fn.new { |pos| var vc = variables.count if (pos > vc) Fiber.abort("Argument cannot exceed %(vc).") if (pos == vc) { var vs = variables.map { |v| (v.value == TRUE) ? "T" : "F" }.toList var es = (evalExpression.call() == TRUE) ? "T" : "F" System.print("%(vs.join(" "))  %(es)") return } variables[pos].value = FALSE setVariables.call(pos + 1) variables[pos].value = TRUE setVariables.call(pos + 1) }   System.print("Accepts single-character variables (except for 'T' and 'F',") System.print("which specify explicit true or false values), postfix, with") System.print("&|!^ for and, or, not, xor, respectively; optionally") System.print("seperated by spaces or tabs. Just enter nothing to quit.")   while (true) { expr = Input.text("\nBoolean expression: ") if (expr == "") return expr = Str.upper(expr).replace(" ", "").replace("\t", "") variables.clear() for (e in expr) { if (!isOperator.call(e) && !"TF".contains(e) && !isVariable.call(e)) { variables.add(Variable.new(e, FALSE)) } } if (variables.isEmpty) return var vs = variables.map { |v| v.name }.join(" ") System.print("\n%(vs)  %(expr)") var h = vs.count + expr.count + 2 System.print("=" * h) setVariables.call(0) }
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
#zkl
zkl
var primes =Utils.Generator(Import("sieve.zkl").postponed_sieve); // lazy var offsets=Utils.cycle( T(0,1),T(-1,0),T(0,-1),T(1,0) ); // (N,E,S,W), lazy const BLACK=0, WHITE=0xff|ff|ff, GREEN=0x00|ff|00, EMPTY=0x080|80|80; fcn uspiral(N){ if((M:=N).isEven) M+=1; // need odd width, height img,p := PPM(M,M,EMPTY), primes.next(); // 2 .. 250,007: 22,045 primes x,y,n := N/2,x,2; img[x,y]=GREEN; x+=1; // start on 2 facing "north" while(True){ ox,oy:=offsets.next(); leftx,lefty:=offsets.peek(); // set direction while(True){ img[x,y]=( if(n==p){ p=primes.next(); WHITE } else BLACK ); if(n==N*N) break(2); // all done n+=1; if(img[x+leftx,y+lefty]==EMPTY) // nothing to my left, turn left { x+=leftx; y+=lefty; break; } x+=ox; y+=oy; // move in a straight line } } img }   uspiral(500).write(File("ulamSpiral.ppm","wb"));