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/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
#Haskell
Haskell
import Data.List import Data.Numbers.Primes   ulam n representation = swirl n . map representation
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.]
#C.2B.2B
C++
#include <iostream> #include "prime_sieve.hpp"   bool is_left_truncatable(const prime_sieve& sieve, int p) { for (int n = 10, q = p; p > n; n *= 10) { if (!sieve.is_prime(p % n) || q == p % n) return false; q = p % n; } return true; }   bool is_right_truncatable(const prime_sieve& sieve, int p) { for (int q = p/10; q > 0; q /= 10) { if (!sieve.is_prime(q)) return false; } return true; }   int main() { const int limit = 1000000;   // find the prime numbers up to the limit prime_sieve sieve(limit + 1);   int largest_left = 0; int largest_right = 0; // find largest left truncatable prime for (int p = limit; p >= 2; --p) { if (sieve.is_prime(p) && is_left_truncatable(sieve, p)) { largest_left = p; break; } } // find largest right truncatable prime for (int p = limit; p >= 2; --p) { if (sieve.is_prime(p) && is_right_truncatable(sieve, p)) { largest_right = p; break; } } // write results to standard output std::cout << "Largest left truncatable prime is " << largest_left << '\n'; std::cout << "Largest right truncatable prime is " << largest_right << '\n'; return 0; }
http://rosettacode.org/wiki/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive. Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes. For N over its range, generate and show counts of the outputs of randN and unbiased(randN). The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN. This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
#Visual_Basic_.NET
Visual Basic .NET
Module Module1 Dim random As New Random()   Function RandN(n As Integer) As Boolean Return random.Next(0, n) = 0 End Function   Function Unbiased(n As Integer) As Boolean Dim flip1 As Boolean Dim flip2 As Boolean   Do flip1 = RandN(n) flip2 = RandN(n) Loop While flip1 = flip2   Return flip1 End Function   Sub Main() For n = 3 To 6 Dim biasedZero = 0 Dim biasedOne = 0 Dim unbiasedZero = 0 Dim unbiasedOne = 0 For i = 1 To 100000 If RandN(n) Then biasedOne += 1 Else biasedZero += 1 End If If Unbiased(n) Then unbiasedOne += 1 Else unbiasedZero += 1 End If Next   Console.WriteLine("(N = {0}):".PadRight(17) + "# of 0" + vbTab + "# of 1" + vbTab + "% of 0" + vbTab + "% of 1", n) Console.WriteLine("(Biased: {0}):".PadRight(15) + "{0}" + vbTab + "{1}" + vbTab + "{2}" + vbTab + "{3}", biasedZero, biasedOne, biasedZero / 1000, biasedOne / 1000) Console.WriteLine("(UnBiased: {0}):".PadRight(15) + "{0}" + vbTab + "{1}" + vbTab + "{2}" + vbTab + "{3}", unbiasedZero, unbiasedOne, unbiasedZero / 1000, unbiasedOne / 1000) Next End Sub   End Module
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#PicoLisp
PicoLisp
(de truncate (File Len) (native "@" "truncate" 'I File Len) )
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#PL.2FI
PL/I
  /* Parameters to be read in by the program are: */ /* 1. the name of the file to be truncated, and */ /* 2. the size of file after truncation. */   truncate_file: procedure options (main); /* 12 July 2012 */ declare (i, n) fixed binary (31); declare filename character(50) varying; declare in file record input, out file record output;   put ('What is the name of the file to be truncated?'); get edit (filename) (L); put ('What is the length of file to be retained?'); get (n);   begin; declare c(n) character (1), ch character (1);   open file (in) title ('/' || filename || ',type(fixed),recsize(1)' ) input; do i = 1 to n; read file (in) into (ch); c(i) = ch; end; close file (in);   open file (out) title ('/' || filename || ',append(n),type(fixed), recsize(' || trim(n) || ')' ); write file (out) from (c); close file (out); end; end truncate_file;  
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.
#APL
APL
:Namespace Turing ⍝ Run Turing machine until it halts ∇r←RunTuring (rules init halts blank itape);state;rt;lt;next state←init lt←⍬ rt←,blank  :If 0≠≢itape ⋄ rt←itape ⋄ :EndIf  :While ~(⊂state)∊halts next←((⊂state(⊃rt))≡¨↓rules[;⍳2])⌿rules 'No rule applies!'⎕SIGNAL(0=≢next)/11 (⊃rt)←⊃next[1;3] state←⊃next[1;5]  :Select ⊃next[1;4]  :Case 'stay' ⋄ ⍝nothing  :Case 'right' lt,⍨←⊃rt rt←1↓rt  :If 0=≢rt ⋄ rt←,blank ⋄ :EndIf  :Case 'left'  :If 0=≢lt ⋄ lt←,blank ⋄ :EndIf rt,⍨←⊃lt lt←1↓lt  :Else 'Invalid action'⎕SIGNAL 11  :EndSelect  :EndWhile r←(⌽lt),rt ∇   ⍝ Display the resulting tape neatly ∇r←len Display t r←(len⌊≢t)↑t →(len≥≢t)/0 r,←'... (total length: ',(⍕≢t),')' ∇   ⍝ Simple incrementer ∇t←∆1_SimpleIncrementer t ←⊂'q0' '1' '1' 'right' 'q0' t,←⊂'q0' 'B' '1' 'stay' 'qf' t←(↑t) 'q0' (,⊂'qf') 'B' '111' ∇   ⍝ Three state beaver ∇t←∆2_ThreeStateBeaver t ←⊂'a' '0' '1' 'right' 'b' t,←⊂'a' '1' '1' 'left' 'c' t,←⊂'b' '0' '1' 'left' 'a' t,←⊂'b' '1' '1' 'right' 'b' t,←⊂'c' '0' '1' 'left' 'b' t,←⊂'c' '1' '1' 'stay' 'halt' t←(↑t) 'a' (,⊂'halt') '0' '' ∇   ⍝ Five state beaver ∇t←∆3_FiveStateBeaver t ←⊂'A' '0' '1' 'right' 'B' t,←⊂'A' '1' '1' 'left' 'C' t,←⊂'B' '0' '1' 'right' 'C' t,←⊂'B' '1' '1' 'right' 'B' t,←⊂'C' '0' '1' 'right' 'D' t,←⊂'C' '1' '0' 'left' 'E' t,←⊂'D' '0' '1' 'left' 'A' t,←⊂'D' '1' '1' 'left' 'D' t,←⊂'E' '0' '1' 'stay' 'H' t,←⊂'E' '1' '0' 'left' 'A' t←(↑t) 'A' (,⊂'H') '0' '' ∇   ⍝ Run all of them and display the results ∇RunAll;m;ms ms←('∆'=⊃¨ms)/ms←⎕NL¯3  :For m :In ms ⎕←(1↓m),': ',(32 Display RunTuring ⍎m)  :EndFor ∇ :EndNamespace
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.
#ActionScript
ActionScript
trace("Radians:"); trace("sin(Pi/4) = ", Math.sin(Math.PI/4)); trace("cos(Pi/4) = ", Math.cos(Math.PI/4)); trace("tan(Pi/4) = ", Math.tan(Math.PI/4)); trace("arcsin(0.5) = ", Math.asin(0.5)); trace("arccos(0.5) = ", Math.acos(0.5)); trace("arctan(0.5) = ", Math.atan(0.5)); trace("arctan2(-1,-2) = ", Math.atan2(-1,-2)); trace("\nDegrees") trace("sin(45) = ", Math.sin(45 * Math.PI/180)); trace("cos(45) = ", Math.cos(45 * Math.PI/180)); trace("tan(45) = ", Math.tan(45 * Math.PI/180)); trace("arcsin(0.5) = ", Math.asin(0.5)*180/Math.PI); trace("arccos(0.5) = ", Math.acos(0.5)*180/Math.PI); trace("arctan(0.5) = ", Math.atan(0.5)*180/Math.PI); trace("arctan2(-1,-2) = ", Math.atan2(-1,-2)*180/Math.PI);  
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm. From the wikipedia entry: ask for 11 numbers to be read into a sequence S reverse sequence S for each item in sequence S result := call a function to do an operation if result overflows alert user else print result The task is to implement the algorithm: Use the function:     f ( x ) = | x | 0.5 + 5 x 3 {\displaystyle f(x)=|x|^{0.5}+5x^{3}} The overflow condition is an answer of greater than 400. The 'user alert' should not stop processing of other items of the sequence. Print a prompt before accepting eleven, textual, numeric inputs. You may optionally print the item as well as its associated result, but the results must be in reverse order of input. The sequence   S   may be 'implied' and so not shown explicitly. Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#Agena
Agena
scope # TPK algorithm in Agena local y; local a := []; local f := proc( t :: number ) is return sqrt(abs(t))+5*t*t*t end; for i from 0 to 10 do a[i] := tonumber( io.read() ) od; for i from 10 to 0 by - 1 do y:=f(a[i]); if y > 400 then print( "TOO LARGE" ) else printf( "%10.4f\n", y ) fi od epocs
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).
#ALGOL_60
ALGOL 60
begin integer i; real y; real array a[0:10]; real procedure f(t); value t; real t; f:=sqrt(abs(t))+5*t^3; for i:=0 step 1 until 10 do inreal(0, a[i]); for i:=10 step -1 until 0 do begin y:=f(a[i]); if y > 400 then outstring(1, "TOO LARGE") else outreal(1,y); outchar(1, "\n", 1) end end
http://rosettacode.org/wiki/Tree_from_nesting_levels
Tree from nesting levels
Given a flat list of integers greater than zero, representing object nesting levels, e.g. [1, 2, 4], generate a tree formed from nested lists of those nesting level integers where: Every int appears, in order, at its depth of nesting. If the next level int is greater than the previous then it appears in a sub-list of the list containing the previous item The generated tree data structure should ideally be in a languages nested list format that can be used for further calculations rather than something just calculated for printing. An input of [1, 2, 4] should produce the equivalent of: [1, [2, [[4]]]] where 1 is at depth1, 2 is two deep and 4 is nested 4 deep. [1, 2, 4, 2, 2, 1] should produce [1, [2, [[4]], 2, 2], 1]. All the nesting integers are in the same order but at the correct nesting levels. Similarly [3, 1, 3, 1] should generate [[[3]], 1, [[3]], 1] Task Generate and show here the results for the following inputs: [] [1, 2, 4] [3, 1, 3, 1] [1, 2, 3, 1] [3, 2, 1, 3] [3, 3, 3, 1, 1, 3, 3, 3]
#Phix
Phix
function test(sequence s, integer level=1, idx=1) sequence res = {}, part while idx<=length(s) do switch compare(s[idx],level) do case +1: {idx,part} = test(s,level+1,idx) res = append(res,part) case 0: res &= s[idx] case -1: idx -= 1 exit end switch idx += 1 end while return iff(level=1?res:{idx,res}) end function constant tests = {{}, {1, 2, 4}, -- {1, 2, 4, 2, 2, 1}, -- (fine too) {3, 1, 3, 1}, {1, 2, 3, 1}, {3, 2, 1, 3}, {3, 3, 3, 1, 1, 3, 3, 3}} for i=1 to length(tests) do sequence ti = tests[i], res = test(ti), rpp = ppf(res,{pp_Nest,3,pp_Indent,4}) printf(1,"%v nests to %v\n or %s\n",{ti,res,rpp}) end for
http://rosettacode.org/wiki/Twelve_statements
Twelve statements
This puzzle is borrowed from   math-frolic.blogspot. Given the following twelve statements, which of them are true? 1. This is a numbered list of twelve statements. 2. Exactly 3 of the last 6 statements are true. 3. Exactly 2 of the even-numbered statements are true. 4. If statement 5 is true, then statements 6 and 7 are both true. 5. The 3 preceding statements are all false. 6. Exactly 4 of the odd-numbered statements are true. 7. Either statement 2 or 3 is true, but not both. 8. If statement 7 is true, then 5 and 6 are both true. 9. Exactly 3 of the first 6 statements are true. 10. The next two statements are both true. 11. Exactly 1 of statements 7, 8 and 9 are true. 12. Exactly 4 of the preceding statements are true. Task When you get tired of trying to figure it out in your head, write a program to solve it, and print the correct answer or answers. Extra credit Print out a table of near misses, that is, solutions that are contradicted by only a single statement.
#Go
Go
package main   import "fmt"   // its' not too much more work to check all the permutations concurrently var solution = make(chan int) var nearMiss = make(chan int) var done = make(chan bool)   func main() { // iterate and use the bits as the permutation for i := 0; i < 4096; i++ { go checkPerm(i) } // collect the misses and list them after the complete solution(s) var ms []int for i := 0; i < 4096; { select { case <-done: i++ case s := <-solution: print12("solution", s) case m := <-nearMiss: ms = append(ms, m) } } for _, m := range ms { print12("near miss", m) } }   func print12(label string, bits int) { fmt.Print(label, ":") for i := 1; i <= 12; i++ { if bits&1 == 1 { fmt.Print(" ", i) } bits >>= 1 } fmt.Println() }   func checkPerm(tz int) { // closure returns true if tz bit corresponding to // 1-based statement number is 1. ts := func(n uint) bool { return tz>>(n-1)&1 == 1 } // variadic closure returns number of statements listed as arguments // which have corresponding tz bit == 1. ntrue := func(xs ...uint) int { nt := 0 for _, x := range xs { if ts(x) { nt++ } } return nt } // a flag used on repeated calls to test. // set to true when first contradiction is found. // if another is found, this function (checkPerm) can "short circuit" // and return immediately without checking additional statements. var con bool // closure called to test each statement test := func(statement uint, b bool) { switch { case ts(statement) == b: case con: panic("bail") default: con = true } } // short circuit mechanism defer func() { if x := recover(); x != nil { if msg, ok := x.(string); !ok && msg != "bail" { panic(x) } } done <- true }()   // 1. This is a numbered list of twelve statements. test(1, true)   // 2. Exactly 3 of the last 6 statements are true. test(2, ntrue(7, 8, 9, 10, 11, 12) == 3)   // 3. Exactly 2 of the even-numbered statements are true. test(3, ntrue(2, 4, 6, 8, 10, 12) == 2)   // 4. If statement 5 is true, then statements 6 and 7 are both true. test(4, !ts(5) || ts(6) && ts(7))   // 5. The 3 preceding statements are all false. test(5, !ts(4) && !ts(3) && !ts(2))   // 6. Exactly 4 of the odd-numbered statements are true. test(6, ntrue(1, 3, 5, 7, 9, 11) == 4)   // 7. Either statement 2 or 3 is true, but not both. test(7, ts(2) != ts(3))   // 8. If statement 7 is true, then 5 and 6 are both true. test(8, !ts(7) || ts(5) && ts(6))   // 9. Exactly 3 of the first 6 statements are true. test(9, ntrue(1, 2, 3, 4, 5, 6) == 3)   // 10. The next two statements are both true. test(10, ts(11) && ts(12))   // 11. Exactly 1 of statements 7, 8 and 9 are true. test(11, ntrue(7, 8, 9) == 1)   // 12. Exactly 4 of the preceding statements are true. test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4)   // no short circuit? send permutation as either near miss or solution if con { nearMiss <- tz } else { solution <- tz } }
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.
#Go
Go
package main   import ( "bufio" "errors" "fmt" "go/ast" "go/parser" "go/token" "os" "reflect" )   func main() { in := bufio.NewScanner(os.Stdin) for { fmt.Print("Expr: ") in.Scan() if err := in.Err(); err != nil { fmt.Println(err) return } if !tt(in.Text()) { return } } }   func tt(expr string) bool { // call library parser tree, err := parser.ParseExpr(expr) if err != nil { fmt.Println(err) return false } // create handy object to pass around e := &evaluator{nil, map[string]bool{}, tree} // library tree traversal function calls e.Visit for each node. // use this to collect variables of the expression. ast.Walk(e, tree) // print headings for truth table for _, n := range e.names { fmt.Printf("%-6s", n) } fmt.Println(" ", expr) // start recursive table generation function on first variable e.evalVar(0) return true }   type evaluator struct { names []string // variables, in order of appearance val map[string]bool // map variables to boolean values tree ast.Expr // parsed expression as ast }   // visitor function called by library Walk function. // builds a list of unique variable names. func (e *evaluator) Visit(n ast.Node) ast.Visitor { if id, ok := n.(*ast.Ident); ok { if !e.val[id.Name] { e.names = append(e.names, id.Name) e.val[id.Name] = true } } return e }   // method recurses for each variable of the truth table, assigning it to // false, then true. At bottom of recursion, when all variables are // assigned, it evaluates the expression and outputs one line of the // truth table func (e *evaluator) evalVar(nx int) bool { if nx == len(e.names) { // base case v, err := evalNode(e.tree, e.val) if err != nil { fmt.Println(" ", err) return false } // print variable values for _, n := range e.names { fmt.Printf("%-6t", e.val[n]) } // print expression value fmt.Println(" ", v) return true } // recursive case for _, v := range []bool{false, true} { e.val[e.names[nx]] = v if !e.evalVar(nx + 1) { return false } } return true }   // recursively evaluate ast func evalNode(nd ast.Node, val map[string]bool) (bool, error) { switch n := nd.(type) { case *ast.Ident: return val[n.Name], nil case *ast.BinaryExpr: x, err := evalNode(n.X, val) if err != nil { return false, err } y, err := evalNode(n.Y, val) if err != nil { return false, err } switch n.Op { case token.AND: return x && y, nil case token.OR: return x || y, nil case token.XOR: return x != y, nil default: return unsup(n.Op) } case *ast.UnaryExpr: x, err := evalNode(n.X, val) if err != nil { return false, err } switch n.Op { case token.XOR: return !x, nil default: return unsup(n.Op) } case *ast.ParenExpr: return evalNode(n.X, val) } return unsup(reflect.TypeOf(nd)) }   func unsup(i interface{}) (bool, error) { return false, errors.New(fmt.Sprintf("%v unsupported", i)) }  
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
#J
J
spiral =: ,~ $ [: /: }.@(2 # >:@i.@-) +/\@# <:@+: $ (, -)@(1&,)
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 739, 73, and 7 formed by removing digits from its right are also prime. No zeroes are allowed in truncatable primes. Task The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied). Related tasks Find largest left truncatable prime in a given base Sieve of Eratosthenes See also Truncatable Prime from MathWorld.]
#Clojure
Clojure
(use '[clojure.contrib.lazy-seqs :only [primes]])   (def prime? (let [mem (ref #{}) primes (ref primes)] (fn [n] (dosync (if (< n (first @primes)) (@mem n) (let [[mems ss] (split-with #(<= % n) @primes)] (ref-set primes ss) ((commute mem into mems) n)))))))   (defn drop-lefts [n] (let [dropl #(if (< % 10) 0 (Integer. (subs (str %) 1)))] (->> (iterate dropl n) (take-while pos? ,) next)))   (defn drop-rights [n] (->> (iterate #(quot % 10) n) next (take-while pos? ,)))   (defn truncatable-left? [n] (every? prime? (drop-lefts n)))   (defn truncatable-right? [n] (every? prime? (drop-rights n)))   user> (->> (for [p primes  :while (< p 1000000)  :when (not-any? #{\0} (str p))  :let [l? (if (truncatable-left? p) p 0) r? (if (truncatable-right? p) p 0)]  :when (or l? r?)] [l? r?]) ((juxt #(apply max-key first %) #(apply max-key second %)) ,) ((juxt ffirst (comp second second)) ,) (map vector ["left truncatable: " "right truncatable: "] ,)) (["left truncatable: " 998443] ["right truncatable: " 739399])
http://rosettacode.org/wiki/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive. Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes. For N over its range, generate and show counts of the outputs of randN and unbiased(randN). The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN. This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
#Wren
Wren
import "random" for Random import "/fmt" for Fmt   var rand = Random.new()   var biased = Fn.new { |n| rand.float() < 1 / n }   var unbiased = Fn.new { |n| while (true) { var a = biased.call(n) var b = biased.call(n) if (a != b) return a } }   var m = 50000 var f = "$d: $2.2f\% $2.2f\%" for (n in 3..6) { var c1 = 0 var c2 = 0 for (i in 0...m) { if (biased.call(n)) c1 = c1 + 1 if (unbiased.call(n)) c2 = c2 + 1 } Fmt.print(f, n, 100 * c1 / m, 100 * c2 / m) }
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#PowerBASIC
PowerBASIC
SUB truncateFile (file AS STRING, length AS DWORD) IF LEN(DIR$(file)) THEN DIM f AS LONG f = FREEFILE OPEN file FOR BINARY AS f IF length > LOF(f) THEN CLOSE f ERROR 62 'Input past end ELSE SEEK f, length + 1 SETEOF f CLOSE f END IF ELSE ERROR 53 'File not found END IF END SUB
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#Powershell
Powershell
Function Truncate-File(fname) { $null | Set-Content -Path "$fname" }  
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#PureBasic
PureBasic
Procedure SetFileSize(File$, length.q) Protected fh, pos, i If FileSize(File$) < length Debug "File to small, is a directory or does not exist." ProcedureReturn #False Else fh = OpenFile(#PB_Any, File$) FileSeek(fh, length) TruncateFile(fh) CloseFile(fh) EndIf ProcedureReturn #True EndProcedure
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.
#AutoHotkey
AutoHotkey
; By Uberi, http://www.autohotkey.com/board/topic/58599-turing-machine/ SetBatchLines, -1 OnExit, Exit SaveFilePath := A_ScriptFullPath ".ini" ; Defaults are for a 2-state_3-symbol turning machine. Format: ; machine state symbol on tape, symbol on tape | tape shift (- is left, + is right, 0 is halt) | machine state , Rule1 := "A0,1|1|B" , Rule2 := "A1,2|-1|A" , Rule3 := "A2,1|-1|A" , Rule4 := "B0,2|-1|A" , Rule5 := "B1,2|1|B" , Rule6 := "B2,0|1|A" ; no error check is run on this input, so be sure states and symbols align with actions IniRead, UseSaveFile, %SaveFilePath%, Global, UseSaveFile, 1 ; on exit, save state to text file so I can resume on next run IniRead, MaxIterations, %SaveFilePath%, Global, MaxIterations, 100000 ; set as %A_Space% to run indefinitely IniRead, Section, %SaveFilePath%, Global, Section, 2-state_3-symbol ; The name of the machine to run. Options defined: ; 2-state_3-symbol ; Simple_incrementer ; Three-state_busy_beaver ; Probable_busy_beaver_Wikipedia   IniRead, States, %SaveFilePath%, %Section%, States, A|B ; valid states IniRead, InitialState, %SaveFilePath%, %Section%, InitialState, A ; start state IniRead, TerminalState, %SaveFilePath%, %Section%, TerminalState, C ; end state IniRead, Symbols, %SaveFilePath%, %Section%, Symbols, 0,1,2 ; valid symbols IniRead, DefaultCell, %SaveFilePath%, %Section%, DefaultCell, 0 ; the default symbol of any cell not defined on input tape IniRead, ProgramCode, %SaveFilePath%, %Section%, ProgramCode, 10101|01010 ; start tape Iniread, RuleCount, %SaveFilePath%, %Section%, RuleCount, 6 ; number of actions to read Loop, %RuleCount% { IniRead, Temp1, %SaveFilePath%, %Section%, Rule%A_Index%, % Rule%A_Index% StringSplit, Temp, Temp1, `, Action%Temp1% := Temp2 }   IniRead, Index, %SaveFilePath%, SavedState, Index, 0 IniRead, IterationCount, %SaveFilePath%, SavedState, IterationCount, 0 IniRead, State, %SaveFilePath%, SavedState, State, %InitialState% If IterationCount > 0 IniRead, ProgramCode, %SaveFilePath%, SavedState, ProgramCode, %ProgramCode%   IfNotInString, ProgramCode, | ProgramCode := "|" ProgramCode StringSplit, Temp, ProgramCode, | NegativeCells := Temp1, PositiveCells := Temp2   Loop, Parse, Symbols, | Color%A_LoopField% := hex(mod((A_Index+1/(2**((A_Index-1)//7))-1)/7,1)*16777215) ; unlimited number of unique colors Color%DefaultCell% := "White"   Gui, Color, Black Gui, +ToolWindow +AlwaysOnTop +LastFound -Caption WindowID := WinExist() OnMessage(0x201, "WM_LBUTTONDOWN") Gui, Font, s6 cWhite, Arial Loop, 61 ; display 30 cell symbols on each side of current index { Temp1 := ((A_Index - 1) * 15) + 1 Gui, Add, Progress, x%Temp1% y1 w14 h40 vCell%A_Index% BackgroundWhite Gui, Add, Text, x%Temp1% y42 w15 h10 vLabel%A_Index% Center } Gui, Add, Text, x2 y54 w26 h10 vState Gui, Add, Text, x35 y54 w50 h10 vCurrentCell Gui, Add, Text, x350 y54 w158 h10 vActions Gui, Add, Text, x844 y54 w33 h10, Iterations: Gui, Add, Text, x884 y54 w29 h10 vIterations Right Gui, Font, s4 cWhite Bold, Arial Gui, Add, Text, x450 y1 w15 h10 Center, V GuiControl, Move, Cell31, x451 y8 w14 h33 Gui, Show, y20 w916 h64, Wolfram's 2-State 3-Symbol Turing Machine ;'   ;MaxIndex := ProgramOffset + StrLen(ProgramCode), MinIndex := ProgramOffset ; not implemented While, ((MaxIterations = "") || IterationCount <= MaxIterations) ; process until limit is reached, if any { Loop, 61 ; color each cell per its current symbol { ; must run for all displayed cells because they are not directly mapped to shifting tape TempIndex := (Index + A_Index) - 31 GuiControl, , Label%A_Index%, %TempIndex% CellColor := CellGet(TempIndex) , CellColor := Color%CellColor% GuiControl, +Background%CellColor%, Cell%A_Index% } CurrentCell := CellGet(Index) GuiControl, , State, State: %State% GuiControl, , CurrentCell, Current Cell: %CurrentCell% GuiControl, , Iterations, %IterationCount% If (State = TerminalState) Break   StringSplit, Temp, Action%State%%CurrentCell%, | GuiControl, , Actions, % "Actions: Print " . Temp1 . ", Move " . ((Temp2 = -1) ? "left" : "right") . ", " . ((State <> Temp3) ? "Switch to state " . Temp3 : "Do not switch state")   IterationCount++ , CellPut(Index,Temp1) , Index += Temp2 , State := Temp3 ;, (Index > MaxIndex) ? MaxIndex := Index : "" ;, (Index < MinIndex) ? MinIndex := Index : ""   Sleep, 0.1*1000 } MsgBox, 64, Complete, Completed %IterationCount% iterations of the Turing machine. Return     ; Hotkeys and functions: ~Pause::Pause   GuiEscape: GuiClose: ExitApp   Exit: If UseSaveFile { IniWrite, %Index%, %SaveFilePath%, %Section%, Index IniWrite, %IterationCount%, %SaveFilePath%, %Section%, IterationCount IniWrite, %State%, %SaveFilePath%, %Section%, State IniWrite, %NegativeCells%|%PositiveCells%, %SaveFilePath%, %Section%, ProgramCode } ExitApp   CellGet(Index) { global NegativeCells, PositiveCells, DefaultCell Temp1 := (Index < 0) ? SubStr(NegativeCells,Abs(Index),1) : SubStr(PositiveCells,Index + 1,1) Return, (Temp1 = "") ? DefaultCell : Temp1 }   CellPut(Index,Char) { global NegativeCells, PositiveCells, DefaultCell static StrGetFunc := "StrGet" ; workaround to hide function from AHK Basic (which does not have or require it) CharType := A_IsUnicode ? "UShort" : "UChar" , (Index < 0) ? (Index := 0 - Index , Temp1 := Index - StrLen(NegativeCells) , (Temp1 > 0) ? (VarSetCapacity(Pad,64) ; these three functions are quirks in AHK's memory management (not required) , VarSetCapacity(Pad,0) , VarSetCapacity(Pad,Temp1,Asc(DefaultCell)) , NegativeCells .= A_IsUnicode ? %StrGetFunc%(&Pad,Temp1,"CP0") : Pad) : "" , NumPut(Asc(Char),NegativeCells,(Index - 1) << !!A_IsUnicode,CharType) ) : (Temp1 := Index - StrLen(PositiveCells) + 1 , (Temp1 > 0) ? (VarSetCapacity(Pad,64) ; these three functions are quirks in AHK's memory management (not required) , VarSetCapacity(Pad,0) , VarSetCapacity(Pad,Temp1,Asc(DefaultCell)) , PositiveCells .= A_IsUnicode ? %StrGetFunc%(&Pad,Temp1,"CP0") : Pad) : "" , NumPut(Asc(Char),PositiveCells,Index << !!A_IsUnicode,CharType) ) }   Hex(p_Integer) { PtrType:=(A_PtrSize=8) ? "Ptr":"UInt" l_Format:="`%0" . 6 . "I64X" VarSetCapacity(l_Argument,8) NumPut(p_Integer,l_Argument,0,"Int64") VarSetCapacity(l_Buffer,A_IsUnicode ? 12:6,0) DllCall(A_IsUnicode ? "msvcrt\_vsnwprintf":"msvcrt\_vsnprintf" ,"Str",l_Buffer ;-- Storage location for output ,"UInt",6 ;-- Maximum number of characters to write ,"Str",l_Format ;-- Format specification ,PtrType,&l_Argument) ;-- Argument Return l_Buffer }   WM_LBUTTONDOWN() { If (A_Gui = 1) PostMessage, 0xA1, 2 }
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.
#Ada
Ada
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; with Ada.Float_Text_Io; use Ada.Float_Text_Io; with Ada.Text_IO; use Ada.Text_IO;   procedure Trig is Degrees_Cycle : constant Float := 360.0; Radians_Cycle : constant Float := 2.0 * Ada.Numerics.Pi; Angle_Degrees : constant Float := 45.0; Angle_Radians : constant Float := Ada.Numerics.Pi / 4.0; procedure Put (V1, V2 : Float) is begin Put (V1, Aft => 5, Exp => 0); Put (" "); Put (V2, Aft => 5, Exp => 0); New_Line; end Put; begin Put (Sin (Angle_Degrees, Degrees_Cycle), Sin (Angle_Radians, Radians_Cycle)); Put (Cos (Angle_Degrees, Degrees_Cycle), Cos (Angle_Radians, Radians_Cycle)); Put (Tan (Angle_Degrees, Degrees_Cycle), Tan (Angle_Radians, Radians_Cycle)); Put (Cot (Angle_Degrees, Degrees_Cycle), Cot (Angle_Radians, Radians_Cycle)); Put (ArcSin (Sin (Angle_Degrees, Degrees_Cycle), Degrees_Cycle), ArcSin (Sin (Angle_Radians, Radians_Cycle), Radians_Cycle)); Put (Arccos (Cos (Angle_Degrees, Degrees_Cycle), Degrees_Cycle), Arccos (Cos (Angle_Radians, Radians_Cycle), Radians_Cycle)); Put (Arctan (Y => Tan (Angle_Degrees, Degrees_Cycle)), Arctan (Y => Tan (Angle_Radians, Radians_Cycle))); Put (Arccot (X => Cot (Angle_Degrees, Degrees_Cycle)), Arccot (X => Cot (Angle_Degrees, Degrees_Cycle))); end 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).
#ALGOL_68
ALGOL 68
[ 0 : 10 ]REAL a; PROC f = ( REAL t )REAL: sqrt(ABS t)+5*t*t*t; FOR i FROM LWB a TO UPB a DO read( ( a[ i ] ) ) OD; FOR i FROM UPB a BY -1 TO LWB a DO REAL y=f(a[i]); IF y > 400 THEN print( ( "TOO LARGE", newline ) ) ELSE print( ( fixed( y, -9, 4 ), newline ) ) FI OD
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).
#ALGOL_W
ALGOL W
begin real y; real array a( 0 :: 10 ); real procedure f( real value t ); sqrt(abs(t))+5*t*t*t; for i:=0 until 10 do read( a(i) ); r_format := "A"; r_w := 9; r_d := 4; for i:=10 step -1 until 0 do begin y:=f(a(i)); if y > 400 then write( "TOO LARGE" ) else write( y ); end end.
http://rosettacode.org/wiki/Tree_from_nesting_levels
Tree from nesting levels
Given a flat list of integers greater than zero, representing object nesting levels, e.g. [1, 2, 4], generate a tree formed from nested lists of those nesting level integers where: Every int appears, in order, at its depth of nesting. If the next level int is greater than the previous then it appears in a sub-list of the list containing the previous item The generated tree data structure should ideally be in a languages nested list format that can be used for further calculations rather than something just calculated for printing. An input of [1, 2, 4] should produce the equivalent of: [1, [2, [[4]]]] where 1 is at depth1, 2 is two deep and 4 is nested 4 deep. [1, 2, 4, 2, 2, 1] should produce [1, [2, [[4]], 2, 2], 1]. All the nesting integers are in the same order but at the correct nesting levels. Similarly [3, 1, 3, 1] should generate [[[3]], 1, [[3]], 1] Task Generate and show here the results for the following inputs: [] [1, 2, 4] [3, 1, 3, 1] [1, 2, 3, 1] [3, 2, 1, 3] [3, 3, 3, 1, 1, 3, 3, 3]
#Python
Python
def to_tree(x, index=0, depth=1): so_far = [] while index < len(x): this = x[index] if this == depth: so_far.append(this) elif this > depth: index, deeper = to_tree(x, index, depth + 1) so_far.append(deeper) else: # this < depth: index -=1 break index += 1 return (index, so_far) if depth > 1 else so_far     if __name__ == "__main__": from pprint import pformat   def pnest(nest:list, width: int=9) -> str: text = pformat(nest, width=width).replace('\n', '\n ') print(f" OR {text}\n")   exercises = [ [], [1, 2, 4], [3, 1, 3, 1], [1, 2, 3, 1], [3, 2, 1, 3], [3, 3, 3, 1, 1, 3, 3, 3], ] for flat in exercises: nest = to_tree(flat) print(f"{flat} NESTS TO: {nest}") pnest(nest)
http://rosettacode.org/wiki/Twelve_statements
Twelve statements
This puzzle is borrowed from   math-frolic.blogspot. Given the following twelve statements, which of them are true? 1. This is a numbered list of twelve statements. 2. Exactly 3 of the last 6 statements are true. 3. Exactly 2 of the even-numbered statements are true. 4. If statement 5 is true, then statements 6 and 7 are both true. 5. The 3 preceding statements are all false. 6. Exactly 4 of the odd-numbered statements are true. 7. Either statement 2 or 3 is true, but not both. 8. If statement 7 is true, then 5 and 6 are both true. 9. Exactly 3 of the first 6 statements are true. 10. The next two statements are both true. 11. Exactly 1 of statements 7, 8 and 9 are true. 12. Exactly 4 of the preceding statements are true. Task When you get tired of trying to figure it out in your head, write a program to solve it, and print the correct answer or answers. Extra credit Print out a table of near misses, that is, solutions that are contradicted by only a single statement.
#Groovy
Groovy
enum Rule { r01( 1, { r()*.num == (1..12) }), r02( 2, { r(7..12).count { it.truth } == 3 }), r03( 3, { r(2..12, 2).count { it.truth } == 2 }), r04( 4, { r(5).truth ? r(6).truth && r(7).truth : true }), r05( 5, { r(2..4).count { it.truth } == 0 }), r06( 6, { r(1..11, 2).count { it.truth } == 4 }), r07( 7, { r(2).truth != r(3).truth }), r08( 8, { r(7).truth ? r(5).truth && r(6).truth : true }), r09( 9, { r(1..6).count { it.truth } == 3 }), r10(10, { r(11).truth && r(12).truth }), r11(11, { r(7..9).count { it.truth } == 1 }), r12(12, { r(1..11).count { it.truth } == 4 });   final int num final Closure statement boolean truth   static final List<Rule> rules = [ null, r01, r02, r03, r04, r05, r06, r07, r08, r09, r10, r11, r12]   private Rule(num, statement) { this.num = num this.statement = statement }   public static Rule r(int index) { rules[index] } public static List<Rule> r() { rules[1..12] } public static List<Rule> r(List<Integer> indices) { rules[indices] } public static List<Rule> r(IntRange indices) { rules[indices] } public static List<Rule> r(IntRange indices, int step) { r(indices.step(step)) }   public static void setAllTruth(int bits) { (1..12).each { r(it).truth = !(bits & (1 << (12 - it))) } }   public static void evaluate() { def nearMisses = [:] (0..<(2**12)).each { i -> setAllTruth(i) def truthCandidates = r().findAll { it.truth } def truthMatchCount = r().count { it.statement() == it.truth } if (truthMatchCount == 12) { println ">Solution< ${truthCandidates*.num}" } else if (truthMatchCount == 11) { def miss = (1..12).find { r(it).statement() != r(it).truth } nearMisses << [(truthCandidates): miss] } } nearMisses.each { truths, miss -> printf ("Near Miss: %-21s (failed %2d)\n", "${truths*.num}", miss) } } }   Rule.evaluate()
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.
#Haskell
Haskell
import Control.Monad (mapM, foldM, forever) import Data.List (unwords, unlines, nub) import Data.Maybe (fromJust)   truthTable expr = let tokens = words expr operators = ["&", "|", "!", "^", "=>"] variables = nub $ filter (not . (`elem` operators)) tokens table = zip variables <$> mapM (const [True,False]) variables results = map (\r -> (map snd r) ++ (calculate tokens) r) table header = variables ++ ["result"] in showTable $ header : map (map show) results   -- Performs evaluation of token sequence in a given context. -- The context is an assoc-list, which binds variable and it's value. -- Here the monad is simple ((->) r). calculate :: [String] -> [(String, Bool)] -> [Bool] calculate = foldM interprete [] where interprete (x:y:s) "&" = (: s) <$> pure (x && y) interprete (x:y:s) "|" = (: s) <$> pure (x || y) interprete (x:y:s) "^" = (: s) <$> pure (x /= y) interprete (x:y:s) "=>" = (: s) <$> pure (not y || x) interprete (x:s) "!" = (: s) <$> pure (not x) interprete s var = (: s) <$> fromJust . lookup var   -- pretty printing showTable tbl = unlines $ map (unwords . map align) tbl where align txt = take colWidth $ txt ++ repeat ' ' colWidth = max 6 $ maximum $ map length (head tbl)   main = forever $ getLine >>= putStrLn . truthTable
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
#Java
Java
import java.util.Arrays;   public class Ulam{ enum Direction{ RIGHT, UP, LEFT, DOWN; }   private static String[][] genUlam(int n){ return genUlam(n, 1); }   private static String[][] genUlam(int n, int i){ String[][] spiral = new String[n][n]; Direction dir = Direction.RIGHT; int j = i; int y = n / 2; int x = (n % 2 == 0) ? y - 1 : y; //shift left for even n's while(j <= ((n * n) - 1 + i)){ spiral[y][x] = isPrime(j) ? String.format("%4d", j) : " ---";   switch(dir){ case RIGHT: if(x <= (n - 1) && spiral[y - 1][x] == null && j > i) dir = Direction.UP; break; case UP: if(spiral[y][x - 1] == null) dir = Direction.LEFT; break; case LEFT: if(x == 0 || spiral[y + 1][x] == null) dir = Direction.DOWN; break; case DOWN: if(spiral[y][x + 1] == null) dir = Direction.RIGHT; break; }   switch(dir){ case RIGHT: x++; break; case UP: y--; break; case LEFT: x--; break; case DOWN: y++; break; } j++; } return spiral; }   public static boolean isPrime(int a){ if(a == 2) return true; if(a <= 1 || a % 2 == 0) return false; long max = (long)Math.sqrt(a); for(long n = 3; n <= max; n += 2){ if(a % n == 0) return false; } return true; }   public static void main(String[] args){ String[][] ulam = genUlam(9); for(String[] row : ulam){ System.out.println(Arrays.toString(row).replaceAll(",", "")); } System.out.println();   for(String[] row : ulam){ System.out.println(Arrays.toString(row).replaceAll("\\[\\s+\\d+", "[ * ").replaceAll("\\s+\\d+", " * ").replaceAll(",", "")); } } }
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.]
#CoffeeScript
CoffeeScript
# You could have symmetric algorithms for max right and left # truncatable numbers, but they lend themselves to slightly # different optimizations.   max_right_truncatable_number = (n, f) -> # This algorithm only evaluates 37 numbers for primeness to # get the max right truncatable prime < 1000000. Its # optimization is that it prunes candidates for # the first n-1 digits before having to iterate through # the 10 possibilities for the last digit. if n < 10 candidate = n while candidate > 0 return candidate if f(candidate) candidate -= 1 else left = Math.floor n / 10 while left > 0 left = max_right_truncatable_number left, f right = 9 while right > 0 candidate = left * 10 + right return candidate if candidate <= n and f(candidate) right -= 1 left -= 1 throw Error "none found"   max_left_truncatable_number = (max, f) -> # This is a pretty straightforward countdown. The first # optimization here would probably be to cache results of # calling f on small numbers. is_left_truncatable = (n) -> candidate = 0 power_of_ten = 1 while n > 0 r = n % 10 return false if r == 0 n = Math.floor n / 10 candidate = r * power_of_ten + candidate power_of_ten *= 10 return false unless f(candidate) true do -> n = max while n > 0 return n if is_left_truncatable n, f n -= 1 throw Error "none found"   is_prime = (n) -> return false if n == 1 return true if n == 2 for d in [2..n] return false if n % d == 0 return true if d * d >= n     console.log "right", max_right_truncatable_number(999999, is_prime) console.log "left", max_left_truncatable_number(999999, is_prime)  
http://rosettacode.org/wiki/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive. Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes. For N over its range, generate and show counts of the outputs of randN and unbiased(randN). The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN. This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
#zkl
zkl
fcn randN(N){ (not (0).random(N)).toInt() } fcn unbiased(randN){ while((a:=randN())==randN()){} a }
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#Python
Python
  def truncate_file(name, length): if not os.path.isfile(name): return False if length >= os.path.getsize(name): return False with open(name, 'ab') as f: f.truncate(length) return True  
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#R
R
  truncate_file <- function(filename, n_bytes) {   # check file exists and size is greater than n_bytes stopifnot( "file does not exist"= file.exists(filename), "not enough bytes in file"= file.size(filename) >= n_bytes )   # read bytes from input file input.con <- file(filename, "rb") bindata <- readBin(input.con, integer(), n=n_bytes/4) close(input.con)   # write bytes to temporary file tmp.filename <- tempfile() output.con <- file(tmp.filename, "wb") writeBin(bindata, output.con) close(output.con)   # double check that everything worked before overwriting original file stopifnot( "temp file is not expected size"= file.size(tmp.filename) == n_bytes )   # overwrite input file with temporary file file.rename(tmp.filename, filename)   }  
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#Racket
Racket
  #lang racket   (define (truncate file size) (unless (file-exists? file) (error 'truncat "missing file: ~a" file)) (when (> size (file-size file)) (printf "Warning: extending file size.\n")) (call-with-output-file* file #:exists 'update (λ(o) (file-truncate o size))))  
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.
#BASIC
BASIC
• R$(), an array of rules; • T$, an input tape (where an empty string stands for a blank tape); • B$, a character to use as a blank; • S$, an initial state; • H$, a halting state.
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).
#11l
11l
F f(n) R sum((1..n).filter(k -> gcd(@n, k) == 1).map(k -> 1))   F is_prime(n) R f(n) == n - 1   L(n) 1..25 print(‘ f(#.) == #.’.format(n, f(n))‘’(I is_prime(n) {‘, is prime’} E ‘’)) V count = 0 L(n) 1..10'000 count += is_prime(n) I n C (100, 1000, 10'000) print(‘Primes up to #.: #.’.format(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
#11l
11l
V best = [0] * 16   F try_swaps(&deck, f, =s, d, n) I d > :best[n]  :best[n] = d   V i = 0 V k = 1 << s L s != 0 k >>= 1 s-- I deck[s] == -1 | deck[s] == s L.break i [|]= k I (i [&] f) == i & d + :best[s] <= :best[n] R d s++   V deck2 = copy(deck) k = 1 L(i2) 1 .< s k <<= 1 I deck2[i2] == -1 I (f [&] k) != 0 L.continue E I deck2[i2] != i2 L.continue   deck[i2] = i2 L(j) 0 .. i2 deck2[j] = deck[i2 - j] try_swaps(&deck2, f [|] k, s, 1 + d, n)   F topswops(n)  :best[n] = 0 V deck0 = [-1] * 16 deck0[0] = 0 try_swaps(&deck0, 1, n, 0, n) R :best[n]   L(i) 1..12 print(‘#2: #.’.format(i, topswops(i)))
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle). For the inverse functions,   use the same number and convert its answer to radians and degrees. If your language does not have trigonometric functions available or only has some available,   write functions to calculate the functions based on any   known approximation or identity.
#ALGOL_68
ALGOL 68
main:( REAL pi = 4 * arc tan(1); # Pi / 4 is 45 degrees. All answers should be the same. # REAL radians = pi / 4; REAL degrees = 45.0; REAL temp; # sine # print((sin(radians), " ", sin(degrees * pi / 180), new line)); # cosine # print((cos(radians), " ", cos(degrees * pi / 180), new line)); # tangent # print((tan(radians), " ", tan(degrees * pi / 180), new line)); # arcsine # temp := arc sin(sin(radians)); print((temp, " ", temp * 180 / pi, new line)); # arccosine # temp := arc cos(cos(radians)); print((temp, " ", temp * 180 / pi, new line)); # arctangent # temp := arc tan(tan(radians)); print((temp, " ", temp * 180 / pi, new line)) )
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm. From the wikipedia entry: ask for 11 numbers to be read into a sequence S reverse sequence S for each item in sequence S result := call a function to do an operation if result overflows alert user else print result The task is to implement the algorithm: Use the function:     f ( x ) = | x | 0.5 + 5 x 3 {\displaystyle f(x)=|x|^{0.5}+5x^{3}} The overflow condition is an answer of greater than 400. The 'user alert' should not stop processing of other items of the sequence. Print a prompt before accepting eleven, textual, numeric inputs. You may optionally print the item as well as its associated result, but the results must be in reverse order of input. The sequence   S   may be 'implied' and so not shown explicitly. Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#APL
APL
∇ {res}←Trabb;f;S;i;a;y ⍝ define a function Trabb f←{(0.5*⍨|⍵)+5×⍵*3} ⍝ define a function f S←,⍎{⍞←⍵ ⋄ (≢⍵)↓⍞}'Please, enter 11 numbers: '  :For i a :InEach (⌽⍳≢S)(⌽S) ⍝ loop through N..1 and reversed S  :If 400<y←f(a) ⎕←'Too large: ',⍕i  :Else ⎕←i,y  :EndIf  :EndFor ∇
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).
#Arturo
Arturo
proc: function [x]-> ((abs x) ^ 0.5) + 5 * x ^ 3   ask: function [msg][ to [:floating] first.n: 11 split.words strip input msg ]   loop reverse ask "11 numbers: " 'n [ result: proc n print [n ":" (result > 400)? -> "TOO LARGE!" -> result] ]
http://rosettacode.org/wiki/Tree_from_nesting_levels
Tree from nesting levels
Given a flat list of integers greater than zero, representing object nesting levels, e.g. [1, 2, 4], generate a tree formed from nested lists of those nesting level integers where: Every int appears, in order, at its depth of nesting. If the next level int is greater than the previous then it appears in a sub-list of the list containing the previous item The generated tree data structure should ideally be in a languages nested list format that can be used for further calculations rather than something just calculated for printing. An input of [1, 2, 4] should produce the equivalent of: [1, [2, [[4]]]] where 1 is at depth1, 2 is two deep and 4 is nested 4 deep. [1, 2, 4, 2, 2, 1] should produce [1, [2, [[4]], 2, 2], 1]. All the nesting integers are in the same order but at the correct nesting levels. Similarly [3, 1, 3, 1] should generate [[[3]], 1, [[3]], 1] Task Generate and show here the results for the following inputs: [] [1, 2, 4] [3, 1, 3, 1] [1, 2, 3, 1] [3, 2, 1, 3] [3, 3, 3, 1, 1, 3, 3, 3]
#Quackery
Quackery
[ stack ] is prev ( --> s )   [ temp take swap join temp put ] is add$ ( x --> )   [ dup [] = if done 0 prev put $ "' " temp put witheach [ dup prev take - over prev put dup 0 > iff [ times [ $ "[ " add$ ] ] else [ abs times [ $ "] " add$ ] ] number$ space join add$ ] prev take times [ $ "] " add$ ] temp take quackery ] is nesttree ( [ --> [ )   ' [ [ ] [ 1 2 4 ] [ 3 1 3 1 ] [ 1 2 3 1 ] [ 3 2 1 3 ] [ 3 3 3 1 1 3 3 3 ] ]   witheach [ dup echo say " --> " nesttree echo cr cr ]
http://rosettacode.org/wiki/Tree_from_nesting_levels
Tree from nesting levels
Given a flat list of integers greater than zero, representing object nesting levels, e.g. [1, 2, 4], generate a tree formed from nested lists of those nesting level integers where: Every int appears, in order, at its depth of nesting. If the next level int is greater than the previous then it appears in a sub-list of the list containing the previous item The generated tree data structure should ideally be in a languages nested list format that can be used for further calculations rather than something just calculated for printing. An input of [1, 2, 4] should produce the equivalent of: [1, [2, [[4]]]] where 1 is at depth1, 2 is two deep and 4 is nested 4 deep. [1, 2, 4, 2, 2, 1] should produce [1, [2, [[4]], 2, 2], 1]. All the nesting integers are in the same order but at the correct nesting levels. Similarly [3, 1, 3, 1] should generate [[[3]], 1, [[3]], 1] Task Generate and show here the results for the following inputs: [] [1, 2, 4] [3, 1, 3, 1] [1, 2, 3, 1] [3, 2, 1, 3] [3, 3, 3, 1, 1, 3, 3, 3]
#Raku
Raku
sub new_level ( @stack --> Nil ) { my $e = []; push @stack.tail, $e; push @stack, $e; } sub to_tree_iterative ( @xs --> List ) { my $nested = []; my @stack = $nested;   for @xs -> Int $x { new_level(@stack) while $x > @stack; pop @stack while $x < @stack; push @stack.tail, $x; }   return $nested; } my @tests = (), (1, 2, 4), (3, 1, 3, 1), (1, 2, 3, 1), (3, 2, 1, 3), (3, 3, 3, 1, 1, 3, 3, 3); say .Str.fmt( '%15s => ' ), .&to_tree_iterative for @tests;
http://rosettacode.org/wiki/Twelve_statements
Twelve statements
This puzzle is borrowed from   math-frolic.blogspot. Given the following twelve statements, which of them are true? 1. This is a numbered list of twelve statements. 2. Exactly 3 of the last 6 statements are true. 3. Exactly 2 of the even-numbered statements are true. 4. If statement 5 is true, then statements 6 and 7 are both true. 5. The 3 preceding statements are all false. 6. Exactly 4 of the odd-numbered statements are true. 7. Either statement 2 or 3 is true, but not both. 8. If statement 7 is true, then 5 and 6 are both true. 9. Exactly 3 of the first 6 statements are true. 10. The next two statements are both true. 11. Exactly 1 of statements 7, 8 and 9 are true. 12. Exactly 4 of the preceding statements are true. Task When you get tired of trying to figure it out in your head, write a program to solve it, and print the correct answer or answers. Extra credit Print out a table of near misses, that is, solutions that are contradicted by only a single statement.
#Haskell
Haskell
import Data.List (findIndices)   tf :: [[Int] -> Bool] -> [[Int]] tf = traverse (const [1, 0])   wrongness :: [Int] -> [[Int] -> Bool] -> [Int] wrongness ns ps = findIndices id (zipWith (/=) ns (map (fromEnum . ($ ns)) ps))   statements :: [[Int] -> Bool] statements = [ (== 12) . length , 3 ⊂ [length statements - 6 ..] , 2 ⊂ [1,3 ..] , 4 → [4 .. 6] , 0 ⊂ [1 .. 3] , 4 ⊂ [0,2 ..] , 1 ⊂ [1, 2] , 6 → [4 .. 6] , 3 ⊂ [0 .. 5] , 2 ⊂ [10, 11] , 1 ⊂ [6, 7, 8] , 4 ⊂ [0 .. 10] ] where (⊂), (→) :: Int -> [Int] -> [Int] -> Bool (s ⊂ x) b = s == (sum . map (b !!) . takeWhile (< length b)) x (a → x) b = (b !! a == 0) || all ((== 1) . (b !!)) x   testall :: [[Int] -> Bool] -> Int -> [([Int], [Int])] testall s n = [ (b, w) | b <- tf s , w <- [wrongness b s] , length w == n ]   main :: IO () main = let t = testall statements in do putStrLn "Answer" mapM_ print $ t 0 putStrLn "Near misses" mapM_ print $ t 1
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.
#J
J
truthTable=:3 :0 assert. -. 1 e. 'data expr names table' e.&;: y names=. ~. (#~ _1 <: nc) ;:expr=. y data=. #:i.2^#names (names)=. |:data (' ',;:inv names,<expr),(1+#@>names,<expr)":data,.".expr )
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
#JavaScript
JavaScript
  <!-- UlamSpiral.html --> <html> <head><title>Ulam Spiral</title> <script src="VOE.js"></script> <script> // http://rosettacode.org/wiki/User:AnatolV/Helper_Functions // Use v.2.0 var pst;   // ***** Additional helper functions // Pad number from left function padLeft(n,ns) { return (" " + n).slice(-ns); }   // Is number n a prime? function isPrime(n) { var n2=Math.sqrt(n); for(var i=2; i<=n2; i++) { if(n%i === 0) return false; }//fend i return n !== 1; }   function insm(mat,x,y) { var xz=mat[0].length, yz=xz; return(x>=0 && x<xz && y>=0 && y<yz) } // *****   function rbCheck() { if (document.getElementById('rbDef').checked) {pst=0} if (document.getElementById('rbAst').checked) {pst=1} if (document.getElementById('rbNum').checked) {pst=2} } function rbSet() { document.getElementById("rbDef").checked = true; rbCheck(); }   // The Ulam Spiral function pspUlam() { var i, j, x, y, xmx, ymx, cnt, dir, M, Mij, sp=" ", sc=3; // Setting basic vars for canvas and matrix var cvs = document.getElementById('cvsId'); var ctx = cvs.getContext("2d"); if(pst<0||pst>2) {pst=0} if(pst==0) {n=100; sc=3} else {n=10; sc=5} console.log("sc", typeof(sc)); if(n%2==0) {n++}; var n2=n*n, pch, sz=n2.toString().length, pch2=sp.repeat(sz); var fgc="navy", bgc="white"; // Create matrix, finding number of rows and columns var M=new Array(n); for (i=0; i<n; i++) { M[i]=new Array(n); for (j=0; j<n; j++) {M[i][j]=0} } var r = M[0].length, c = M.length, k=0, dsz=1; // Logging init parameters var ttl="Matrix ("+r+","+c+")"; console.log(" *** Ulam spiral: ",n,"x",n,"p-flag=",pst, "sc", sc); // Generating and plotting Ulam spiral x=y=Math.floor(n/2)+1; xmx=ymx=cnt=1; dir="R"; for(var i=1; i<=n2; i++) { // if(isPrime(i)) // if prime { if(!insm(M,x,y)) {break}; if(pst==2) {M[y][x]=i} else {M[y][x]=1}; } // all numbers if(dir=="R") {if(xmx>0){x++;xmx--} else {dir="U";ymx=cnt;y--;ymx--} continue}; if(dir=="U") {if(ymx>0){y--;ymx--} else {dir="L";cnt++;xmx=cnt;x--;xmx--} continue}; if(dir=="L") {if(xmx>0){x--;xmx--} else {dir="D";ymx=cnt;y++;ymx--} continue}; if(dir=="D") {if(ymx>0){y++;ymx--} else {dir="R";cnt++;xmx=cnt;x++;xmx--}; continue}; }//fend i //Plot/Print according to the p-flag(0-real plot,1-"*",2-primes) if(pst==0) {pmat01(M, fgc, bgc, sc, 0); return}; var logs; if(pst==1) {for(i=1;i<n;i++) {logs="|"; for(j=1;j<n;j++) { Mij=M[i][j]; if(Mij>0) {pch="*"} else {pch=" "}; logs+=" "+pch;} logs+="|"; console.log(logs);}//fiend pmat01(M, fgc, bgc, sc, 0); console.log("sc", sc); return; }//ifend //console.log(" ",pch);} console.log(" ")}; return}; if(pst==2) {for(i=1;i<n;i++) {logs="|"; for(j=1;j<n;j++) {Mij=M[i][j]; if(Mij==0) {pch=pch2} else {pch=padLeft(Mij,sz)}; logs+=pch; } //" "+ logs+=" |"; console.log(logs);}//fiend pmat01(M, fgc, bgc, sc, 0); console.log("sc", sc); return; }//ifend   }//func end // ****************************************** </script></head> <body onload='rbSet();' style="font-family: arial, helvatica, sans-serif;"> <b>Plot/print style:</b> <input type="radio" onclick="rbCheck();" name="rb" id="rbDef"/><b>Plot</b>&nbsp; <input type="radio" onclick="rbCheck();" name="rb" id="rbAst"/><b>Print *</b>&nbsp; <input type="radio" onclick="rbCheck();" name="rb" id="rbNum"/><b>Print numbers</b>&nbsp; <input type="button" value="Plot it!" onclick="pspUlam();"> <h3>Ulam Spiral</h3> <canvas id="cvsId" width="300" height="300" style="border: 2px inset;"></canvas> </body> </html>  
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.]
#Common_Lisp
Common Lisp
  (defun start () (format t "Largest right-truncatable ~a~%" (max-right-truncatable)) (format t "Largest left-truncatable ~a~%" (max-left-truncatable)))   (defun max-right-truncatable () (loop for el in (6-digits-R-truncatables) maximizing el into max finally (return max)))   (defun 6-digits-R-truncatables (&optional (lst '(2 3 5 7)) (n 5)) (if (zerop n) lst (6-digits-R-truncatables (R-trunc lst) (- n 1))))   (defun R-trunc (lst) (remove-if (lambda (x) (not (primep x))) (loop for el in lst append (mapcar (lambda (x) (+ (* 10 el) x)) '(1 3 7 9)))))   (defun max-left-truncatable () (loop for el in (6-digits-L-truncatables) maximizing el into max finally (return max)))   (defun 6-digits-L-truncatables (&optional (lst '(3 7)) (n 5)) (if (zerop n) lst (6-digits-L-truncatables (L-trunc lst (- 6 n)) (- n 1))))   (defun L-trunc (lst n) (remove-if (lambda (x) (not (primep x))) (loop for el in lst append (mapcar (lambda (x) (+ (* (expt 10 n) x) el)) '(1 2 3 4 5 6 7 8 9)))))   (defun primep (n) (primep-aux n 2))   (defun primep-aux (n d) (cond ((> d (sqrt n)) t) ((zerop (rem n d)) nil) (t (primep-aux n (+ d 1)))))  
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#Raku
Raku
use NativeCall;   sub truncate(Str, int32 --> int32) is native {*}   sub MAIN (Str $file, Int $to) { given $file.IO { .e or die "$file doesn't exist"; .w or die "$file isn't writable"; .s >= $to or die "$file is not big enough to truncate"; } truncate($file, $to) == 0 or die "Truncation was unsuccessful"; }
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#REXX
REXX
/*REXX program truncates a file to a specified (and smaller) number of bytes. */ parse arg siz FID /*obtain required arguments from the CL*/ FID=strip(FID) /*elide FID leading/trailing blanks. */ if siz=='' then call ser "No truncation size was specified (1st argument)." if FID=='' then call ser "No fileID was specified (2nd argument)." if \datatype(siz,'W') then call ser "trunc size isn't an integer: " siz if siz<1 then call ser "trunc size isn't a positive integer: " siz _=charin(FID,1,siz+1) /*position file and read a wee bit more*/ #=length(_) /*get the length of the part just read.*/ if #==0 then call ser "the specified file doesn't exist: " FID if #<siz then call ser "the file is smaller than trunc size: " # call lineout FID /*close the file used, just to be safe.*/ 'ERASE' FID /*invoke a command to delete the file */ call lineout FID /*close the file, maybe for REXX's use.*/ call charout FID, left(_,siz), 1 /*write a truncated version of the file*/ call lineout FID /*close the file used, just to be safe.*/ say 'file ' FID " truncated to " siz 'bytes.' /*display some information to terminal.*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ ser: say '***error***' arg(1); exit 13 /*display an error message and exit. */
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.
#C
C
#include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h>   enum { LEFT, RIGHT, STAY };   typedef struct { int state1; int symbol1; int symbol2; int dir; int state2; } transition_t;   typedef struct tape_t tape_t; struct tape_t { int symbol; tape_t *left; tape_t *right; };   typedef struct { int states_len; char **states; int final_states_len; int *final_states; int symbols_len; char *symbols; int blank; int state; int tape_len; tape_t *tape; int transitions_len; transition_t ***transitions; } turing_t;   int state_index (turing_t *t, char *state) { int i; for (i = 0; i < t->states_len; i++) { if (!strcmp(t->states[i], state)) { return i; } } return 0; }   int symbol_index (turing_t *t, char symbol) { int i; for (i = 0; i < t->symbols_len; i++) { if (t->symbols[i] == symbol) { return i; } } return 0; }   void move (turing_t *t, int dir) { tape_t *orig = t->tape; if (dir == RIGHT) { if (orig && orig->right) { t->tape = orig->right; } else { t->tape = calloc(1, sizeof (tape_t)); t->tape->symbol = t->blank; if (orig) { t->tape->left = orig; orig->right = t->tape; } } } else if (dir == LEFT) { if (orig && orig->left) { t->tape = orig->left; } else { t->tape = calloc(1, sizeof (tape_t)); t->tape->symbol = t->blank; if (orig) { t->tape->right = orig; orig->left = t->tape; } } } }   turing_t *create (int states_len, ...) { va_list args; va_start(args, states_len); turing_t *t = malloc(sizeof (turing_t)); t->states_len = states_len; t->states = malloc(states_len * sizeof (char *)); int i; for (i = 0; i < states_len; i++) { t->states[i] = va_arg(args, char *); } t->final_states_len = va_arg(args, int); t->final_states = malloc(t->final_states_len * sizeof (int)); for (i = 0; i < t->final_states_len; i++) { t->final_states[i] = state_index(t, va_arg(args, char *)); } t->symbols_len = va_arg(args, int); t->symbols = malloc(t->symbols_len); for (i = 0; i < t->symbols_len; i++) { t->symbols[i] = va_arg(args, int); } t->blank = symbol_index(t, va_arg(args, int)); t->state = state_index(t, va_arg(args, char *)); t->tape_len = va_arg(args, int); t->tape = NULL; for (i = 0; i < t->tape_len; i++) { move(t, RIGHT); t->tape->symbol = symbol_index(t, va_arg(args, int)); } if (!t->tape_len) { move(t, RIGHT); } while (t->tape->left) { t->tape = t->tape->left; } t->transitions_len = va_arg(args, int); t->transitions = malloc(t->states_len * sizeof (transition_t **)); for (i = 0; i < t->states_len; i++) { t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *)); } for (i = 0; i < t->transitions_len; i++) { transition_t *tran = malloc(sizeof (transition_t)); tran->state1 = state_index(t, va_arg(args, char *)); tran->symbol1 = symbol_index(t, va_arg(args, int)); tran->symbol2 = symbol_index(t, va_arg(args, int)); tran->dir = va_arg(args, int); tran->state2 = state_index(t, va_arg(args, char *)); t->transitions[tran->state1][tran->symbol1] = tran; } va_end(args); return t; }   void print_state (turing_t *t) { printf("%-10s ", t->states[t->state]); tape_t *tape = t->tape; while (tape->left) { tape = tape->left; } while (tape) { if (tape == t->tape) { printf("[%c]", t->symbols[tape->symbol]); } else { printf(" %c ", t->symbols[tape->symbol]); } tape = tape->right; } printf("\n"); }   void run (turing_t *t) { int i; while (1) { print_state(t); for (i = 0; i < t->final_states_len; i++) { if (t->final_states[i] == t->state) { return; } } transition_t *tran = t->transitions[t->state][t->tape->symbol]; t->tape->symbol = tran->symbol2; move(t, tran->dir); t->state = tran->state2; } }   int main () { printf("Simple incrementer\n"); turing_t *t = create( /* states */ 2, "q0", "qf", /* final_states */ 1, "qf", /* symbols */ 2, 'B', '1', /* blank */ 'B', /* initial_state */ "q0", /* initial_tape */ 3, '1', '1', '1', /* transitions */ 2, "q0", '1', '1', RIGHT, "q0", "q0", 'B', '1', STAY, "qf" ); run(t); printf("\nThree-state busy beaver\n"); t = create( /* states */ 4, "a", "b", "c", "halt", /* final_states */ 1, "halt", /* symbols */ 2, '0', '1', /* blank */ '0', /* initial_state */ "a", /* initial_tape */ 0, /* transitions */ 6, "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" ); run(t); return 0; printf("\nFive-state two-symbol probable busy beaver\n"); t = create( /* states */ 6, "A", "B", "C", "D", "E", "H", /* final_states */ 1, "H", /* symbols */ 2, '0', '1', /* blank */ '0', /* initial_state */ "A", /* initial_tape */ 0, /* transitions */ 10, "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" ); run(t); }  
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).
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program totient.s */   /************************************/ /* Constantes */ /************************************/ .include "../includeConstantesARM64.inc" .equ MAXI, 25   /*********************************/ /* Initialized data */ /*********************************/ .data szMessNumber: .asciz " number @ totient @ @ \n" szCarriageReturn: .asciz "\n" szMessPrime: .asciz " is prime." szMessSpace: .asciz " " szMessCounterPrime: .asciz "Number of primes to @ : @ \n" szMessOverflow: .asciz "Overflow function isPrime.\n" /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: mov x4,#1 // start number 1: mov x0,x4 bl totient // compute totient mov x5,x0 mov x0,x4 bl isPrime // control if number is prime mov x6,x0 mov x0,x4 // display result ldr x1,qAdrsZoneConv bl conversion10 // call décimal conversion ldr x0,qAdrszMessNumber ldr x1,qAdrsZoneConv // insert conversion in message bl strInsertAtCharInc mov x7,x0 mov x0,x5 ldr x1,qAdrsZoneConv bl conversion10 // call décimal conversion mov x0,x7 ldr x1,qAdrsZoneConv // insert conversion in message bl strInsertAtCharInc mov x7,x0 cmp x6,#1 ldr x1,qAdrszMessPrime ldr x8,qAdrszMessSpace csel x1,x1,x8,eq mov x0,x7 bl strInsertAtCharInc bl affichageMess // display message   add x4,x4,#1 // increment number cmp x4,#MAXI // maxi ? ble 1b // and loop   mov x4,#2 // first number mov x5,#0 // prime counter ldr x6,iCst1000 // load constantes ldr x7,iCst10000 ldr x8,iCst100000 2: mov x0,x4 bl isPrime cmp x0,#0 beq 3f add x5,x5,#1 3: add x4,x4,#1 cmp x4,#100 bne 4f mov x0,#100 mov x1,x5 bl displayCounter b 7f 4: cmp x4,x6 // 1000 bne 5f mov x0,x6 mov x1,x5 bl displayCounter b 7f 5: cmp x4,x7 // 10000 bne 6f mov x0,x7 mov x1,x5 bl displayCounter b 7f 6: cmp x4,x8 // 100000 bne 7f mov x0,x8 mov x1,x5 bl displayCounter 7: cmp x4,x8 ble 2b // and loop   100: // standard end of the program mov x0, #0 // return code mov x8,EXIT svc #0 // perform the system call qAdrszCarriageReturn: .quad szCarriageReturn qAdrsZoneConv: .quad sZoneConv qAdrszMessNumber: .quad szMessNumber qAdrszMessCounterPrime: .quad szMessCounterPrime qAdrszMessPrime: .quad szMessPrime qAdrszMessSpace: .quad szMessSpace iCst1000: .quad 1000 iCst10000: .quad 10000 iCst100000: .quad 100000 /******************************************************************/ /* display counter */ /******************************************************************/ /* x0 contains limit */ /* x1 contains counter */ displayCounter: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers mov x2,x1 ldr x1,qAdrsZoneConv bl conversion10 // call décimal conversion ldr x0,qAdrszMessCounterPrime ldr x1,qAdrsZoneConv // insert conversion in message bl strInsertAtCharInc mov x3,x0 mov x0,x2 ldr x1,qAdrsZoneConv bl conversion10 // call décimal conversion mov x0,x3 ldr x1,qAdrsZoneConv // insert conversion in message bl strInsertAtCharInc bl affichageMess 100: ldp x2,x3,[sp],16 // restaur registers ldp x1,lr,[sp],16 // restaur registers ret /******************************************************************/ /* compute totient of number */ /******************************************************************/ /* x0 contains number */ totient: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers mov x4,x0 // totient mov x5,x0 // save number mov x1,#0 // for first divisor 1: // begin loop mul x3,x1,x1 // compute square cmp x3,x5 // compare number bgt 4f // end add x1,x1,#2 // next divisor udiv x2,x5,x1 msub x3,x1,x2,x5 // compute remainder cmp x3,#0 // remainder null ? bne 3f 2: // begin loop 2 udiv x2,x5,x1 msub x3,x1,x2,x5 // compute remainder cmp x3,#0 csel x5,x2,x5,eq // new value = quotient beq 2b   udiv x2,x4,x1 // divide totient sub x4,x4,x2 // compute new totient 3: cmp x1,#2 // first divisor ? mov x0,1 csel x1,x0,x1,eq // divisor = 1 b 1b // and loop 4: cmp x5,#1 // final value > 1 ble 5f mov x0,x4 // totient mov x1,x5 // divide by value udiv x2,x4,x5 // totient divide by value sub x4,x4,x2 // compute new totient 5:   mov x0,x4 100: ldp x4,x5,[sp],16 // restaur registers ldp x2,x3,[sp],16 // restaur registers ldp x1,lr,[sp],16 // restaur registers ret /***************************************************/ /* Verification si un nombre est premier */ /***************************************************/ /* x0 contient le nombre à verifier */ /* x0 retourne 1 si premier 0 sinon */ isPrime: stp x1,lr,[sp,-16]! // save registres stp x2,x3,[sp,-16]! // save registres mov x2,x0 sub x1,x0,#1 cmp x2,0 beq 99f // retourne zéro cmp x2,2 // pour 1 et 2 retourne 1 ble 2f mov x0,#2 bl moduloPur64 bcs 100f // erreur overflow cmp x0,#1 bne 99f // Pas premier cmp x2,3 beq 2f mov x0,#3 bl moduloPur64 blt 100f // erreur overflow cmp x0,#1 bne 99f   cmp x2,5 beq 2f mov x0,#5 bl moduloPur64 bcs 100f // erreur overflow cmp x0,#1 bne 99f // Pas premier   cmp x2,7 beq 2f mov x0,#7 bl moduloPur64 bcs 100f // erreur overflow cmp x0,#1 bne 99f // Pas premier   cmp x2,11 beq 2f mov x0,#11 bl moduloPur64 bcs 100f // erreur overflow cmp x0,#1 bne 99f // Pas premier   cmp x2,13 beq 2f mov x0,#13 bl moduloPur64 bcs 100f // erreur overflow cmp x0,#1 bne 99f // Pas premier   cmp x2,17 beq 2f mov x0,#17 bl moduloPur64 bcs 100f // erreur overflow cmp x0,#1 bne 99f // Pas premier 2: cmn x0,0 // carry à zero pas d'erreur mov x0,1 // premier b 100f 99: cmn x0,0 // carry à zero pas d'erreur mov x0,#0 // Pas premier 100: ldp x2,x3,[sp],16 // restaur des 2 registres ldp x1,lr,[sp],16 // restaur des 2 registres ret // retour adresse lr x30   /**************************************************************/ /********************************************************/ /* Calcul modulo de b puissance e modulo m */ /* Exemple 4 puissance 13 modulo 497 = 445 */ /********************************************************/ /* x0 nombre */ /* x1 exposant */ /* x2 modulo */ moduloPur64: stp x1,lr,[sp,-16]! // save registres stp x3,x4,[sp,-16]! // save registres stp x5,x6,[sp,-16]! // save registres stp x7,x8,[sp,-16]! // save registres stp x9,x10,[sp,-16]! // save registres cbz x0,100f cbz x1,100f mov x8,x0 mov x7,x1 mov x6,1 // resultat udiv x4,x8,x2 msub x9,x4,x2,x8 // contient le reste 1: tst x7,1 beq 2f mul x4,x9,x6 umulh x5,x9,x6 //cbnz x5,99f mov x6,x4 mov x0,x6 mov x1,x5 bl divisionReg128U cbnz x1,99f // overflow mov x6,x3 2: mul x8,x9,x9 umulh x5,x9,x9 mov x0,x8 mov x1,x5 bl divisionReg128U cbnz x1,99f // overflow mov x9,x3 lsr x7,x7,1 cbnz x7,1b mov x0,x6 // result cmn x0,0 // carry à zero pas d'erreur b 100f 99: ldr x0,qAdrszMessOverflow bl affichageMess cmp x0,0 // carry à un car erreur mov x0,-1 // code erreur   100: ldp x9,x10,[sp],16 // restaur des 2 registres ldp x7,x8,[sp],16 // restaur des 2 registres ldp x5,x6,[sp],16 // restaur des 2 registres ldp x3,x4,[sp],16 // restaur des 2 registres ldp x1,lr,[sp],16 // restaur des 2 registres ret // retour adresse lr x30 qAdrszMessOverflow: .quad szMessOverflow /***************************************************/ /* division d un nombre de 128 bits par un nombre de 64 bits */ /***************************************************/ /* x0 contient partie basse dividende */ /* x1 contient partie haute dividente */ /* x2 contient le diviseur */ /* x0 retourne partie basse quotient */ /* x1 retourne partie haute quotient */ /* x3 retourne le reste */ divisionReg128U: stp x6,lr,[sp,-16]! // save registres stp x4,x5,[sp,-16]! // save registres mov x5,#0 // raz du reste R mov x3,#128 // compteur de boucle mov x4,#0 // dernier bit 1: lsl x5,x5,#1 // on decale le reste de 1 tst x1,1<<63 // test du bit le plus à gauche lsl x1,x1,#1 // on decale la partie haute du quotient de 1 beq 2f orr x5,x5,#1 // et on le pousse dans le reste R 2: tst x0,1<<63 lsl x0,x0,#1 // puis on decale la partie basse beq 3f orr x1,x1,#1 // et on pousse le bit de gauche dans la partie haute 3: orr x0,x0,x4 // position du dernier bit du quotient mov x4,#0 // raz du bit cmp x5,x2 blt 4f sub x5,x5,x2 // on enleve le diviseur du reste mov x4,#1 // dernier bit à 1 4: // et boucle subs x3,x3,#1 bgt 1b lsl x1,x1,#1 // on decale le quotient de 1 tst x0,1<<63 lsl x0,x0,#1 // puis on decale la partie basse beq 5f orr x1,x1,#1 5: orr x0,x0,x4 // position du dernier bit du quotient mov x3,x5 100: ldp x4,x5,[sp],16 // restaur des 2 registres ldp x6,lr,[sp],16 // restaur des 2 registres ret // retour adresse lr x30     /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../includeARM64.inc"  
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
#360_Assembly
360 Assembly
* Topswops optimized 12/07/2016 TOPSWOPS CSECT USING TOPSWOPS,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " <- ST R15,8(R13) " -> LR R13,R15 " addressability MVC N,=F'1' n=1 LOOPN L R4,N n; do n=1 to 10 ===-------------==* C R4,=F'10' " * BH ELOOPN . * MVC P(40),PINIT p=pinit MVC COUNTM,=F'0' countm=0 REPEAT MVC CARDS(40),P cards=p -------------------------+ SR R11,R11 count=0 | WHILE CLC CARDS,=F'1' do while cards(1)^=1 ---------+ BE EWHILE . | MVC M,CARDS m=cards(1) L R2,M m SRA R2,1 m/2 ST R2,MD2 md2=m/2 L R3,M @card(mm)=m SLA R3,2 *4 LA R3,CARDS-4(R3) @card(mm) LA R2,CARDS @card(i)=0 LA R6,1 i=1 LOOPI C R6,MD2 do i=1 to m/2 -------------+ BH ELOOPI . | L R0,0(R2) swap r0=cards(i) MVC 0(4,R2),0(R3) swap cards(i)=cards(mm) ST R0,0(R3) swap cards(mm)=r0 AH R2,=H'4' @card(i)=@card(i)+4 SH R3,=H'4' @card(mm)=@card(mm)-4 LA R6,1(R6) i=i+1 | B LOOPI ----------------------------+ ELOOPI LA R11,1(R11) count=count+1 | B WHILE -------------------------------+ EWHILE C R11,COUNTM if count>countm BNH NOTGT then ST R11,COUNTM countm=count NOTGT BAL R14,NEXTPERM call nextperm LTR R0,R0 until nextperm=0 | BNZ REPEAT ---------------------------------+ L R1,N n XDECO R1,XDEC edit n MVC PG(2),XDEC+10 output n MVI PG+2,C':' output ':' L R1,COUNTM countm XDECO R1,XDEC edit countm MVC PG+3(4),XDEC+8 output countm XPRNT PG,L'PG print buffer L R1,N n * LA R1,1(R1) +1 * ST R1,N n=n+1 * B LOOPN ===------------------------------==* ELOOPN L R13,4(0,R13) epilog LM R14,R12,12(R13) " restore XR R15,R15 " rc=0 BR R14 exit PINIT DC F'1',F'2',F'3',F'4',F'5',F'6',F'7',F'8',F'9',F'10' CARDS DS 10F cards P DS 10F p COUNTM DS F countm M DS F m N DS F n MD2 DS F m/2 PG DC CL20' ' buffer XDEC DS CL12 temp *------- ---- nextperm ----------{----------------------------------- NEXTPERM L R9,N nn=n SR R8,R8 jj=0 LR R7,R9 nn BCTR R7,0 j=nn-1 LTR R7,R7 if j=0 BZ ELOOPJ1 then skip do loop LOOPJ1 LR R1,R7 do j=nn-1 to 1 by -1; j ----+ SLA R1,2 . | L R2,P-4(R1) p(j) C R2,P(R1) if p(j)<p(j+1) BNL PJGEPJP then LR R8,R7 jj=j B ELOOPJ1 leave j | PJGEPJP BCT R7,LOOPJ1 j=j-1 ---------------------+ ELOOPJ1 LA R7,1(R8) j=jj+1 LOOPJ2 CR R7,R9 do j=jj+1 while j<nn ------+ BNL ELOOPJ2 . | LR R2,R7 j SLA R2,2 . LR R3,R9 nn SLA R3,2 . L R0,P-4(R2) swap p(j),p(nn) L R1,P-4(R3) " ST R0,P-4(R3) " ST R1,P-4(R2) " BCTR R9,0 nn=nn-1 LA R7,1(R7) j=j+1 | B LOOPJ2 ----------------------------+ ELOOPJ2 LTR R8,R8 if jj=0 BNZ JJNE0 then LA R0,0 return(0) BR R14 " JJNE0 LA R7,1(R8) j=jj+1 LR R2,R7 j SLA R2,2 r@p(j) LR R3,R8 jj SLA R3,2 r@p(jj) LOOPJ3 L R0,P-4(R2) p(j) ----------------------+ C R0,P-4(R3) do j=jj+1 while p(j)<p(jj) | BNL ELOOPJ3 LA R2,4(R2) r@p(j)=r@p(j)+4 LA R7,1(R7) j=j+1 | B LOOPJ3 ----------------------------+ ELOOPJ3 L R1,P-4(R3) swap p(j),p(jj) ST R0,P-4(R3) " ST R1,P-4(R2) " LA R0,1 return(1) BR R14 ---------------}----------------------------------- YREGS END TOPSWOPS
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
#Ada
Ada
with Ada.Integer_Text_IO, Generic_Perm;   procedure Topswaps is   function Topswaps(Size: Positive) return Natural is package Perms is new Generic_Perm(Size); P: Perms.Permutation; Done: Boolean; Max: Natural;   function Swapper_Calls(P: Perms.Permutation) return Natural is Q: Perms.Permutation := P; I: Perms.Element := P(1); begin if I = 1 then return 0; else for Idx in 1 .. I loop Q(Idx) := P(I-Idx+1); end loop; return 1 + Swapper_Calls(Q); end if; end Swapper_Calls;   begin Perms.Set_To_First(P, Done); Max:= Swapper_Calls(P); while not Done loop Perms.Go_To_Next(P, Done); Max := natural'Max(Max, Swapper_Calls(P)); end loop; return Max; end Topswaps;   begin for I in 1 .. 10 loop Ada.Integer_Text_IO.Put(Item => Topswaps(I), Width => 3); end loop; end Topswaps;
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.
#ALGOL_W
ALGOL W
begin  % Algol W only supplies sin, cos and arctan as standard. We can define  %  % arcsin, arccos and tan functions using these. The standard functions  %  % use radians so we also provide versions that use degrees  %    % convert degrees to radians  % real procedure toRadians( real value x ) ; pi * ( x / 180 );  % convert radians to degrees  % real procedure toDegrees( real value x ) ; 180 * ( x / pi );  % tan of an angle in radians  % real procedure tan( real value x ) ; sin( x ) / cos( x );  % arcsin in radians  % real procedure arcsin( real value x ) ; arctan( x / sqrt( 1 - ( x * x ) ) );  % arccos in radians  % real procedure arccos( real value x ) ; arctan( sqrt( 1 - ( x * x ) ) / x );  % sin of an angle in degrees  % real procedure sinD( real value x ) ; sin( toRadians( x ) );  % cos of an angle in degrees  % real procedure cosD( real value x ) ; cos( toRadians( x ) );  % tan of an angle in degrees  % real procedure tanD( real value x ) ; tan( toRadians( x ) );  % arctan in degrees  % real procedure arctanD( real value x ) ; toDegrees( arctan( x ) );  % arcsin in degrees  % real procedure arcsinD( real value x ) ; toDegrees( arcsin( x ) );  % arccos in degrees  % real procedure arccosD( real value x ) ; toDegrees( arccos( x ) );      % test the procedures % begin   real piOver4, piOver3, oneOverRoot2, root3Over2; piOver3 := pi / 3; piOver4  := pi / 4; oneOverRoot2 := 1.0 / sqrt( 2 ); root3Over2 := sqrt( 3 ) / 2;     r_w := 12; r_d := 5; r_format := "A"; s_w := 0; % set output format  %   write( "PI/4: ", piOver4, " 1/root(2): ", oneOverRoot2 ); write(); write( "sin 45 degrees: ", sinD( 45 ), " sin pi/4 radians: ", sin( piOver4 ) ); write( "cos 45 degrees: ", cosD( 45 ), " cos pi/4 radians: ", cos( piOver4 ) ); write( "tan 45 degrees: ", tanD( 45 ), " tan pi/4 radians: ", tan( piOver4 ) ); write(); write( "arcsin( sin( pi/4 radians ) ): ", arcsin( sin( piOver4 ) ) ); write( "arccos( cos( pi/4 radians ) ): ", arccos( cos( piOver4 ) ) ); write( "arctan( tan( pi/4 radians ) ): ", arctan( tan( piOver4 ) ) ); write(); write( "PI/3: ", piOver4, " root(3)/2: ", root3Over2 ); write(); write( "sin 60 degrees: ", sinD( 60 ), " sin pi/3 radians: ", sin( piOver3 ) ); write( "cos 60 degrees: ", cosD( 60 ), " cos pi/3 radians: ", cos( piOver3 ) ); write( "tan 60 degrees: ", tanD( 60 ), " tan pi/3 radians: ", tan( piOver3 ) ); write(); write( "arcsin( sin( 60 degrees ) ): ", arcsinD( sinD( 60 ) ) ); write( "arccos( cos( 60 degrees ) ): ", arccosD( cosD( 60 ) ) ); write( "arctan( tan( 60 degrees ) ): ", arctanD( tanD( 60 ) ) );   end   end.
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm. From the wikipedia entry: ask for 11 numbers to be read into a sequence S reverse sequence S for each item in sequence S result := call a function to do an operation if result overflows alert user else print result The task is to implement the algorithm: Use the function:     f ( x ) = | x | 0.5 + 5 x 3 {\displaystyle f(x)=|x|^{0.5}+5x^{3}} The overflow condition is an answer of greater than 400. The 'user alert' should not stop processing of other items of the sequence. Print a prompt before accepting eleven, textual, numeric inputs. You may optionally print the item as well as its associated result, but the results must be in reverse order of input. The sequence   S   may be 'implied' and so not shown explicitly. Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#ASIC
ASIC
  REM Trabb Pardo-Knuth algorithm REM Used "magic numbers" because of strict specification of the algorithm. DIM S@(10) PRINT "Enter 11 numbers." FOR I = 0 TO 10 I1= I + 1 PRINT I1; PRINT " => "; INPUT TMP@ S@(I) = TMP@ NEXT I PRINT REM Reverse HALFIMAX = 10 / 2 FOR I = 0 TO HALFIMAX IREV = 10 - I TMP@ = S@(I) S@(I) = S@(IREV) S@(IREV) = TMP@ NEXT I REM Results REM Leading spaces in printed numbers are removed CLS FOR I = 0 TO 10 PRINT "f("; STMP$ = STR$(S@(I)) STMP$ = LTRIM$(STMP$) PRINT STMP$; PRINT ") = "; N@ = S@(I) GOSUB CALCF: R@ = F@ IF R@ > 400 THEN PRINT "overflow" ELSE STMP$ = STR$(R@) STMP$ = LTRIM$(STMP$) PRINT STMP$ ENDIF NEXT I END   CALCF: REM Calculates f(N@) REM Result in F@ X@ = ABS(N@) GOSUB CALCSQRT: F@ = 5.0 * N@ F@ = F@ * N@ F@ = F@ * N@ F@ = F@ + SQRT@ RETURN   CALCSQRT: REM Calculates approximate (+- 0.00001) square root of X@ for X@ >= 0 (bisection method) REM Result in SQRT@ A@ = 0.0 IF X@ >= 1.0 THEN B@ = X@ ELSE B@ = 1.0 ENDIF L@ = B@ - A@ L@ = ABS(L@) WHILE L@ > 0.00001 MIDDLE@ = A@ + B@ MIDDLE@ = MIDDLE@ / 2 MIDDLETO2@ = MIDDLE@ * MIDDLE@ IF MIDDLETO2@ < X@ THEN A@ = MIDDLE@ ELSE B@ = MIDDLE@ ENDIF L@ = B@ - A@ L@ = ABS(L@) WEND SQRT@ = MIDDLE@ RETURN  
http://rosettacode.org/wiki/Tree_from_nesting_levels
Tree from nesting levels
Given a flat list of integers greater than zero, representing object nesting levels, e.g. [1, 2, 4], generate a tree formed from nested lists of those nesting level integers where: Every int appears, in order, at its depth of nesting. If the next level int is greater than the previous then it appears in a sub-list of the list containing the previous item The generated tree data structure should ideally be in a languages nested list format that can be used for further calculations rather than something just calculated for printing. An input of [1, 2, 4] should produce the equivalent of: [1, [2, [[4]]]] where 1 is at depth1, 2 is two deep and 4 is nested 4 deep. [1, 2, 4, 2, 2, 1] should produce [1, [2, [[4]], 2, 2], 1]. All the nesting integers are in the same order but at the correct nesting levels. Similarly [3, 1, 3, 1] should generate [[[3]], 1, [[3]], 1] Task Generate and show here the results for the following inputs: [] [1, 2, 4] [3, 1, 3, 1] [1, 2, 3, 1] [3, 2, 1, 3] [3, 3, 3, 1, 1, 3, 3, 3]
#Wren
Wren
import "/seq" for Stack import "/fmt" for Fmt   var toTree = Fn.new { |list| var nested = [] var s = Stack.new() s.push(nested) for (n in list) { while (n != s.count) { if (n > s.count) { var inner = [] s.peek().add(inner) s.push(inner) } else { s.pop() } } s.peek().add(n) } return nested }   var tests = [ [], [1, 2, 4], [3, 1, 3, 1], [1, 2, 3, 1], [3, 2, 1, 3], [3, 3, 3, 1, 1, 3, 3, 3] ] for (test in tests) { var nest = toTree.call(test) Fmt.print("$24n => $n", test, nest) }
http://rosettacode.org/wiki/Twelve_statements
Twelve statements
This puzzle is borrowed from   math-frolic.blogspot. Given the following twelve statements, which of them are true? 1. This is a numbered list of twelve statements. 2. Exactly 3 of the last 6 statements are true. 3. Exactly 2 of the even-numbered statements are true. 4. If statement 5 is true, then statements 6 and 7 are both true. 5. The 3 preceding statements are all false. 6. Exactly 4 of the odd-numbered statements are true. 7. Either statement 2 or 3 is true, but not both. 8. If statement 7 is true, then 5 and 6 are both true. 9. Exactly 3 of the first 6 statements are true. 10. The next two statements are both true. 11. Exactly 1 of statements 7, 8 and 9 are true. 12. Exactly 4 of the preceding statements are true. Task When you get tired of trying to figure it out in your head, write a program to solve it, and print the correct answer or answers. Extra credit Print out a table of near misses, that is, solutions that are contradicted by only a single statement.
#J
J
apply 128!:2   NB. example '*:' apply 1 2 3 1 4 9
http://rosettacode.org/wiki/Twelve_statements
Twelve statements
This puzzle is borrowed from   math-frolic.blogspot. Given the following twelve statements, which of them are true? 1. This is a numbered list of twelve statements. 2. Exactly 3 of the last 6 statements are true. 3. Exactly 2 of the even-numbered statements are true. 4. If statement 5 is true, then statements 6 and 7 are both true. 5. The 3 preceding statements are all false. 6. Exactly 4 of the odd-numbered statements are true. 7. Either statement 2 or 3 is true, but not both. 8. If statement 7 is true, then 5 and 6 are both true. 9. Exactly 3 of the first 6 statements are true. 10. The next two statements are both true. 11. Exactly 1 of statements 7, 8 and 9 are true. 12. Exactly 4 of the preceding statements are true. Task When you get tired of trying to figure it out in your head, write a program to solve it, and print the correct answer or answers. Extra credit Print out a table of near misses, that is, solutions that are contradicted by only a single statement.
#Java
Java
  public class LogicPuzzle { boolean S[] = new boolean[13]; int Count = 0;   public boolean check2 () { int count = 0; for (int k = 7; k <= 12; k++) if (S[k]) count++; return S[2] == (count == 3); }   public boolean check3 () { int count = 0; for (int k = 2; k <= 12; k += 2) if (S[k]) count++; return S[3] == (count == 2); }   public boolean check4 () { return S[4] == ( !S[5] || S[6] && S[7]); }   public boolean check5 () { return S[5] == ( !S[2] && !S[3] && !S[4]); }   public boolean check6 () { int count = 0; for (int k = 1; k <= 11; k += 2) if (S[k]) count++; return S[6] == (count == 4); }   public boolean check7 () { return S[7] == ((S[2] || S[3]) && !(S[2] && S[3])); }   public boolean check8 () { return S[8] == ( !S[7] || S[5] && S[6]); }   public boolean check9 () { int count = 0; for (int k = 1; k <= 6; k++) if (S[k]) count++; return S[9] == (count == 3); }   public boolean check10 () { return S[10] == (S[11] && S[12]); }   public boolean check11 () { int count = 0; for (int k = 7; k <= 9; k++) if (S[k]) count++; return S[11] == (count == 1); }   public boolean check12 () { int count = 0; for (int k = 1; k <= 11; k++) if (S[k]) count++; return S[12] == (count == 4); }   public void check () { if (check2() && check3() && check4() && check5() && check6() && check7() && check8() && check9() && check10() && check11() && check12()) { for (int k = 1; k <= 12; k++) if (S[k]) System.out.print(k + " "); System.out.println(); Count++; } }   public void recurseAll (int k) { if (k == 13) check(); else { S[k] = false; recurseAll(k + 1); S[k] = true; recurseAll(k + 1); } }   public static void main (String args[]) { LogicPuzzle P = new LogicPuzzle(); P.S[1] = true; P.recurseAll(2); System.out.println(); System.out.println(P.Count + " Solutions found."); } }  
http://rosettacode.org/wiki/Truth_table
Truth table
A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function. Task Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function. (One can assume that the user input is correct). Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function. Either reverse-polish or infix notation expressions are allowed. Related tasks   Boolean values   Ternary logic See also   Wolfram MathWorld entry on truth tables.   some "truth table" examples from Google.
#Java
Java
import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack;   public class TruthTable { public static void main( final String... args ) { System.out.println( new TruthTable( args ) ); }   private interface Operator { boolean evaluate( Stack<Boolean> s ); }   /** * Supported operators and what they do. For more ops, add entries here. */ private static final Map<String,Operator> operators = new HashMap<String,Operator>() {{ // Can't use && or || because shortcut evaluation may mean the stack is not popped enough put( "&", stack -> Boolean.logicalAnd( stack.pop(), stack.pop() ) ); put( "|", stack -> Boolean.logicalOr( stack.pop(), stack.pop() ) ); put( "!", stack -> ! stack.pop() ); put( "^", stack -> ! stack.pop().equals ( stack.pop() ) ); }};   private final List<String> variables; private final String[] symbols;   /** * Constructs a truth table for the symbols in an expression. */ public TruthTable( final String... symbols ) { final Set<String> variables = new LinkedHashSet<>();   for ( final String symbol : symbols ) { if ( ! operators.containsKey( symbol ) ) { variables.add( symbol ); } } this.variables = new ArrayList<>( variables ); this.symbols = symbols; }   @Override public String toString () { final StringBuilder result = new StringBuilder();   for ( final String variable : variables ) { result.append( variable ).append( ' ' ); } result.append( ' ' ); for ( final String symbol : symbols ) { result.append( symbol ).append ( ' ' ); } result.append( '\n' ); for ( final List<Boolean> values : enumerate( variables.size () ) ) { final Iterator<String> i = variables.iterator();   for ( final Boolean value : values ) { result.append( String.format( "%-" + i.next().length() + "c ", value ? 'T' : 'F' ) ); } result.append( ' ' ) .append( evaluate( values ) ? 'T' : 'F' ) .append( '\n' ); }   return result.toString (); }   /** * Recursively generates T/F values */ private static List<List<Boolean>> enumerate( final int size ) { if ( 1 == size ) return new ArrayList<List<Boolean>>() {{ add( new ArrayList<Boolean>() {{ add(false); }} ); add( new ArrayList<Boolean>() {{ add(true); }} ); }};   return new ArrayList<List<Boolean>>() {{ for ( final List<Boolean> head : enumerate( size - 1 ) ) { add( new ArrayList<Boolean>( head ) {{ add(false); }} ); add( new ArrayList<Boolean>( head ) {{ add(true); }} ); } }}; }   /** * Evaluates the expression for a set of values. */ private boolean evaluate( final List<Boolean> enumeration ) { final Iterator<Boolean> i = enumeration.iterator(); final Map<String,Boolean> values = new HashMap<>(); final Stack<Boolean> stack = new Stack<>();   variables.forEach ( v -> values.put( v, i.next() ) ); for ( final String symbol : symbols ) { final Operator op = operators.get ( symbol );   // Reverse Polish notation makes this bit easy stack.push( null == op ? values.get ( symbol ) : op.evaluate ( stack ) ); } return stack.pop(); } }
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
#jq
jq
def array($init): [range(0; .) | $init];   # Test if input is a one-character string holding a digit def isDigit: type=="string" and length==1 and explode[0] as $c | (48 <= $c and $c <= 57);   def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;   def generate($n; $i; $c): if $n <= 1 then "'n' must be more than 1." | error else { s: ($n|array(array(""))), dir: "right", y: (($n/2)|floor) } | .x = if ($n % 2 == 0) then .y - 1 else .y end # shift left for even n | reduce range($i; $n * $n + $i) as $j (.; .s[.y][.x] = ( if $j | is_prime then (if $c|isDigit then $j|lpad(4) else " \($c) " end) else " ---" end) | if .dir == "right" then if (.x <= $n - 1 and .s[.y - 1][.x] == "" and $j > i) then .dir = "up" else . end elif .dir == "up" then if (.s[.y][.x - 1] == "") then .dir = "left" else . end elif .dir == "left" then if (.x == 0 or .s[.y + 1][.x] == "") then .dir = "down" else . end elif .dir == "down" then if (.s[.y][.x + 1] == "") then .dir = "right" else . end else . end | if .dir == "right" then .x += 1 elif .dir == "up" then .y += -1 elif .dir == "left" then .x += -1 elif .dir == "down" then .y += 1 else . end ) | .s[] | join(" ") end ;   # with digits generate(9; 1; "0"), "",   # with * generate(9; 1; "*")  
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 739, 73, and 7 formed by removing digits from its right are also prime. No zeroes are allowed in truncatable primes. Task The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied). Related tasks Find largest left truncatable prime in a given base Sieve of Eratosthenes See also Truncatable Prime from MathWorld.]
#D
D
import std.stdio, std.math, std.string, std.conv, std.algorithm, std.range;   bool isPrime(in int n) pure nothrow { if (n <= 1) return false; foreach (immutable i; 2 .. cast(int)sqrt(real(n)) + 1) if (!(n % i)) return false; return true; }   bool isTruncatablePrime(bool left)(in int n) pure { immutable s = n.text; if (s.canFind('0')) return false; foreach (immutable i; 0 .. s.length) static if (left) { if (!s[i .. $].to!int.isPrime) return false; } else { if (!s[0 .. i + 1].to!int.isPrime) return false; } return true; }   void main() { enum n = 1_000_000; writeln("Largest left-truncatable prime in 2 .. ", n, ": ", iota(n, 1, -1).filter!(isTruncatablePrime!true).front); writeln("Largest right-truncatable prime in 2 .. ", n, ": ", iota(n, 1, -1).filter!(isTruncatablePrime!false).front); }
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#Ring
Ring
  file = "C:\Ring\ReadMe.txt" fp = read(file) fpstr = left(fp, 100) see fpstr + nl write(file, fpstr)  
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#Ruby
Ruby
# Open a file for writing, and truncate it to 1234 bytes. File.open("file", "ab") do |f| f.truncate(1234) f << "Killroy was here" # write to file end # file is closed now.   # Just truncate a file to 567 bytes. File.truncate("file", 567)
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#Rust
Rust
use std::path::Path; use std::fs;   fn truncate_file<P: AsRef<Path>>(filename: P, filesize: usize) -> Result<(), Error> { use Error::*; let file = fs::read(&filename).or(Err(NotFound))?;   if filesize > file.len() { return Err(FilesizeTooSmall) }   fs::write(&filename, &file[..filesize]).or(Err(UnableToWrite))?; Ok(()) }   #[derive(Debug)] enum Error { /// File not found NotFound, /// Truncated size would be larger than the current size FilesizeTooSmall, /// Likely due to having read but not write permissions UnableToWrite, }
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.
#C.23
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks;   public class TuringMachine { public static async Task Main() { var fiveStateBusyBeaver = new TuringMachine("A", '0', "H").WithTransitions( ("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") ); var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();   var incrementer = new TuringMachine("q0", 'B', "qf").WithTransitions( ("q0", '1', '1', Right, "q0"), ("q0", 'B', '1', Stay, "qf") ) .WithInput("111"); foreach (var _ in incrementer.Run()) PrintLine(incrementer); PrintResults(incrementer);   var threeStateBusyBeaver = new TuringMachine("a", '0', "halt").WithTransitions( ("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") ); foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver); PrintResults(threeStateBusyBeaver);   var sorter = new TuringMachine("A", '*', "X").WithTransitions( ("A", 'a', 'a', Right, "A"), ("A", 'b', 'B', Right, "B"), ("A", '*', '*', Left, "E"), ("B", 'a', 'a', Right, "B"), ("B", 'b', 'b', Right, "B"), ("B", '*', '*', Left, "C"), ("C", 'a', 'b', Left, "D"), ("C", 'b', 'b', Left, "C"), ("C", 'B', 'b', Left, "E"), ("D", 'a', 'a', Left, "D"), ("D", 'b', 'b', Left, "D"), ("D", 'B', 'a', Right, "A"), ("E", 'a', 'a', Left, "E"), ("E", '*', '*', Right, "X") ) .WithInput("babbababaa"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter);   sorter.Reset().WithInput("bbbababaaabba"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter);   Console.WriteLine(await busyBeaverTask); PrintResults(fiveStateBusyBeaver);   void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + "\tState " + tm.State);   void PrintResults(TuringMachine tm) { Console.WriteLine($"End state: {tm.State} = {(tm.Success ? "Success" : "Failure")}"); Console.WriteLine(tm.Steps + " steps"); Console.WriteLine("tape length: " + tm.TapeLength); Console.WriteLine(); } }   public const int Left = -1, Stay = 0, Right = 1; private readonly Tape tape; private readonly string initialState; private readonly HashSet<string> terminatingStates; private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;   public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) { State = this.initialState = initialState; tape = new Tape(blankSymbol); this.terminatingStates = terminatingStates.ToHashSet(); }   public TuringMachine WithTransitions( params (string state, char read, char write, int move, string toState)[] transitions) { this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState)); return this; }   public TuringMachine Reset() { State = initialState; Steps = 0; tape.Reset(); return this; }   public TuringMachine WithInput(string input) { tape.Input(input); return this; }   public int Steps { get; private set; } public string State { get; private set; } public bool Success => terminatingStates.Contains(State); public int TapeLength => tape.Length; public string TapeString => tape.ToString();   public IEnumerable<string> Run() { yield return State; while (Step()) yield return State; }   public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) { var chrono = Stopwatch.StartNew(); await RunAsync(cancel); chrono.Stop(); return chrono.Elapsed; }   public Task RunAsync(CancellationToken cancel = default) => Task.Run(() => { while (Step()) cancel.ThrowIfCancellationRequested(); });   private bool Step() { if (!transitions.TryGetValue((State, tape.Current), out var action)) return false; tape.Current = action.write; tape.Move(action.move); State = action.toState; Steps++; return true; }     private class Tape { private List<char> forwardTape = new List<char>(), backwardTape = new List<char>(); private int head = 0; private char blank;   public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);   public void Reset() { backwardTape.Clear(); forwardTape.Clear(); head = 0; forwardTape.Add(blank); }   public void Input(string input) { Reset(); forwardTape.Clear(); forwardTape.AddRange(input); }   public void Move(int direction) { head += direction; if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank); if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank); }   public char Current { get => head < 0 ? backwardTape[~head] : forwardTape[head]; set { if (head < 0) backwardTape[~head] = value; else forwardTape[head] = value; } }   public int Length => backwardTape.Count + forwardTape.Count;   public override string ToString() { int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1; var builder = new StringBuilder(" ", Length * 2 + 1); if (backwardTape.Count > 0) { builder.Append(string.Join(" ", backwardTape)).Append(" "); if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')'); for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]); } builder.Append(string.Join(" ", forwardTape)).Append(" "); if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')'); return builder.ToString(); }   }   }
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).
#Ada
Ada
with Ada.Text_IO; with Ada.Integer_Text_IO;   procedure Totient is   function Totient (N : in Integer) return Integer is Tot : Integer := N; I  : Integer; N2  : Integer := N; begin I := 2; while I * I <= N2 loop if N2 mod I = 0 then while N2 mod I = 0 loop N2 := N2 / I; end loop; Tot := Tot - Tot / I; end if;   if I = 2 then I := 1; end if; I := I + 2; end loop;   if N2 > 1 then Tot := Tot - Tot / N2; end if;   return Tot; end Totient;   Count : Integer := 0; Tot  : Integer; Placeholder : String := " n Phi Is_Prime"; Image_N  : String renames Placeholder ( 1 .. 3); Image_Phi  : String renames Placeholder ( 6 .. 8); Image_Prime : String renames Placeholder (11 .. 17); use Ada.Text_IO; use Ada.Integer_Text_IO; begin   Put_Line (Placeholder);   for N in 1 .. 25 loop Tot := Totient (N);   if N - 1 = Tot then Count := Count + 1; end if; Put (Image_N, N); Put (Image_Phi, Tot); Image_Prime := (if N - 1 = Tot then " True" else " False"); Put_Line (Placeholder); end loop; New_Line;   Put_Line ("Number of primes up to " & Integer'(25)'Image &" =" & Count'Image);   for N in 26 .. 100_000 loop Tot := Totient (N);   if Tot = N - 1 then Count := Count + 1; end if;   if N = 100 or N = 1_000 or N mod 10_000 = 0 then Put_Line ("Number of primes up to " & N'Image & " =" & Count'Image); end if; end loop;   end Totient;
http://rosettacode.org/wiki/Topswops
Topswops
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is composed of reversing the first   m   cards where   m   is the value of the topmost card. Rounds are repeated until the topmost card is the number   1   and the number of swaps is recorded. For our example the swaps produce: [2, 4, 1, 3] # Initial shuffle [4, 2, 1, 3] [3, 1, 2, 4] [2, 1, 3, 4] [1, 2, 3, 4] For a total of four swaps from the initial ordering to produce the terminating case where   1   is on top. For a particular number   n   of cards,   topswops(n)   is the maximum swaps needed for any starting permutation of the   n   cards. Task The task is to generate and show here a table of   n   vs   topswops(n)   for   n   in the range   1..10   inclusive. Note Topswops   is also known as   Fannkuch   from the German word   Pfannkuchen   meaning   pancake. Related tasks   Number reversal game   Sorting algorithms/Pancake sort
#AutoHotkey
AutoHotkey
Topswops(Obj, n){ R := [] for i, val in obj{ if (i <=n) res := val (A_Index=1?"":",") res else res .= "," val } Loop, Parse, res, `, R[A_Index]:= A_LoopField return R }
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
#C
C
#include <stdio.h> #include <string.h>   typedef struct { char v[16]; } deck; typedef unsigned int uint;   uint n, d, best[16];   void tryswaps(deck *a, uint f, uint s) { # define A a->v # define B b.v if (d > best[n]) best[n] = d; while (1) { if ((A[s] == s || (A[s] == -1 && !(f & 1U << s))) && (d + best[s] >= best[n] || A[s] == -1)) break;   if (d + best[s] <= best[n]) return; if (!--s) return; }   d++; deck b = *a; for (uint i = 1, k = 2; i <= s; k <<= 1, i++) { if (A[i] != i && (A[i] != -1 || (f & k))) continue;   for (uint j = B[0] = i; j--;) B[i - j] = A[j]; tryswaps(&b, f | k, s); } d--; }   int main(void) { deck x; memset(&x, -1, sizeof(x)); x.v[0] = 0;   for (n = 1; n < 13; n++) { tryswaps(&x, 1, n - 1); printf("%2d: %d\n", n, best[n]); }   return 0; }
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that 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.
#Arturo
Arturo
pi: 4*atan 1.0   radians: pi/4 degrees: 45.0   print "sine" print [sin radians, sin degrees*pi/180]   print "cosine" print [cos radians, cos degrees*pi/180]   print "tangent" print [tan radians, tan degrees*pi/180]   print "arcsine" print [asin sin radians, (asin sin radians)*180/pi]   print "arccosine" print [acos cos radians, (acos cos radians)*180/pi]   print "arctangent" print [atan tan radians, (atan tan radians)*180/pi]
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm. From the wikipedia entry: ask for 11 numbers to be read into a sequence S reverse sequence S for each item in sequence S result := call a function to do an operation if result overflows alert user else print result The task is to implement the algorithm: Use the function:     f ( x ) = | x | 0.5 + 5 x 3 {\displaystyle f(x)=|x|^{0.5}+5x^{3}} The overflow condition is an answer of greater than 400. The 'user alert' should not stop processing of other items of the sequence. Print a prompt before accepting eleven, textual, numeric inputs. You may optionally print the item as well as its associated result, but the results must be in reverse order of input. The sequence   S   may be 'implied' and so not shown explicitly. Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#AutoIt
AutoIt
; Trabb Pardo–Knuth algorithm ; by James1337 (autoit.de) ; AutoIt Version: 3.3.8.1   Local $S, $i, $y   Do $S = InputBox("Trabb Pardo–Knuth algorithm", "Please enter 11 numbers:", "1 2 3 4 5 6 7 8 9 10 11") If @error Then Exit $S = StringSplit($S, " ") Until ($S[0] = 11)   For $i = 11 To 1 Step -1 $y = f($S[$i]) If ($y > 400) Then ConsoleWrite("f(" & $S[$i] & ") = Overflow!" & @CRLF) Else ConsoleWrite("f(" & $S[$i] & ") = " & $y & @CRLF) EndIf Next   Func f($x) Return Sqrt(Abs($x)) + 5*$x^3 EndFunc
http://rosettacode.org/wiki/Twelve_statements
Twelve statements
This puzzle is borrowed from   math-frolic.blogspot. Given the following twelve statements, which of them are true? 1. This is a numbered list of twelve statements. 2. Exactly 3 of the last 6 statements are true. 3. Exactly 2 of the even-numbered statements are true. 4. If statement 5 is true, then statements 6 and 7 are both true. 5. The 3 preceding statements are all false. 6. Exactly 4 of the odd-numbered statements are true. 7. Either statement 2 or 3 is true, but not both. 8. If statement 7 is true, then 5 and 6 are both true. 9. Exactly 3 of the first 6 statements are true. 10. The next two statements are both true. 11. Exactly 1 of statements 7, 8 and 9 are true. 12. Exactly 4 of the preceding statements are true. Task When you get tired of trying to figure it out in your head, write a program to solve it, and print the correct answer or answers. Extra credit Print out a table of near misses, that is, solutions that are contradicted by only a single statement.
#jq
jq
def indexed(filter): . as $in | reduce range(0;length) as $i ([]; if ($i | filter) then . + [$in[$i]] else . end);   def count(value): map(select(. == value)) | length;   # The truth or falsity of the 12 statements can be captured in an array of size 12: def generate(k): if k == 1 then [true], [false] else generate(1) + generate(k-1) end;   # Input: a boolean array def evaluate: [ (length == 12), #1 ((.[6:] | count(true)) == 3), #2 ((indexed(. % 2 == 1) | count(true)) == 2), #3 (if .[4] then .[5] and .[6] else true end), #4 ((.[1:4] | count(false)) == 3), #5 ((indexed(. % 2 == 0) | count(true)) == 4), #6 (([.[1], .[2]] | count(true)) == 1), #7 (if .[6] then .[4] and .[5] else true end), #8 ((.[0:6] | count(true)) == 3), #9 (.[10] and .[11]), #10 ((.[6:9] | count(true)) == 1), #11 ((.[0:11] | count(true)) == 4) #12 ];   # The following query generates the solution to the problem: # generate(12) | . as $vector | if evaluate == $vector then $vector else empty end   # Running "task" as defined next would generate # both the general solution as well as the off-by-one solutions:   def task:   # count agreements def agreed(x;y): reduce range(0;x|length) as $i (0; if x[$i] == y[$i] then .+1 else . end);   reduce generate(12) as $vector ([]; ($vector | evaluate) as $e | agreed($vector; $e) as $agreed | if $agreed == 12 then [[12,$vector]] + . elif $agreed == 11 then . + [[11, $vector]] else . end);   # Since the solutions have been given elsewhere, we simply count the # number of exact and off-by-one solutions:   task | length
http://rosettacode.org/wiki/Twelve_statements
Twelve statements
This puzzle is borrowed from   math-frolic.blogspot. Given the following twelve statements, which of them are true? 1. This is a numbered list of twelve statements. 2. Exactly 3 of the last 6 statements are true. 3. Exactly 2 of the even-numbered statements are true. 4. If statement 5 is true, then statements 6 and 7 are both true. 5. The 3 preceding statements are all false. 6. Exactly 4 of the odd-numbered statements are true. 7. Either statement 2 or 3 is true, but not both. 8. If statement 7 is true, then 5 and 6 are both true. 9. Exactly 3 of the first 6 statements are true. 10. The next two statements are both true. 11. Exactly 1 of statements 7, 8 and 9 are true. 12. Exactly 4 of the preceding statements are true. Task When you get tired of trying to figure it out in your head, write a program to solve it, and print the correct answer or answers. Extra credit Print out a table of near misses, that is, solutions that are contradicted by only a single statement.
#Julia
Julia
using Printf   function showflaggedbits{T<:BitArray{1}}(a::T, f::T) tf = map(x->x ? "T" : "F", a) flg = map(x->x ? "*" : " ", f) join(tf .* flg, " ") end   const props = [s -> length(s) == 12, s -> sum(s[7:12]) == 3, s -> sum(s[2:2:end]) == 2, s -> !s[5] || (s[6] & s[7]), s -> !any(s[2:4]), s -> sum(s[1:2:end]) == 4, s -> s[2] $ s[3], s -> !s[7] || (s[5] & s[6]), s -> sum(s[1:6]) == 3, s -> s[11] & s[12], s -> sum(s[7:9]) == 1, s -> sum(s[1:end-1]) == 4]   const NDIG = length(props) NDIG < WORD_SIZE || println("WARNING, too many propositions!")   mhist = zeros(Int, NDIG+1)   println("Checking the ", NDIG, " statements against all possibilities.\n") print(" "^15) for i in 1:NDIG print(@sprintf "%3d" i) end println()   for i in 0:(2^NDIG-1) s = bitpack(digits(i, 2, NDIG)) t = bitpack([p(s) for p in props]) misses = s$t mcnt = sum(misses) mhist[NDIG-mcnt+1] += 1 mcnt < 2 || mcnt == NDIG || continue if mcnt == 0 print(" Exact Match: ") elseif mcnt == NDIG print(" Total Miss: ") else print(" Near Miss: ") end println(showflaggedbits(t, misses)) end   println() println("Distribution of matches") println(" Matches Cases") for i in (NDIG+1):-1:1 println(@sprintf "  %2d => %4d" i-1 mhist[i]) 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.
#JavaScript
JavaScript
<!DOCTYPE html><html><head><title>Truth table</title><script> var elem,expr,vars; function isboolop(chr){return "&|!^".indexOf(chr)!=-1;} function varsindexof(chr){ var i; for(i=0;i<vars.length;i++){if(vars[i][0]==chr)return i;} return -1; } function printtruthtable(){ var i,str; elem=document.createElement("pre"); expr=prompt("Boolean expression:\nAccepts single-character variables (except for \"T\" and \"F\", which specify explicit true or false values), postfix, with \"&|!^\" for and, or, not, xor, respectively; optionally seperated by whitespace.").replace(/\s/g,""); vars=[]; for(i=0;i<expr.length;i++)if(!isboolop(expr[i])&&expr[i]!="T"&&expr[i]!="F"&&varsindexof(expr[i])==-1)vars.push([expr[i],-1]); if(vars.length==0)return; str=""; for(i=0;i<vars.length;i++)str+=vars[i][0]+" "; elem.innerHTML="<b>"+str+expr+"</b>\n"; vars[0][1]=false; truthpartfor(1); vars[0][1]=true; truthpartfor(1); vars[0][1]=-1; document.body.appendChild(elem); } function truthpartfor(index){ if(index==vars.length){ var str,i; str=""; for(i=0;i<index;i++)str+=(vars[i][1]?"<b>T</b>":"F")+" "; elem.innerHTML+=str+(parsebool()?"<b>T</b>":"F")+"\n"; return; } vars[index][1]=false; truthpartfor(index+1); vars[index][1]=true; truthpartfor(index+1); vars[index][1]=-1; } function parsebool(){ var stack,i,idx; console.log(vars); stack=[]; for(i=0;i<expr.length;i++){ if(expr[i]=="T")stack.push(true); else if(expr[i]=="F")stack.push(false); else if((idx=varsindexof(expr[i]))!=-1)stack.push(vars[idx][1]); else if(isboolop(expr[i])){ switch(expr[i]){ case "&":stack.push(stack.pop()&stack.pop());break; case "|":stack.push(stack.pop()|stack.pop());break; case "!":stack.push(!stack.pop());break; case "^":stack.push(stack.pop()^stack.pop());break; } } else alert("Non-conformant character "+expr[i]+" in expression. Should not be possible."); console.log(stack); } return stack[0]; } </script></head><body onload="printtruthtable()"></body></html>
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
#Julia
Julia
using Primes   function ulamspiral(ord::Int) # Possible directions dirs = [[0, 1], [-1, 0], [0, -1], [1, 0]] # fdir = ["→", "↑", "←", "↓"] # for debug pourpose cur = maxsteps = 1 # starting direction & starting max steps steps = n = 0 # starting steps & starting number in cell pos = [ord ÷ 2 + 1, isodd(ord) ? ord ÷ 2 + 1 : ord ÷ 2] # starting position M = Matrix{Bool}(ord, ord) # result matrix while n < ord ^ 2 # main loop (stop when the matrix is filled) n += 1 M[pos[1], pos[2]] = isprime(n) steps += 1 # Debug print # @printf("M[%i, %i] = %5s (%2i), step %i/%i, nxt %s\n", pos[1], pos[2], isprime(n), n, steps, maxsteps, fdir[cur]) pos .+= dirs[cur] # increment position if steps == maxsteps # if reached max number of steps in that direction... steps = 0 # ...reset steps if iseven(cur) maxsteps += 1 end # if the current direction is even increase the number of steps cur += 1 # change direction if cur > 4 cur -= 4 end # correct overflow end end return M end   mprint(m::Matrix) = for i in 1:size(m, 1) println(join(el ? " ∙ " : " " for el in m[i, :]), '\n') end   M = ulamspiral(9) mprint(M)
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.]
#EchoLisp
EchoLisp
  ;; does p include a 0 in its decimal representation ? (define (nozero? n) (= -1 (string-index (number->string n) "0")))   ;; right truncate : p and successive quotients by 10 (integer division) must be primes (define (right-trunc p) (unless (zero? p) (and (prime? p) (right-trunc (quotient p 10))))) (remember 'right-trunc)   ;; left truncate : p and successive modulo by 10, 100, .. must be prime (define (left-trunc p (mod 1000000)) (unless (< mod 1) (and (prime? p) (nozero? p) (left-trunc (modulo p mod) (/ mod 10)))))   ;; start from 999999. stop on first found (define (fact-trunc trunc) (for ((p (in-range 999999 100000 -1))) #:break (when (trunc p) (writeln p) #t)))  
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#Scala
Scala
import java.io.FileOutputStream   object TruncFile extends App { if (args.length < 2) println("Usage: java TruncFile fileName newSize") else { //turn on "append" so it doesn't clear the file val outChan = new FileOutputStream(args(0), true).getChannel() val newSize = args(1).toLong outChan.truncate(newSize) } }
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#Sidef
Sidef
func truncate(filename, len) { var file = File(filename); len > file.size -> && die "The provided length is greater than the length of the file"; file.truncate(len); }   # truncate "file.ext" to 1234 bytes truncate("file.ext", 1234);
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.
#C.2B.2B
C++
  #include <vector> #include <string> #include <iostream> #include <algorithm> #include <fstream> #include <iomanip> //-------------------------------------------------------------------------------------------------- typedef unsigned int uint; using namespace std; const uint TAPE_MAX_LEN = 49152; //-------------------------------------------------------------------------------------------------- struct action { char write, direction; }; //-------------------------------------------------------------------------------------------------- class tape { public: tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); } void reset() { clear( '0' ); headPos = _sp; } char read(){ return _t[headPos]; } void input( string a ){ if( a == "" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; } void clear( char c ) { _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); } void action( const action* a ) { write( a->write ); move( a->direction ); } void print( int c = 10 ) { int ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx; for( int x = st; x < ed; x++ ) { tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } cout << endl << setw( c + 1 ) << "^" << endl; } private: void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; } void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } } string _t; uint headPos, _sp; char blk; const uint MAX_LEN; }; //-------------------------------------------------------------------------------------------------- class state { public: bool operator ==( const string o ) { return o == name; } string name, next; char symbol, write, direction; }; //-------------------------------------------------------------------------------------------------- class actionTable { public: bool loadTable( string file ) { reset(); ifstream mf; mf.open( file.c_str() ); if( mf.is_open() ) { string str; state stt; while( mf.good() ) { getline( mf, str ); if( str[0] == '\'' ) break; parseState( str, stt ); states.push_back( stt ); } while( mf.good() ) { getline( mf, str ); if( str == "" ) continue; if( str[0] == '!' ) blank = str.erase( 0, 1 )[0]; if( str[0] == '^' ) curState = str.erase( 0, 1 ); if( str[0] == '>' ) input = str.erase( 0, 1 ); } mf.close(); return true; } cout << "Could not open " << file << endl; return false; }   bool action( char symbol, action& a ) { vector<state>::iterator f = states.begin(); while( true ) { f = find( f, states.end(), curState ); if( f == states.end() ) return false; if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) ) { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; } f++; } return true; } void reset() { states.clear(); blank = '0'; curState = input = ""; } string getInput() { return input; } char getBlank() { return blank; } private: void parseState( string str, state& stt ) { string a[5]; int idx = 0; for( string::iterator si = str.begin(); si != str.end(); si++ ) { if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); } stt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4]; } vector<state> states; char blank; string curState, input; }; //-------------------------------------------------------------------------------------------------- class utm { public: utm() { files[0] = "incrementer.utm"; files[1] = "busy_beaver.utm"; files[2] = "sort.utm"; } void start() { while( true ) { reset(); int t = showMenu(); if( t == 0 ) return; if( !at.loadTable( files[t - 1] ) ) return; startMachine(); } } private: void simulate() { char r; action a; while( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); } cout << endl << endl; system( "pause" ); }   int showMenu() { int t = -1; while( t < 0 || t > 3 ) { system( "cls" ); cout << "1. Incrementer\n2. Busy beaver\n3. Sort\n\n0. Quit"; cout << endl << endl << "Choose an action "; cin >> t; } return t; }   void reset() { tp.reset(); at.reset(); } void startMachine() { system( "cls" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }   tape tp; actionTable at; string files[7]; }; //-------------------------------------------------------------------------------------------------- int main( int a, char* args[] ){ utm mm; mm.start(); return 0; } //--------------------------------------------------------------------------------------------------  
http://rosettacode.org/wiki/Totient_function
Totient function
The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the integers up to a given positive integer   n   that are relatively prime to   n   counts the integers   k   in the range   1 ≤ k ≤ n   for which the greatest common divisor   gcd(n,k)   is equal to   1   counts numbers   ≤ n   and   prime to   n If the totient number   (for N)   is one less than   N,   then   N   is prime. Task Create a   totient   function and:   Find and display   (1 per line)   for the 1st   25   integers:   the integer   (the index)   the totient number for that integer   indicate if that integer is prime   Find and display the   count   of the primes up to          100   Find and display the   count   of the primes up to       1,000   Find and display the   count   of the primes up to     10,000   Find and display the   count   of the primes up to   100,000     (optional) Show all output here. Related task   Perfect totient numbers Also see   Wikipedia: Euler's totient function.   MathWorld: totient function.   OEIS: Euler totient function phi(n).
#ALGOL_68
ALGOL 68
BEGIN # returns the number of integers k where 1 <= k <= n that are mutually prime to n # PROC totient = ( INT n )INT: IF n < 3 THEN 1 ELIF n = 3 THEN 2 ELSE INT result := n; INT v := n; INT i := 2; WHILE i * i <= v DO IF v MOD i = 0 THEN WHILE v MOD i = 0 DO v OVERAB i OD; result -:= result OVER i FI; IF i = 2 THEN i := 1 FI; i +:= 2 OD; IF v > 1 THEN result -:= result OVER v FI; result FI # totient # ; # show the totient function values for the first 25 integers # print( ( " n phi(n) remarks", newline ) ); FOR n TO 25 DO INT tn = totient( n ); print( ( whole( n, -2 ), ": ", whole( tn, -5 ), IF tn = n - 1 AND tn /= 0 THEN " n is prime" ELSE "" FI, newline ) ) OD; # use the totient function to count primes # INT n100 := 0, n1000 := 0, n10000 := 0, n100000 := 0; FOR n TO 100 000 DO IF totient( n ) = n - 1 THEN IF n <= 100 THEN n100 +:= 1 FI; IF n <= 1 000 THEN n1000 +:= 1 FI; IF n <= 10 000 THEN n10000 +:= 1 FI; IF n <= 100 000 THEN n100000 +:= 1 FI FI OD; print( ( "There are ", whole( n100, -6 ), " primes below 100", newline ) ); print( ( "There are ", whole( n1000, -6 ), " primes below 1 000", newline ) ); print( ( "There are ", whole( n10000, -6 ), " primes below 10 000", newline ) ); print( ( "There are ", whole( n100000, -6 ), " primes below 100 000", newline ) ) 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
#C.2B.2B
C++
  #include <iostream> #include <vector> #include <numeric> #include <algorithm>   int topswops(int n) { std::vector<int> list(n); std::iota(std::begin(list), std::end(list), 1); int max_steps = 0; do { auto temp_list = list; for (int steps = 1; temp_list[0] != 1; ++steps) { std::reverse(std::begin(temp_list), std::begin(temp_list) + temp_list[0]); if (steps > max_steps) max_steps = steps; } } while (std::next_permutation(std::begin(list), std::end(list))); return max_steps; }   int main() { for (int i = 1; i <= 10; ++i) { std::cout << i << ": " << topswops(i) << std::endl; } return 0; }
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that 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.
#Asymptote
Asymptote
real pi = 4 * atan(1); real radian = pi / 4.0; real angulo = 45.0 * pi / 180;   write("Radians  : ", radian); write("Degrees  : ", angulo / pi * 180); write(); write("Sine  : ", sin(radian), sin(angulo)); write("Cosine  : ", cos(radian), cos(angulo)); write("Tangent  : ", tan(radian), tan(angulo)); write(); real temp = asin(sin(radian)); write("Arc Sine  : ", temp, temp * 180 / pi); temp = acos(cos(radian)); write("Arc Cosine  : ", temp, temp * 180 / pi); temp = atan(tan(radian)); write("Arc Tangent : ", temp, temp * 180 / pi);
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm. From the wikipedia entry: ask for 11 numbers to be read into a sequence S reverse sequence S for each item in sequence S result := call a function to do an operation if result overflows alert user else print result The task is to implement the algorithm: Use the function:     f ( x ) = | x | 0.5 + 5 x 3 {\displaystyle f(x)=|x|^{0.5}+5x^{3}} The overflow condition is an answer of greater than 400. The 'user alert' should not stop processing of other items of the sequence. Print a prompt before accepting eleven, textual, numeric inputs. You may optionally print the item as well as its associated result, but the results must be in reverse order of input. The sequence   S   may be 'implied' and so not shown explicitly. Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#AWK
AWK
  # syntax: GAWK -f TRABB_PARDO-KNUTH_ALGORITHM.AWK BEGIN { printf("enter 11 numbers: ") getline S n = split(S,arr," ") if (n != 11) { printf("%d numbers entered; S/B 11\n",n) exit(1) } for (i=n; i>0; i--) { x = f(arr[i]) printf("f(%s) = %s\n",arr[i],(x>400) ? "too large" : x) } exit(0) } function abs(x) { if (x >= 0) { return x } else { return -x } } function f(x) { return sqrt(abs(x)) + 5 * x ^ 3 }  
http://rosettacode.org/wiki/Twelve_statements
Twelve statements
This puzzle is borrowed from   math-frolic.blogspot. Given the following twelve statements, which of them are true? 1. This is a numbered list of twelve statements. 2. Exactly 3 of the last 6 statements are true. 3. Exactly 2 of the even-numbered statements are true. 4. If statement 5 is true, then statements 6 and 7 are both true. 5. The 3 preceding statements are all false. 6. Exactly 4 of the odd-numbered statements are true. 7. Either statement 2 or 3 is true, but not both. 8. If statement 7 is true, then 5 and 6 are both true. 9. Exactly 3 of the first 6 statements are true. 10. The next two statements are both true. 11. Exactly 1 of statements 7, 8 and 9 are true. 12. Exactly 4 of the preceding statements are true. Task When you get tired of trying to figure it out in your head, write a program to solve it, and print the correct answer or answers. Extra credit Print out a table of near misses, that is, solutions that are contradicted by only a single statement.
#Kotlin
Kotlin
// version 1.1.3   typealias Predicate = (String) -> Boolean   val predicates = listOf<Predicate>( { it.length == 13 }, // indexing starts at 0 but first bit ignored { (7..12).count { i -> it[i] == '1' } == 3 }, { (2..12 step 2).count { i -> it[i] == '1' } == 2 }, { it[5] == '0' || (it[6] == '1' && it[7] == '1') }, { it[2] == '0' && it[3] == '0' && it[4] == '0' }, { (1..11 step 2).count { i -> it[i] == '1' } == 4 }, { (it[2] == '1') xor (it[3] == '1') }, { it[7] == '0' || (it[5] == '1' && it[6] == '1') }, { (1..6).count { i -> it[i] == '1' } == 3 }, { it[11] == '1' && it[12] == '1' }, { (7..9).count { i -> it[i] == '1' } == 1 }, { (1..11).count { i -> it[i] == '1' } == 4 } )   fun show(s: String, indent: Boolean) { if (indent) print(" ") for (i in s.indices) if (s[i] == '1') print("$i ") println() }   fun main(args: Array<String>) { println("Exact hits:") for (i in 0..4095) { val s = i.toString(2).padStart(13, '0') var j = 1 if (predicates.all { it(s) == (s[j++] == '1') }) show(s, true) }   println("\nNear misses:") for (i in 0..4095) { val s = i.toString(2).padStart(13, '0') var j = 1 if (predicates.count { it(s) == (s[j++] == '1') } == 11) { var k = 1 val iof = predicates.indexOfFirst { it(s) != (s[k++] == '1') } + 1 print(" (Fails at statement ${"%2d".format(iof)}) ") show(s, false) } } }
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.
#Julia
Julia
module TruthTable   using Printf using MacroTools   isvariablename(::Any) = false isvariablename(s::Symbol) = all(x -> isletter(x) || x == '_', string(s))   function table(expr) if !isvariablename(expr) && !Meta.isexpr(expr, :call) throw(ArgumentError("expr must be a boolean expression")) end   exprstr = string(expr) # Collect variable names symset = Set{Symbol}() MacroTools.prewalk(expr) do node isvariablename(node) && push!(symset, node) return node end symlist = collect(symset)   # Create assignment assertions + evaluate blocks = Vector{Expr}(undef, 2 ^ length(symlist) + 1) blocks[1] = quote println(join(lpad.($(symlist), 6), " | "), " || ", $exprstr) end for (i, tup) in enumerate(Iterators.product(Iterators.repeated((false, true), length(symlist))...)) blocks[i + 1] = quote let $(Expr(:(=), Expr(:tuple, symlist...), Expr(:tuple, tup...))) println(join(lpad.($(Expr(:tuple, symlist...)), 6), " | "), " || ", lpad($expr, $(length(exprstr)))) end end end   return esc(Expr(:block, blocks...)) end   macro table(expr) return table(expr) end   end # module TruthTable
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
#Kotlin
Kotlin
object Ulam { fun generate(n: Int, i: Int = 1, c: Char = '*') { require(n > 1) val s = Array(n) { Array(n, { "" }) } var dir = Direction.RIGHT var y = n / 2 var x = if (n % 2 == 0) y - 1 else y // shift left for even n's for (j in i..n * n - 1 + i) { s[y][x] = if (isPrime(j)) if (c.isDigit()) "%4d".format(j) else " $c " else " ---"   when (dir) { Direction.RIGHT -> if (x <= n - 1 && s[y - 1][x].none() && j > i) dir = Direction.UP Direction.UP -> if (s[y][x - 1].none()) dir = Direction.LEFT Direction.LEFT -> if (x == 0 || s[y + 1][x].none()) dir = Direction.DOWN Direction.DOWN -> if (s[y][x + 1].none()) dir = Direction.RIGHT }   when (dir) { Direction.RIGHT -> x++ Direction.UP -> y-- Direction.LEFT -> x-- Direction.DOWN -> y++ } } for (row in s) println("[" + row.joinToString("") + ']') println() }   private enum class Direction { RIGHT, UP, LEFT, DOWN }   private fun isPrime(a: Int): Boolean { when { a == 2 -> return true a <= 1 || a % 2 == 0 -> return false else -> { val max = Math.sqrt(a.toDouble()).toInt() for (n in 3..max step 2) if (a % n == 0) return false return true } } } }   fun main(args: Array<String>) { Ulam.generate(9, c = '0') Ulam.generate(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.]
#Eiffel
Eiffel
  class APPLICATION   create make   feature   make do io.put_string ("Largest right truncatable prime: " + find_right_truncatable_primes.out) io.new_line io.put_string ("Largest left truncatable prime: " + find_left_truncatable_primes.out) end   find_right_truncatable_primes: INTEGER -- Largest right truncatable prime below 1000000. local i, maybe_prime: INTEGER found, is_one: BOOLEAN do from i := 999999 until found loop is_one := True from maybe_prime := i until not is_one or maybe_prime.out.count = 1 loop if maybe_prime.out.has ('0') or maybe_prime.out.has ('2') or maybe_prime.out.has ('4') or maybe_prime.out.has ('6') or maybe_prime.out.has ('8') then is_one := False else if not is_prime (maybe_prime) then is_one := False elseif is_prime (maybe_prime) and maybe_prime.out.count > 1 then maybe_prime := truncate_right (maybe_prime) end end end if is_one then found := True Result := i end i := i - 2 end ensure Result_is_smaller: Result < 1000000 end   find_left_truncatable_primes: INTEGER -- Largest left truncatable prime below 1000000. local i, maybe_prime: INTEGER found, is_one: BOOLEAN do from i := 999999 until found loop is_one := True from maybe_prime := i until not is_one or maybe_prime.out.count = 1 loop if not is_prime (maybe_prime) then is_one := False elseif is_prime (maybe_prime) and maybe_prime.out.count > 1 then if maybe_prime.out.at (2) = '0' then is_one := False else maybe_prime := truncate_left (maybe_prime) end end end if is_one then found := True Result := i end i := i - 2 end ensure Result_is_smaller: Result < 1000000 end   feature {NONE}   is_prime (n: INTEGER): BOOLEAN --Is 'n' a prime number? require positiv_input: n > 0 local i: INTEGER max: REAL_64 math: DOUBLE_MATH do create math if n = 2 then Result := True elseif n <= 1 or n \\ 2 = 0 then Result := False else Result := True max := math.sqrt (n) from i := 3 until i > max loop if n \\ i = 0 then Result := False end i := i + 2 end end end   truncate_left (n: INTEGER): INTEGER -- 'n' truncated by one digit from the left side. require truncatable: n.out.count > 1 local st: STRING do st := n.out st.remove_head (1) Result := st.to_integer ensure Result_truncated: Result.out.count = n.out.count - 1 end   truncate_right (n: INTEGER): INTEGER -- 'n' truncated by one digit from the right side. require truncatable: n.out.count > 1 local st: STRING do st := n.out st.remove_tail (1) Result := st.to_integer ensure Result_truncated: Result.out.count = n.out.count - 1 end   end  
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#Standard_ML
Standard ML
local open Posix.FileSys val perm = S.flags [S.irusr, S.iwusr, S.irgrp, S.iwgrp, S.iroth, S.iwoth] in fun truncate (path, len) = let val fd = createf (path, O_WRONLY, O.noctty, perm) in ftruncate (fd, len); Posix.IO.close fd end end
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#Tcl
Tcl
package require Tcl 8.5   set f [open "file" r+]; # Truncation is done on channels chan truncate $f 1234; # Truncate at a particular length (in bytes) close $f
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#UNIX_Shell
UNIX Shell
# Truncate a file named "myfile" to 1440 kilobytes. ls myfile >/dev/null && dd if=/dev/null of=myfile bs=1 seek=1440k
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.
#11l
11l
T Node Int data Node? left Node? right   F (data, Node? left = N, Node? right = N) .data = data .left = left .right = right   F preorder(visitor) -> N visitor(.data) I .left != N .left.preorder(visitor) I .right != N .right.preorder(visitor)   F inorder(visitor) -> N I .left != N .left.inorder(visitor) visitor(.data) I .right != N .right.inorder(visitor)   F postorder(visitor) -> N I .left != N .left.postorder(visitor) I .right != N .right.postorder(visitor) visitor(.data)   F preorder2(&d, level = 0) -> N d[level].append(.data) I .left != N .left.preorder2(d, level + 1) I .right != N .right.preorder2(d, level + 1)   F levelorder(visitor) DefaultDict[Int, [Int]] d .preorder2(&d) L(k) sorted(d.keys()) L(v) d[k] visitor(v)   V tree = Node(1, Node(2, Node(4, Node(7, N, N), N), Node(5, N, N)), Node(3, Node(6, Node(8, N, N), Node(9, N, N)), N))   F printwithspace(Int i) print(‘#. ’.format(i), end' ‘’)   print(‘ preorder: ’, end' ‘’) tree.preorder(printwithspace) print() print(‘ inorder: ’, end' ‘’) tree.inorder(printwithspace) print() print(‘ postorder: ’, end' ‘’) tree.postorder(printwithspace) print() print(‘levelorder: ’, end' ‘’) tree.levelorder(printwithspace) print()
http://rosettacode.org/wiki/Topic_variable
Topic variable
Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language. For instance you can (but you don't have to) show how the topic variable can be used by assigning the number 3 {\displaystyle 3} to it and then computing its square and square root.
#AppleScript
AppleScript
on run 1 + 2   ap({square, squareRoot}, {result})   --> {9, 1.732050807569} end run     -- square :: Num a => a -> a on square(x) x * x end square   -- squareRoot :: Num a, Float b => a -> b on squareRoot(x) x ^ 0.5 end squareRoot     -- GENERIC FUNCTIONS ----------------------------------------------------------   -- A list of functions applied to a list of arguments -- (<*> | ap) :: [(a -> b)] -> [a] -> [b] on ap(fs, xs) set lst to {} repeat with f in fs tell mReturn(contents of f) repeat with x in xs set end of lst to |λ|(contents of x) end repeat end tell end repeat return lst end ap   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn
http://rosettacode.org/wiki/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.
#Clojure
Clojure
  (defn tape "Creates a new tape with given blank character and tape contents" ([blank] (tape () blank () blank)) ([right blank] (tape () (first right) (rest right) blank)) ([left head right blank] [(reverse left) (or head blank) (into () right) blank]))   ; Tape operations (defn- left [[[l & ls] _ rs b] c] [ls (or l b) (conj rs c) b]) (defn- right [[ls _ [r & rs] b] c] [(conj ls c) (or r b) rs b]) (defn- stay [[ls _ rs b] c] [ls c rs b]) (defn- head [[_ c _ b]] (or c b)) (defn- pretty [[ls c rs b]] (concat (reverse ls) [[(or c b)]] rs))   (defn new-machine "Returns a function that takes a tape as input, and returns the tape after running the machine specified in `machine`." [machine] (let [rules (into {} (for [[s c c' a s'] (:rules machine)] [[s c] [c' (-> a name symbol resolve) s']])) finished? (into #{} (:terminating machine))] (fn [input-tape] (loop [state (:initial machine) tape input-tape] (if (finished? state) (pretty tape) (let [[out action new-state] (get rules [state (head tape)])] (recur new-state (action tape out))))))))  
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).
#ALGOL-M
ALGOL-M
  BEGIN   % RETURN P MOD Q  % INTEGER FUNCTION MOD (P, Q); INTEGER P, Q; BEGIN MOD := P - Q * (P / Q); END;   % RETURN GREATEST COMMON DIVISOR OF X AND Y  % INTEGER FUNCTION GCD (X, Y); INTEGER X, Y; BEGIN INTEGER R; IF X < Y THEN BEGIN INTEGER TEMP; TEMP := X; X := Y; Y := TEMP; END; WHILE (R := MOD(X, Y)) <> 0 DO BEGIN X := Y; Y := R; END; GCD := Y; END;   % RETURN PHI (ALSO CALLED TOTIENT) OF N % INTEGER FUNCTION PHI(N); INTEGER N; BEGIN INTEGER I, COUNT; COUNT := 1; FOR I := 2 STEP 1 UNTIL N DO BEGIN IF GCD(N,I) = 1 THEN COUNT := COUNT + 1; END; PHI := COUNT; END;     COMMENT - EXERCISE THE FUNCTION; INTEGER N, TOTIENT, COUNT; WRITE(" N PHI(N) PRIME?"); FOR N := 1 STEP 1 UNTIL 25 DO BEGIN WRITE(N, (TOTIENT := PHI(N))); WRITEON(IF TOTIENT = (N-1) THEN " YES" ELSE " NO"); END;   COMMENT - AND USE IT TO COUNT PRIMES; WRITE(""); COUNT := 0; FOR N := 1 STEP 1 UNTIL 1000 DO BEGIN IF PHI(N) = (N-1) THEN COUNT := COUNT + 1; IF N = 100 THEN WRITE("PRIMES UP TO 100 =", COUNT) ELSE IF N = 1000 THEN WRITE("PRIMES UP TO 1000 =", COUNT); END;     END  
http://rosettacode.org/wiki/Topswops
Topswops
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is composed of reversing the first   m   cards where   m   is the value of the topmost card. Rounds are repeated until the topmost card is the number   1   and the number of swaps is recorded. For our example the swaps produce: [2, 4, 1, 3] # Initial shuffle [4, 2, 1, 3] [3, 1, 2, 4] [2, 1, 3, 4] [1, 2, 3, 4] For a total of four swaps from the initial ordering to produce the terminating case where   1   is on top. For a particular number   n   of cards,   topswops(n)   is the maximum swaps needed for any starting permutation of the   n   cards. Task The task is to generate and show here a table of   n   vs   topswops(n)   for   n   in the range   1..10   inclusive. Note Topswops   is also known as   Fannkuch   from the German word   Pfannkuchen   meaning   pancake. Related tasks   Number reversal game   Sorting algorithms/Pancake sort
#D
D
import std.stdio, std.algorithm, std.range, permutations2;   int topswops(in int n) pure @safe { static int flip(int[] xa) pure nothrow @safe @nogc { if (!xa[0]) return 0; xa[0 .. xa[0] + 1].reverse(); return 1 + flip(xa); } return n.iota.array.permutations.map!flip.reduce!max; }   void main() { foreach (immutable i; 1 .. 11) writeln(i, ": ", i.topswops); }
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.
#AutoHotkey
AutoHotkey
pi := 4 * atan(1) radians := pi / 4 degrees := 45.0 result .= "`n" . sin(radians) . " " . sin(degrees * pi / 180) result .= "`n" . cos(radians) . " " . cos(degrees * pi / 180) result .= "`n" . tan(radians) . " " . tan(degrees * pi / 180)   temp := asin(sin(radians)) result .= "`n" . temp . " " . temp * 180 / pi   temp := acos(cos(radians)) result .= "`n" . temp . " " . temp * 180 / pi   temp := atan(tan(radians)) result .= "`n" . temp . " " . temp * 180 / pi   msgbox % result /* output --------------------------- trig.ahk --------------------------- 0.707107 0.707107 0.707107 0.707107 1.000000 1.000000 0.785398 45.000000 0.785398 45.000000 0.785398 45.000000 */
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).
#BASIC
BASIC
  10 REM Trabb Pardo-Knuth algorithm 20 REM Used "magic numbers" because of strict specification 30 REM 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 I+1; "- Enter number"; 90 INPUT S(I) 100 NEXT I 110 PRINT 120 REM Reverse 130 FOR I = 0 TO 10/2 140 LET T = S(I) 150 LET S(I) = S(10-I) 160 LET S(10-I) = T 170 NEXT I 180 REM Results 190 PRINT "num", "f(num)" 200 FOR I = 0 TO 10 210 LET R = FNF(S(I)) 220 IF R>400 THEN 250 230 PRINT S(I), R 240 GOTO 260 250 PRINT S(I), " overflow" 260 NEXT I 270 END  
http://rosettacode.org/wiki/Twelve_statements
Twelve statements
This puzzle is borrowed from   math-frolic.blogspot. Given the following twelve statements, which of them are true? 1. This is a numbered list of twelve statements. 2. Exactly 3 of the last 6 statements are true. 3. Exactly 2 of the even-numbered statements are true. 4. If statement 5 is true, then statements 6 and 7 are both true. 5. The 3 preceding statements are all false. 6. Exactly 4 of the odd-numbered statements are true. 7. Either statement 2 or 3 is true, but not both. 8. If statement 7 is true, then 5 and 6 are both true. 9. Exactly 3 of the first 6 statements are true. 10. The next two statements are both true. 11. Exactly 1 of statements 7, 8 and 9 are true. 12. Exactly 4 of the preceding statements are true. Task When you get tired of trying to figure it out in your head, write a program to solve it, and print the correct answer or answers. Extra credit Print out a table of near misses, that is, solutions that are contradicted by only a single statement.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Print["Answer:\n", Column@Cases[#, {s_, 0} :> s], "\nNear misses:\n", Column@Cases[#, {s_, 1} :> s]] &[{#, Count[Boole /@ {Length@# == 12, Total@#[[7 ;;]] == 3, Total@#[[2 ;; 12 ;; 2]] == 2, #[[5]] (#[[6]] + #[[7]] - 2) == 0, Total@#[[2 ;; 4]] == 0, Total@#[[1 ;; 11 ;; 2]] == 4, #[[2]] + #[[3]] == 1, #[[7]] (#[[5]] + #[[6]] - 2) == 0, Total@#[[;; 6]] == 3, #[[11]] + #[[12]] == 2, Total@#[[7 ;; 9]] == 1, Total@#[[;; 11]] == 4} - #, Except[0]]} & /@ Tuples[{1, 0}, 12]]
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.
#Kotlin
Kotlin
// Version 1.2.31   import java.util.Stack   class Variable(val name: Char, var value: Boolean = false)   lateinit var expr: String var variables = mutableListOf<Variable>()   fun Char.isOperator() = this in "&|!^"   fun Char.isVariable() = this in variables.map { it.name }   fun evalExpression(): Boolean { val stack = Stack<Boolean>()   for (e in expr) { stack.push( if (e == 'T') true else if (e == 'F') false else if (e.isVariable()) variables.single { it.name == e }.value else when (e) { '&' -> stack.pop() and stack.pop() '|' -> stack.pop() or stack.pop() '!' -> !stack.pop() '^' -> stack.pop() xor stack.pop() else -> throw RuntimeException("Non-conformant character '$e' in expression") } ) }   require(stack.size == 1) return stack.peek() }   fun setVariables(pos: Int) { require(pos <= variables.size) if (pos == variables.size) { val vs = variables.map { if (it.value) "T" else "F" }.joinToString(" ") val es = if (evalExpression()) "T" else "F" return println("$vs $es") } variables[pos].value = false setVariables(pos + 1) variables[pos].value = true setVariables(pos + 1) }   fun main(args: Array<String>) { println("Accepts single-character variables (except for 'T' and 'F',") println("which specify explicit true or false values), postfix, with") println("&|!^ for and, or, not, xor, respectively; optionally") println("seperated by spaces or tabs. Just enter nothing to quit.")   while (true) { print("\nBoolean expression: ") expr = readLine()!!.toUpperCase().replace(" ", "").replace("\t", "") if (expr == "") return variables.clear() for (e in expr) { if (!e.isOperator() && e !in "TF" && !e.isVariable()) variables.add(Variable(e)) } if (variables.isEmpty()) return val vs = variables.map { it.name }.joinToString(" ") println("\n$vs $expr") val h = vs.length + expr.length + 2 repeat(h) { print("=") } println("\n") setVariables(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
#Lua
Lua
local function ulamspiral(n, f) print("n = " .. n) local function isprime(p) if p < 2 then return false end if p % 2 == 0 then return p==2 end if p % 3 == 0 then return p==3 end local limit = math.sqrt(p) for f = 5, limit, 6 do if p % f == 0 or p % (f+2) == 0 then return false end end return true end local function spiral(x, y) if n%2==1 then x, y = n-1-x, n-1-y end local m = math.min(x, y, n-1-x, n-1-y) return x<y and (n-2*m-2)^2+(x-m)+(y-m) or (n-2*m)^2-(x-m)-(y-m) end for y = 0, n-1 do for x = 0, n-1 do io.write(f(isprime(spiral(x,y)))) end print() end print() end   -- filling a 132 column terminal (with a 2-wide glyph to better preserve aspect ratio) ulamspiral(132/2, function(b) return b and "██" or " " end)
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 739, 73, and 7 formed by removing digits from its right are also prime. No zeroes are allowed in truncatable primes. Task The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied). Related tasks Find largest left truncatable prime in a given base Sieve of Eratosthenes See also Truncatable Prime from MathWorld.]
#Elena
Elena
import extensions;   const MAXN = 1000000;   extension mathOp { isPrime() { int n := cast int(self);   if (n < 2) { ^ false }; if (n < 4) { ^ true }; if (n.mod:2 == 0) { ^ false }; if (n < 9) { ^ true }; if (n.mod:3 == 0) { ^ false };   int r := n.sqrt(); int f := 5; while (f <= r) { if ((n.mod(f) == 0) || (n.mod(f + 2) == 0)) { ^ false };   f := f + 6 };   ^ true }   isRightTruncatable() { int n := self;   while (n != 0) { ifnot (n.isPrime()) { ^ false };   n := n / 10 };   ^ true }   isLeftTruncatable() { int n := self; int tens := 1;   while (tens < n) { tens := tens * 10 };   while (n != 0) { ifnot (n.isPrime()) { ^ false };   tens := tens / 10; n := n - (n / tens * tens) };   ^ true } }   public program() { var n := MAXN; var max_lt := 0; var max_rt := 0;   while (max_lt == 0 || max_rt == 0) { if(n.toString().indexOf("0") == -1) { if ((max_lt == 0) && (n.isLeftTruncatable())) { max_lt := n };   if ((max_rt == 0) && (n.isRightTruncatable())) { max_rt := n } };   n := n - 1 };   console.printLine("Largest truncable left is ",max_lt); console.printLine("Largest truncable right is ",max_rt);   console.readChar() }
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#VBScript
VBScript
  Sub truncate(fpath,n) 'Check if file exist Set objfso = CreateObject("Scripting.FileSystemObject") If objfso.FileExists(fpath) = False Then WScript.Echo fpath & " does not exist" Exit Sub End If content = "" 'stream the input file Set objinstream = CreateObject("Adodb.Stream") With objinstream .Type = 1 .Open .LoadFromFile(fpath) 'check if the specified size is larger than the file content If n <= .Size Then content = .Read(n) Else WScript.Echo "The specified size is larger than the file content" Exit Sub End If .Close End With 'write the truncated version Set objoutstream = CreateObject("Adodb.Stream") With objoutstream .Type = 1 .Open .Write content .SaveToFile fpath,2 .Close End With Set objinstream = Nothing Set objoutstream = Nothing Set objfso = Nothing End Sub   'testing Call truncate("C:\temp\test.txt",30)  
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#Wren
Wren
import "/ioutil" for FileUtil   var fileName = "temp.txt"   // create a file of length 26 bytes FileUtil.write(fileName, "abcdefghijklmnopqrstuvwxyz") System.print("Contents before truncation: %(FileUtil.read(fileName))")   // truncate file to 13 bytes FileUtil.truncate(fileName, 13) System.print("Contents after truncation : %(FileUtil.read(fileName))")   // attempt to truncate file to 20 bytes FileUtil.truncate(fileName, 20) System.print("Contents are still  : %(FileUtil.read(fileName))")
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.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program deftree64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   .equ NBVAL, 9   /*******************************************/ /* Structures */ /********************************************/ /* structure tree */ .struct 0 tree_root: // root pointer .struct tree_root + 8 tree_size: // number of element of tree .struct tree_size + 8 tree_fin: /* structure node tree */ .struct 0 node_left: // left pointer .struct node_left + 8 node_right: // right pointer .struct node_right + 8 node_value: // element value .struct node_value + 8 node_fin: /* structure queue*/ .struct 0 queue_begin: // next pointer .struct queue_begin + 8 queue_end: // element value .struct queue_end + 8 queue_fin: /* structure node queue */ .struct 0 queue_node_next: // next pointer .struct queue_node_next + 8 queue_node_value: // element value .struct queue_node_value + 8 queue_node_fin: /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessInOrder: .asciz "inOrder :\n" szMessPreOrder: .asciz "PreOrder :\n" szMessPostOrder: .asciz "PostOrder :\n" szMessLevelOrder: .asciz "LevelOrder :\n" szCarriageReturn: .asciz "\n" /* datas error display */ szMessErreur: .asciz "Error detected.\n" /* datas message display */ szMessResult: .ascii "Element value : @ \n"   /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss .align 4 sZoneConv: .skip 24 stTree: .skip tree_fin // place to structure tree stQueue: .skip queue_fin // place to structure queue /*******************************************/ /* code section */ /*******************************************/ .text .global main main: mov x1,1 // node tree value 1: ldr x0,qAdrstTree // structure tree address bl insertElement // add element value x1 cmp x0,-1 beq 99f add x1,x1,1 // increment value cmp x1,NBVAL // end ? ble 1b // no -> loop   ldr x0,qAdrszMessPreOrder bl affichageMess ldr x3,qAdrstTree // tree root address (begin structure) ldr x0,[x3,#tree_root] ldr x1,qAdrdisplayElement // function to execute bl preOrder   ldr x0,qAdrszMessInOrder bl affichageMess ldr x3,qAdrstTree ldr x0,[x3,#tree_root] ldr x1,qAdrdisplayElement // function to execute bl inOrder   ldr x0,qAdrszMessPostOrder bl affichageMess ldr x3,qAdrstTree ldr x0,[x3,#tree_root] ldr x1,qAdrdisplayElement // function to execute bl postOrder   ldr x0,qAdrszMessLevelOrder bl affichageMess ldr x3,qAdrstTree ldr x0,[x3,#tree_root] ldr x1,qAdrdisplayElement // function to execute bl levelOrder b 100f 99: // display error ldr x0,qAdrszMessErreur bl affichageMess 100: // standard end of the program mov x8,EXIT // request to exit program svc 0 // perform system call qAdrszMessInOrder: .quad szMessInOrder qAdrszMessPreOrder: .quad szMessPreOrder qAdrszMessPostOrder: .quad szMessPostOrder qAdrszMessLevelOrder: .quad szMessLevelOrder qAdrszMessErreur: .quad szMessErreur qAdrszCarriageReturn: .quad szCarriageReturn qAdrstTree: .quad stTree qAdrstQueue: .quad stQueue qAdrdisplayElement: .quad displayElement /******************************************************************/ /* insert element in the tree */ /******************************************************************/ /* x0 contains the address of the tree structure */ /* x1 contains the value of element */ /* x0 returns address of element or - 1 if error */ insertElement: stp x1,lr,[sp,-16]! // save registers mov x4,x0 mov x0,node_fin // reservation place one element bl allocHeap cmp x0,-1 // allocation error beq 100f mov x5,x0 str x1,[x5,node_value] // store value in address heap mov x1,0 str x1,[x5,node_left] // init left pointer with zero str x1,[x5,node_right] // init right pointer with zero ldr x2,[x4,tree_size] // load tree size cbnz x2,1f // 0 element ? str x5,[x4,tree_root] // yes -> store in root b 6f 1: // else search free address in tree ldr x3,[x4,tree_root] // start with address root add x6,x2,1 // increment tree size clz x7,x6 // compute zeroes left bits add x7,x7,1 // for sustract the first left bit lsl x6,x6,x7 // shift number in left 2: tst x6,1<<63 // test left bit lsl x6,x6,1 // shift left bit bne 3f // bit at one ldr x1,[x3,node_left] // no store node address in left pointer cbz x1,4f // if equal zero mov x3,x1 // else loop with next node b 2b 3: // yes ldr x1,[x3,node_right] // store node address in right pointer cbz x1,5f // if equal zero mov x3,x1 // else loop with next node b 2b 4: str x5,[x3,node_left] b 6f 5: str x5,[x3,node_right] 6: add x2,x2,1 // increment tree size str x2,[x4,tree_size] 100: ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* preOrder */ /******************************************************************/ /* x0 contains the address of the node */ /* x1 function address */ preOrder: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers cmp x0,#0 beq 100f mov x2,x0 blr x1 // call function   ldr x0,[x2,#node_left] bl preOrder ldr x0,[x2,#node_right] bl preOrder 100: ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* inOrder */ /******************************************************************/ /* x0 contains the address of the node */ /* x1 function address */ inOrder: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers cbz x0,100f mov x3,x0 mov x2,x1 ldr x0,[x3,node_left] bl inOrder mov x0,x3 blr x2 // call function   ldr x0,[x3,node_right] mov x1,x2 bl inOrder 100: ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* postOrder */ /******************************************************************/ /* x0 contains the address of the node */ /* x1 function address */ postOrder: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers cbz x0,100f mov x3,x0 mov x2,x1 ldr x0,[x3,#node_left] bl postOrder   ldr x0,[x3,#node_right] mov x1,x2 bl postOrder mov x0,x3 blr x2 // call function 100: ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* levelOrder */ /******************************************************************/ /* x0 contains the address of the node */ /* x1 function address */ levelOrder: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers cbz x0,100f mov x2,x1 mov x1,x0 ldr x0,qAdrstQueue // adresse queue bl enqueueNode // queue the node 1: // begin loop ldr x0,qAdrstQueue bl isEmptyQueue // is queue empty cbz x0,100f // yes -> end ldr x0,qAdrstQueue bl dequeueNode mov x3,x0 // save node blr x2 // call function ldr x14,[x3,#node_left] // left node ok ? cbz x14,2f ldr x0,qAdrstQueue // yes -> enqueue mov x1,x14 bl enqueueNode 2: ldr x14,[x3,#node_right] // right node ok ? cbz x14,3f ldr x0,qAdrstQueue // yes -> enqueue mov x1,x14 bl enqueueNode 3: b 1b // and loop 100: ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* display node */ /******************************************************************/ /* x0 contains node address */ displayElement: stp x1,lr,[sp,-16]! // save registers ldr x0,[x0,#node_value] ldr x1,qAdrsZoneConv bl conversion10S ldr x0,qAdrszMessResult ldr x1,qAdrsZoneConv bl strInsertAtCharInc // insert result at @ character bl affichageMess 100: ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 qAdrszMessResult: .quad szMessResult qAdrsZoneConv: .quad sZoneConv /******************************************************************/ /* enqueue node */ /******************************************************************/ /* x0 contains the address of the queue */ /* x1 contains the value of element */ /* x0 returns address of element or - 1 if error */ enqueueNode: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers mov x14,x0 mov x0,#queue_node_fin // allocation place heap bl allocHeap cmp x0,#-1 // allocation error beq 100f mov x15,x0 // save heap address str x1,[x15,#queue_node_value] // store node value mov x1,#0 str x1,[x15,#queue_node_next] // init pointer next ldr x0,[x14,#queue_end] cbz x0,1f str x15,[x0,#queue_node_next] b 2f 1: str x15,[x14,#queue_begin] 2: str x15,[x14,#queue_end] mov x0,#0 100: ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* dequeue node */ /******************************************************************/ /* x0 contains the address of the queue */ /* x0 returns address of element or - 1 if error */ dequeueNode: stp x1,lr,[sp,-16]! // save registers ldr x14,[x0,#queue_begin] ldr x15,[x14,#queue_node_value] ldr x16,[x14,#queue_node_next] str x16,[x0,#queue_begin] cbnz x16,1f str x16,[x0,#queue_end] 1: mov x0,x15 100: ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* dequeue node */ /******************************************************************/ /* x0 contains the address of the queue */ /* x0 returns 0 if empty else 1 */ isEmptyQueue: ldr x0,[x0,#queue_begin] cmp x0,#0 cset x0,ne ret // return /******************************************************************/ /* memory allocation on the heap */ /******************************************************************/ /* x0 contains the size to allocate */ /* x0 returns address of memory heap or - 1 if error */ /* CAUTION : The size of the allowance must be a multiple of 4 */ allocHeap: stp x8,lr,[sp,-16]! // save registers // allocation mov x16,x0 // save size mov x0,0 // read address start heap mov x8,BRK // call system 'brk' svc 0 mov x15,x0 // save address heap for return add x0,x0,x16 // reservation place for size mov x8,BRK // call system 'brk' svc 0 cmp x0,-1 // allocation error beq 100f mov x0,x15 // return address memory heap 100: ldp x8,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /***********************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
http://rosettacode.org/wiki/Topic_variable
Topic variable
Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language. For instance you can (but you don't have to) show how the topic variable can be used by assigning the number 3 {\displaystyle 3} to it and then computing its square and square root.
#Axe
Axe
3 Disp *3▶Dec,i