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/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would represent a point in the region,   and a vector from the origin to the point. Given the vectors: A = (a1, a2, a3) B = (b1, b2, b3) C = (c1, c2, c3) then the following common vector products are defined: The dot product       (a scalar quantity) A • B = a1b1   +   a2b2   +   a3b3 The cross product       (a vector quantity) A x B = (a2b3  -   a3b2,     a3b1   -   a1b3,     a1b2   -   a2b1) The scalar triple product       (a scalar quantity) A • (B x C) The vector triple product       (a vector quantity) A x (B x C) Task Given the three vectors: a = ( 3, 4, 5) b = ( 4, 3, 5) c = (-5, -12, -13) Create a named function/subroutine/method to compute the dot product of two vectors. Create a function to compute the cross product of two vectors. Optionally create a function to compute the scalar triple product of three vectors. Optionally create a function to compute the vector triple product of three vectors. Compute and display: a • b Compute and display: a x b Compute and display: a • (b x c), the scalar triple product. Compute and display: a x (b x c), the vector triple product. References   A starting page on Wolfram MathWorld is   Vector Multiplication .   Wikipedia   dot product.   Wikipedia   cross product.   Wikipedia   triple product. Related tasks   Dot product   Quaternion type
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   func DotProd(A, B); \Return the dot product of two 3D vectors int A, B; \A ù B return A(0)*B(0) + A(1)*B(1) + A(2)*B(2);   proc CrossProd(A, B, C); \Calculate the cross product of two 3D vectors int A, B, C; \C:= A x B [C(0):= A(1)*B(2) - A(2)*B(1); C(1):= A(2)*B(0) - A(0)*B(2); C(2):= A(0)*B(1) - A(1)*B(0); ]; \CrossProd   func ScalarTriProd(A, B, C); \Return the scalar triple product int A, B, C; \A ù (B x C) int D(3); [CrossProd(B, C, D); return DotProd(A, D); ]; \ScalarTriProd   proc VectTriProd(A, B, C, D); \Calculate the vector triple product int A, B, C, D; \D:= A x (B x C) int E(3); [CrossProd(B, C, E); CrossProd(A, E, D); ]; \CrossProd     int A, B, C, D(3); [A:= [3, 4, 5]; B:= [4, 3, 5]; C:= [-5, -12, -13];   IntOut(0, DotProd(A,B)); CrLf(0);   CrossProd(A, B, D); IntOut(0, D(0)); ChOut(0, 9\tab\); IntOut(0, D(1)); ChOut(0, 9\tab\); IntOut(0, D(2)); CrLf(0);   IntOut(0, ScalarTriProd(A,B,C)); CrLf(0);   VectTriProd(A, B, C, D); IntOut(0, D(0)); ChOut(0, 9\tab\); IntOut(0, D(1)); ChOut(0, 9\tab\); IntOut(0, D(2)); CrLf(0); ]
http://rosettacode.org/wiki/Twin_primes
Twin primes
Twin primes are pairs of natural numbers   (P1  and  P2)   that satisfy the following:     P1   and   P2   are primes     P1  +  2   =   P2 Task Write a program that displays the number of pairs of twin primes that can be found under a user-specified number (P1 < user-specified number & P2 < user-specified number). Extension Find all twin prime pairs under 100000, 10000000 and 1000000000. What is the time complexity of the program? Are there ways to reduce computation time? Examples > Search Size: 100 > 8 twin prime pairs. > Search Size: 1000 > 35 twin prime pairs. Also see   The OEIS entry: A001097: Twin primes.   The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.   The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.   The OEIS entry: A007508: Number of twin prime pairs below 10^n.
#REXX
REXX
/*REXX pgm counts the number of twin prime pairs under a specified number N (or a list).*/ parse arg $ . /*get optional number of primes to find*/ if $='' | $="," then $= 10 100 1000 10000 100000 1000000 10000000 /*No $? Use default.*/ w= length( commas( word($, words($) ) ) ) /*get length of the last number in list*/ @found= ' twin prime pairs found under ' /*literal used in the showing of output*/   do i=1 for words($); x= word($, i) /*process each N─limit in the $ list.*/ say right( commas(genP(x)), 20) @found right(commas(x), max(length(x), w) ) end /*i*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg _; do ?=length(_)-3 to 1 by -3; _=insert(',', _, ?); end; return _ /*──────────────────────────────────────────────────────────────────────────────────────*/ genP: parse arg y; @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; #= 6; tp= 2; sq.6= 169 if y>10 then tp= tp+1 do j=@.#+2 by 2 for max(0, y%2-@.#%2-1) /*find odd primes from here on. */ parse var j '' -1 _ /*obtain the last digit of the J var.*/ if _==5 then iterate; if j// 3==0 then iterate /*J ÷ by 5? J ÷ by 3? */ if j//7==0 then iterate; if j//11==0 then iterate /*" " " 7? " " " 11? */ /* [↓] divide by the primes. ___ */ do k=6 to # while sq.k<=j /*divide J by other primes ≤ √ J */ if j//@.k == 0 then iterate j /*÷ by prev. prime? ¬prime ___ */ end /*k*/ /* [↑] only divide up to √ J */ prev= @.#; #= #+1; sq.#= j*j; @.#= j /*save prev. P; bump # primes; assign P*/ if j-2==prev then tp= tp + 1 /*This & previous prime twins? Bump TP.*/ end /*j*/; return tp
http://rosettacode.org/wiki/Unprimeable_numbers
Unprimeable numbers
Definitions As used here, all unprimeable numbers   (positive integers)   are always expressed in base ten. ───── Definition from OEIS ─────: Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed. ───── Definition from Wiktionary   (referenced from Adam Spencer's book) ─────: (arithmetic)   that cannot be turned into a prime number by changing just one of its digits to any other digit.   (sic) Unprimeable numbers are also spelled:   unprimable. All one─ and two─digit numbers can be turned into primes by changing a single decimal digit. Examples 190   isn't unprimeable,   because by changing the zero digit into a three yields   193,   which is a prime. The number   200   is unprimeable,   since none of the numbers   201, 202, 203, ··· 209   are prime, and all the other numbers obtained by changing a single digit to produce   100, 300, 400, ··· 900,   or   210, 220, 230, ··· 290   which are all even. It is valid to change   189   into   089   by changing the   1   (one)   into a   0   (zero),   which then the leading zero can be removed,   and then treated as if the   "new"   number is   89. Task   show the first   35   unprimeable numbers   (horizontally, on one line, preferably with a title)   show the   600th   unprimeable number   (optional) show the lowest unprimeable number ending in a specific decimal digit   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)   (optional) use commas in the numbers where appropriate Show all output here, on this page. Also see   the     OEIS     entry:   A118118 (unprimeable)   with some useful counts to compare unprimeable number   the Wiktionary entry (reference from below):   (arithmetic definition) unprimeable   from the Adam Spencer book   (page 200):   Adam Spencer's World of Numbers       (Xoum Publishing)
#REXX
REXX
/*REXX program finds and displays unprimeable numbers (non─negative integers). */ parse arg n x hp . /*obtain optional arguments from the CL*/ if n=='' | n=="," then n= 35 /*Not specified? Then use the default.*/ if x=='' | x=="," then x= 600 /* " " " " " " */ if hp=='' | hp=="," then hp= 10000000 /* " " " " " " */ u= 0 /*number of unprimeable numbers so far.*/ eds=4; ed.1= 1; ed.2= 3; ed.3= 7; ed.4= 9 /*"end" digits which are prime; prime>9*/ call genP hp /*generate primes up to & including HP.*/ $$=; $.=. /*a list " " " " " */ do j=100; if !.j then iterate /*Prime? Unprimeable must be composite*/ Lm= length(j) /*obtain the length-1 of the number J. */ meat= left(j, Lm) /*obtain the first Lm digits of J. */ /* [↑] examine the "end" digit of J. */ do e_=1 for eds; new= meat || ed.e_ /*obtain a different number (than J).*/ if new==j then iterate /*Is it the original number? Then skip.*/ if !.new then iterate j /*This new number a prime? " " */ end /*e_*/ /* [↑] examine a new 1st digit of J. */ do f_=0 for 10; new= (f_||meat) + 0 /*obtain a different number (than J).*/ if new==j then iterate /*Is it the original number? Then skip.*/ if !.new then iterate j /*This new number a prime? " " */ end /*f_*/ /* [↑] examine the front digit of J. */ do a_= 2 for Lm-1 /*traipse through the middle digits. */ meat= left(j, a_ - 1) /*use a number of left─most dec. digits*/ rest= substr(j, a_ + 1) /* " " " " right─most " " */ do n_=0 for 10 /*traipse through all 1─digit numbers. */ new= meat || n_ || rest /*construct new number, like a phoenix.*/ if new==j then iterate /*Is it the original number? Then skip.*/ if !.new then iterate j /*This new number a prime? " " */ end /*n_*/ end /*a_*/ u= u + 1 /*bump the count of unprimeable numbers*/ if u<=n then $$= $$ commas(j) /*maybe add unprimeable # to $$ list.*/ if u==x then $.ox= commas(j) /*assign the Xth unprimeable number.*/ parse var j '' -1 _ /*obtain the right─most dec digit of J.*/ if $._==. then $._= j /*the 1st unprimeable # that ends in _.*/ if $.3==. then iterate; if $.7==. then iterate /*test if specific #'s found.*/ if $.1==. then iterate; if $.9==. then iterate /* " " " " " */ leave /*if here, then we're done. */ end /*j*/   if n>0 then do; say center(' first ' n "unprimeable numbers ", 139, '═') say strip($$); say end if x>0 then say ' the ' th(x) " unprimeable number is: " $.ox say do o=0 for 10; if length($.o)==0 then iterate say ' the first unprimeable number that ends in ' o " is:"right(commas($.o),11) end /*o*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg ?; do c=length(?)-3 to 1 by -3; ?=insert(',', ?, c); end; return ? th:procedure;parse arg x;return x||word('th st nd rd',1+(x//10)*(x//100%10\==1)*(x//10<4)) /*──────────────────────────────────────────────────────────────────────────────────────*/ genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; @.7=17; @.8=19; @.9=23; @.10=29; @.11=31  !.=0; !.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1; !.17=1; !.19=1; !.23=1; !.29=1 #= 11; sq.#= @.# **2 do lim=100 until lim*lim>=hp /*only keep primes up to the sqrt(hp). */ end /*lim*/ /* [↑] find limit for storing primes. */ do j=@.#+2 by 2 to hp; parse var j '' -1 _; if _==5 then iterate /*÷ by 5?*/ if j// 3==0 then iterate; if j// 7==0 then iterate; if j//11==0 then iterate if j//13==0 then iterate; if j//17==0 then iterate; if j//19==0 then iterate if j//23==0 then iterate; if j//29==0 then iterate do k=11 while sq.k<=j /*divide by some generated odd primes. */ if j//@.k==0 then iterate j /*Is J divisible by P? Then not prime*/ end /*k*/ /* [↓] a prime (J) has been found. */ #= #+1; if #<=lim then @.#=j;  !.j=1 /*bump prime count; assign prime to @. */ sq.#= j*j /*calculate square of J for fast WHILE.*/
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.]
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   PROC is prime = (INT n)BOOL:( []BOOL is short prime=(FALSE, TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE); IF n<=UPB is short prime THEN is short prime[n] # EXIT # ELSE IF ( NOT ODD n | TRUE | n MOD 3 = 0 ) THEN FALSE # EXIT # ELSE INT h := ENTIER sqrt(n)+3; FOR a FROM 7 BY 6 WHILE a<h DO IF ( n MOD a = 0 | TRUE | n MOD (a-2) = 0 ) THEN false exit FI OD; TRUE # EXIT # FI FI EXIT false exit: FALSE );   PROC string to int = (STRING in a)INT:( FILE f; STRING a := in a; associate(f, a); INT i; get(f, i); close(f); i );   PROC is trunc prime = (INT in n, PROC(REF STRING)VOID trunc)BOOL: ( INT n := in n; STRING s := whole(n, 0); IF char in string("0", NIL, s) THEN FALSE # EXIT # ELSE WHILE is prime(n) DO s := whole(n, 0); trunc(s); IF UPB s = 0 THEN true exit FI; n := string to int(s) OD; FALSE EXIT true exit: TRUE FI );   PROC get trunc prime = (INT in n, PROC(REF STRING)VOID trunc)VOID:( FOR n FROM in n BY -1 TO 1 DO IF is trunc prime(n, trunc) THEN printf(($g(0)l$, n)); break FI OD; break: ~ );   main:( INT limit = 1000000; printf(($g g(0) gl$,"Highest left- and right-truncatable primes under ",limit,":")); get trunc prime(limit, (REF STRING s)VOID: s := s[LWB s+1:]); get trunc prime(limit, (REF STRING s)VOID: s := s[:UPB s-1]); write("Press Enter"); read(newline) )
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.
#Quackery
Quackery
$ "bigrat.qky" loadfile   [ random 0 = ] is randN ( n --> n )   [ dup randN over randN 2dup = iff 2drop again drop nip ] is unbias ( n --> n )   [ dup echo say " biased --> " 0 1000000 times [ over randN if 1+ ] nip 1000000 6 point$ echo$ ] is showbias ( n --> )   [ dup echo say " unbiased --> " 0 1000000 times [ over unbias if 1+ ] nip 1000000 6 point$ echo$ ] is showunbias ( n --> )   ' [ 3 4 5 6 ] witheach [ dup cr showbias cr showunbias cr ]
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.
#R
R
randN = function(N) sample.int(N, 1) == 1   unbiased = function(f) {while ((x <- f()) == f()) {} x}   samples = 10000 print(t(round(d = 2, sapply(3:6, function(N) c( N = N, biased = mean(replicate(samples, randN(N))), unbiased = mean(replicate(samples, unbiased(function() randN(N)))))))))
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.
#Java
Java
import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel;   public class TruncFile { public static void main(String[] args) throws IOException{ if(args.length < 2){ System.out.println("Usage: java TruncFile fileName newSize"); return; } //turn on "append" so it doesn't clear the file FileChannel outChan = new FileOutputStream(args[0], true).getChannel(); long newSize = Long.parseLong(args[1]); outChan.truncate(newSize); outChan.close(); } }
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.
#Julia
Julia
function truncate_file(fname, size): open(fname, "r+") do f truncate(f, size) end end
http://rosettacode.org/wiki/Tree_datastructures
Tree datastructures
The following shows a tree of data with nesting denoted by visual levels of indentation: RosettaCode rocks code comparison wiki mocks trolling A common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of nodes captures the indentation of the tree. Lets call this the nest form. # E.g. if child nodes are surrounded by brackets # and separated by commas then: RosettaCode(rocks(code, ...), ...) # But only an _example_ Another datastructure for trees is to construct from the root an ordered list of the nodes level of indentation and the name of that node. The indentation for the root node is zero; node 'rocks is indented by one level from the left, and so on. Lets call this the indent form. 0 RosettaCode 1 rocks 2 code ... Task Create/use a nest datastructure format and textual representation for arbitrary trees. Create/use an indent datastructure format and textual representation for arbitrary trees. Create methods/classes/proceedures/routines etc to: Change from a nest tree datastructure to an indent one. Change from an indent tree datastructure to a nest one Use the above to encode the example at the start into the nest format, and show it. transform the initial nest format to indent format and show it. transform the indent format to final nest format and show it. Compare initial and final nest formats which should be the same. Note It's all about showing aspects of the contrasting datastructures as they hold the tree. Comparing nested datastructures is secondary - saving formatted output as a string then a string compare would suffice for this task, if its easier. Show all output on this page.
#Haskell
Haskell
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE UndecidableSuperClasses #-} {-# LANGUAGE TypeApplications #-}   import Data.List (span)   -- A nested tree structure. -- Using `Maybe` allows encoding several zero-level items -- or irregular lists (see test example) data Nest a = Nest (Maybe a) [Nest a] deriving Eq   instance Show a => Show (Nest a) where show (Nest (Just a) []) = show a show (Nest (Just a) s) = show a ++ show s show (Nest Nothing []) = "\"\"" show (Nest Nothing s) = "\"\"" ++ show s   -- An indented tree structure. type Indent a = [(Int, a)]   -- class for isomorphic types class Iso b a => Iso a b where from :: a -> b   -- A bijection from nested form to indent form instance Iso (Nest a) (Indent a) where from = go (-1) where go n (Nest a t) = case a of Just a -> (n, a) : foldMap (go (n + 1)) t Nothing -> foldMap (go (n + 1)) t   -- A bijection from indent form to nested form instance Iso (Indent a) (Nest a) where from = revNest . foldl add (Nest Nothing []) where add t (d,x) = go 0 t where go n (Nest a s) = case compare n d of EQ -> Nest a $ Nest (Just x) [] : s LT -> case s of h:t -> Nest a $ go (n+1) h : t [] -> go n $ Nest a [Nest Nothing []] GT -> go (n-1) $ Nest Nothing [Nest a s]   revNest (Nest a s) = Nest a (reverse $ revNest <$> s)   -- A bijection from indent form to a string instance Iso (Indent String) String where from = unlines . map process where process (d, s) = replicate (4*d) ' ' ++ s   -- A bijection from a string to indent form instance Iso String (Indent String) where from = map process . lines where process s = let (i, a) = span (== ' ') s in (length i `div` 4, a)   -- A bijection from nest form to a string via indent form instance Iso (Nest String) String where from = from @(Indent String) . from   -- A bijection from a string to nest form via indent form instance Iso String (Nest String) where from = from @(Indent String) . from
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]
#C.2B.2B
C++
#include <any> #include <iostream> #include <iterator> #include <vector>   using namespace std;   // Make a tree that is a vector of either values or other trees vector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1) { vector<any> tree; while (first < last && depth <= *first) { if(*first == depth) { // add a single value tree.push_back(*first); ++first; } else // (depth < *b) { // add a subtree tree.push_back(MakeTree(first, last, depth + 1)); first = find(first + 1, last, depth); } }   return tree; }   // Print an input vector or tree void PrintTree(input_iterator auto first, input_iterator auto last) { cout << "["; for(auto it = first; it != last; ++it) { if(it != first) cout << ", "; if constexpr (is_integral_v<remove_reference_t<decltype(*first)>>) { // for printing the input vector cout << *it; } else { // for printing the tree if(it->type() == typeid(unsigned int)) { // a single value cout << any_cast<unsigned int>(*it); } else { // a subtree const auto& subTree = any_cast<vector<any>>(*it); PrintTree(subTree.begin(), subTree.end()); } } } cout << "]"; }   int main(void) { auto execises = vector<vector<unsigned int>> { {}, {1, 2, 4}, {3, 1, 3, 1}, {1, 2, 3, 1}, {3, 2, 1, 3}, {3, 3, 3, 1, 1, 3, 3, 3} };   for(const auto& e : execises) { auto tree = MakeTree(e.begin(), e.end()); PrintTree(e.begin(), e.end()); cout << " Nests to:\n"; PrintTree(tree.begin(), tree.end()); cout << "\n\n"; } }  
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.
#C.2B.2B
C++
#include <iostream> #include <vector> #include <string> #include <cmath>   using namespace std;   // convert int (0 or 1) to string (F or T) inline string str(int n) { return n ? "T": "F"; }   int main(void) { int solution_list_number = 1; vector<string> st; st = { " 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." }; // Good solution is: 1 3 4 6 7 11 are true   int n = 12; // Number of statements. int nTemp = (int)pow(2, n); // Number of solutions to check. for (int counter = 0; counter < nTemp; counter++) { vector<int> s; for (int k = 0; k < n; k++) { s.push_back((counter >> k) & 0x1); } vector<int> test(12); int sum = 0; // check each of the nTemp solutions for match. // 1. This is a numbered list of twelve statements. test[0] = s[0];   // 2. Exactly 3 of the last 6 statements are true. sum = s[6]+ s[7]+s[8]+s[9]+s[10]+s[11]; test[1] = ((sum == 3) == s[1]);   // 3. Exactly 2 of the even-numbered statements are true. sum = s[1]+s[3]+s[5]+s[7]+s[9]+s[11]; test[2] = ((sum == 2) == s[2]);   // 4. If statement 5 is true, then statements 6 and 7 are both true. test[3] = ((s[4] ? (s[5] && s[6]) : true) == s[3]);   // 5. The 3 preceding statements are all false. test[4] = (((s[1] + s[2] + s[3]) == 0) == s[4]);   // 6. Exactly 4 of the odd-numbered statements are true. sum = s[0] + s[2] + s[4] + s[6] + s[8] + s[10]; test[5] = ((sum == 4) == s[5]);   // 7. Either statement 2 or 3 is true, but not both. test[6] = (((s[1] + s[2]) == 1) == s[6]);   // 8. If statement 7 is true, then 5 and 6 are both true. test[7] = ((s[6] ? (s[4] && s[5]) : true) == s[7]);   // 9. Exactly 3 of the first 6 statements are true. sum = s[0]+s[1]+s[2]+s[3]+s[4]+s[5]; test[8] = ((sum == 3) == s[8]);   // 10. The next two statements are both true. test[9] = ((s[10] && s[11]) == s[9]);   // 11. Exactly 1 of statements 7, 8 and 9 are true. sum = s[6]+ s[7] + s[8]; test[10] = ((sum == 1) == s[10]);   // 12. Exactly 4 of the preceding statements are true. sum = s[0]+s[1]+s[2]+s[3]+s[4]+s[5]+s[6]+s[7]+s[8]+s[9]+s[10]; test[11] = ((sum == 4) == s[11]);   // Check test results and print solution if 11 or 12 are true int resultsTrue = 0; for(unsigned int i = 0; i < test.size(); i++){ resultsTrue += test[i]; } if(resultsTrue == 11 || resultsTrue == 12){ cout << solution_list_number++ << ". " ; string output = "1:"+str(s[0])+" 2:"+str(s[1])+" 3:"+str(s[2]) +" 4:"+str(s[3])+" 5:"+str(s[4])+" 6:"+ str(s[5]) +" 7:"+str(s[6])+" 8:"+str(s[7])+" 9:"+str(s[8]) +" 10:"+str(s[9])+" 11:"+str(s[10])+" 12:"+ str(s[11]);   if (resultsTrue == 12) { cout << "Full Match, good solution!" << endl; cout << "\t" << output << endl; } else if(resultsTrue == 11){ int i; for(i = 0; i < 12; i++){ if(test[i] == 0){ break; } } cout << "Missed by one statement: " << st[i] << endl; cout << "\t" << output << endl; } } } }  
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.
#Clojure
Clojure
(use '[clojure.math.combinatorics]   (defn xor? [& args] (odd? (count (filter identity args))))   (defn twelve-statements [] (for [[a b c d e f g h i j k l] (selections [true false] 12)  :when (true? a)  :when (if (= 3 (count (filter true? [g h i j k l]))) (true? b) (false? b))  :when (if (= 2 (count (filter true? [b d f h j l]))) (true? c) (false? c))  :when (if (or (false? e) (every? true? [e f g])) (true? d) (false? d))  :when (if (every? false? [b c d]) (true? e) (false? e))  :when (if (= 4 (count (filter true? [a c e g i k]))) (true? f) (false? f))  :when (if (xor? (true? b) (true? c)) (true? g) (false? g))  :when (if (or (false? g) (every? true? [e f g])) (true? h) (false? h))  :when (if (= 3 (count (filter true? [a b c d e f]))) (true? i) (false? i))  :when (if (every? true? [k l]) (true? j) (false? j))  :when (if (= 1 (count (filter true? [g h i]))) (true? k) (false? k))  :when (if (= 4 (count (filter true? [a b c d e f g h i j k]))) (true? l) (false? l))] [a b c d e f g h i j k l]))
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.
#C.23
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text;   public class TruthTable { enum TokenType { Unknown, WhiteSpace, Constant, Operand, Operator, LeftParenthesis, RightParenthesis }   readonly char trueConstant, falseConstant; readonly IDictionary<char, Operator> operators = new Dictionary<char, Operator>();   public TruthTable(char falseConstant, char trueConstant) { this.trueConstant = trueConstant; this.falseConstant = falseConstant; Operators = new OperatorCollection(operators); }   public OperatorCollection Operators { get; }   public void PrintTruthTable(string expression, bool isPostfix = false) { try { foreach (string line in GetTruthTable(expression, isPostfix)) { Console.WriteLine(line); } } catch (ArgumentException ex) { Console.WriteLine(expression + " " + ex.Message); } }   public IEnumerable<string> GetTruthTable(string expression, bool isPostfix = false) { if (string.IsNullOrWhiteSpace(expression)) throw new ArgumentException("Invalid expression."); //Maps parameters to an index in BitSet //Makes sure they appear in the truth table in the order they first appear in the expression var parameters = expression .Where(c => TypeOf(c) == TokenType.Operand) .Distinct() .Reverse() .Select((c, i) => (symbol: c, index: i)) .ToDictionary(p => p.symbol, p => p.index);   int count = parameters.Count; if (count > 32) throw new ArgumentException("Cannot have more than 32 parameters."); string header = count == 0 ? expression : string.Join(" ", parameters.OrderByDescending(p => p.Value).Select(p => p.Key)) + " " + expression;   if (!isPostfix) expression = ConvertToPostfix(expression);   var values = default(BitSet); var stack = new Stack<char>(expression.Length); for (int loop = 1 << count; loop > 0; loop--) { foreach (char token in expression) stack.Push(token); bool result = Evaluate(stack, values, parameters); if (header != null) { if (stack.Count > 0) throw new ArgumentException("Invalid expression."); yield return header; header = null; } string line = (count == 0 ? "" : " ") + (result ? trueConstant : falseConstant); line = string.Join(" ", Enumerable.Range(0, count) .Select(i => values[count - i - 1] ? trueConstant : falseConstant)) + line; yield return line; values++; } }   public string ConvertToPostfix(string infix) { var stack = new Stack<char>(); var postfix = new StringBuilder(); foreach (char c in infix) { switch (TypeOf(c)) { case TokenType.WhiteSpace: continue; case TokenType.Constant: case TokenType.Operand: postfix.Append(c); break; case TokenType.Operator: int precedence = Precedence(c); while (stack.Count > 0 && Precedence(stack.Peek()) > precedence) { postfix.Append(stack.Pop()); } stack.Push(c); break; case TokenType.LeftParenthesis: stack.Push(c); break; case TokenType.RightParenthesis: char top = default(char); while (stack.Count > 0) { top = stack.Pop(); if (top == '(') break; else postfix.Append(top); } if (top != '(') throw new ArgumentException("No matching left parenthesis."); break; default: throw new ArgumentException("Invalid character: " + c); } } while (stack.Count > 0) { char top = stack.Pop(); if (top == '(') throw new ArgumentException("No matching right parenthesis."); postfix.Append(top); } return postfix.ToString(); }   private bool Evaluate(Stack<char> expression, BitSet values, IDictionary<char, int> parameters) { if (expression.Count == 0) throw new ArgumentException("Invalid expression."); char c = expression.Pop(); TokenType type = TypeOf(c); while (type == TokenType.WhiteSpace) type = TypeOf(c = expression.Pop()); switch (type) { case TokenType.Constant: return c == trueConstant; case TokenType.Operand: return values[parameters[c]]; case TokenType.Operator: bool right = Evaluate(expression, values, parameters); Operator op = operators[c]; if (op.Arity == 1) return op.Function(right, right); bool left = Evaluate(expression, values, parameters); return op.Function(left, right); default: throw new ArgumentException("Invalid character: " + c); } }   private TokenType TypeOf(char c) { if (char.IsWhiteSpace(c)) return TokenType.WhiteSpace; if (c == '(') return TokenType.LeftParenthesis; if (c == ')') return TokenType.RightParenthesis; if (c == trueConstant || c == falseConstant) return TokenType.Constant; if (operators.ContainsKey(c)) return TokenType.Operator; if (char.IsLetter(c)) return TokenType.Operand; return TokenType.Unknown; }   private int Precedence(char op) => operators.TryGetValue(op, out var o) ? o.Precedence : int.MinValue; }   struct Operator { public Operator(char symbol, int precedence, Func<bool, bool> function) : this(symbol, precedence, 1, (l, r) => function(r)) { }   public Operator(char symbol, int precedence, Func<bool, bool, bool> function) : this(symbol, precedence, 2, function) { }   private Operator(char symbol, int precedence, int arity, Func<bool, bool, bool> function) : this() { Symbol = symbol; Precedence = precedence; Arity = arity; Function = function; }   public char Symbol { get; } public int Precedence { get; } public int Arity { get; } public Func<bool, bool, bool> Function { get; } }   public class OperatorCollection : IEnumerable { readonly IDictionary<char, Operator> operators;   internal OperatorCollection(IDictionary<char, Operator> operators) { this.operators = operators; }   public void Add(char symbol, int precedence, Func<bool, bool> function) => operators[symbol] = new Operator(symbol, precedence, function); public void Add(char symbol, int precedence, Func<bool, bool, bool> function) => operators[symbol] = new Operator(symbol, precedence, function);   public void Remove(char symbol) => operators.Remove(symbol);   IEnumerator IEnumerable.GetEnumerator() => operators.Values.GetEnumerator(); }   struct BitSet { private int bits;   private BitSet(int bits) { this.bits = bits; }   public static BitSet operator ++(BitSet bitSet) => new BitSet(bitSet.bits + 1);   public bool this[int index] => (bits & (1 << index)) != 0; }   class Program { public static void Main() { TruthTable tt = new TruthTable('F', 'T') { Operators = { { '!', 6, r => !r }, { '&', 5, (l, r) => l && r }, { '^', 4, (l, r) => l ^ r }, { '|', 3, (l, r) => l || r } } }; //Add a crazy operator: var rng = new Random(); tt.Operators.Add('?', 6, r => rng.NextDouble() < 0.5); string[] expressions = { "!!!T", "?T", "F & x | T", "F & (x | T", "F & x | T)", "a ! (a & a)", "a | (a * a)", "a ^ T & (b & !c)", }; foreach (string expression in expressions) { tt.PrintTruthTable(expression); Console.WriteLine(); }   //Define a different language tt = new TruthTable('0', '1') { Operators = { { '-', 6, r => !r }, { '^', 5, (l, r) => l && r }, { 'v', 3, (l, r) => l || r }, { '>', 2, (l, r) => !l || r }, { '=', 1, (l, r) => l == r }, } }; expressions = new[] { "-X v 0 = X ^ 1", "(H > M) ^ (S > H) > (S > M)" }; foreach (string expression in expressions) { tt.PrintTruthTable(expression); Console.WriteLine(); } } }
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
#Factor
Factor
USING: arrays grouping kernel math math.combinatorics math.matrices math.primes math.ranges math.statistics prettyprint sequences sequences.repeating ; IN: rosetta-code.ulam-spiral   : counts ( n -- seq ) 1 [a,b] 2 repeat rest ;   : vals ( n -- seq ) [ -1 swap neg 2dup [ neg ] bi@ 4array ] [ 2 * 1 - cycle ] bi ;   : evJKT2 ( n -- seq ) [ counts ] [ vals ] bi [ <array> ] 2map concat ;   : spiral ( n -- matrix ) [ evJKT2 cum-sum inverse-permutation ] [ group ] bi ;   : ulam-spiral ( n -- matrix ) spiral dup dim first sq 1 - [ swap - 1 + prime? "o " " " ? ] curry matrix-map ;   : ulam-demo ( -- ) 21 ulam-spiral simple-table. ;   MAIN: ulam-demo
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would represent a point in the region,   and a vector from the origin to the point. Given the vectors: A = (a1, a2, a3) B = (b1, b2, b3) C = (c1, c2, c3) then the following common vector products are defined: The dot product       (a scalar quantity) A • B = a1b1   +   a2b2   +   a3b3 The cross product       (a vector quantity) A x B = (a2b3  -   a3b2,     a3b1   -   a1b3,     a1b2   -   a2b1) The scalar triple product       (a scalar quantity) A • (B x C) The vector triple product       (a vector quantity) A x (B x C) Task Given the three vectors: a = ( 3, 4, 5) b = ( 4, 3, 5) c = (-5, -12, -13) Create a named function/subroutine/method to compute the dot product of two vectors. Create a function to compute the cross product of two vectors. Optionally create a function to compute the scalar triple product of three vectors. Optionally create a function to compute the vector triple product of three vectors. Compute and display: a • b Compute and display: a x b Compute and display: a • (b x c), the scalar triple product. Compute and display: a x (b x c), the vector triple product. References   A starting page on Wolfram MathWorld is   Vector Multiplication .   Wikipedia   dot product.   Wikipedia   cross product.   Wikipedia   triple product. Related tasks   Dot product   Quaternion type
#zkl
zkl
fcn dotp(a,b){ a.zipWith('*,b).sum() } //1 slow but concise fcn crossp([(a1,a2,a3)],[(b1,b2,b3)]) //2 { return(a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1) }
http://rosettacode.org/wiki/Twin_primes
Twin primes
Twin primes are pairs of natural numbers   (P1  and  P2)   that satisfy the following:     P1   and   P2   are primes     P1  +  2   =   P2 Task Write a program that displays the number of pairs of twin primes that can be found under a user-specified number (P1 < user-specified number & P2 < user-specified number). Extension Find all twin prime pairs under 100000, 10000000 and 1000000000. What is the time complexity of the program? Are there ways to reduce computation time? Examples > Search Size: 100 > 8 twin prime pairs. > Search Size: 1000 > 35 twin prime pairs. Also see   The OEIS entry: A001097: Twin primes.   The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.   The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.   The OEIS entry: A007508: Number of twin prime pairs below 10^n.
#Ring
Ring
  load "stdlib.ring"   limit = list(7) for n = 1 to 7 limit[n] = pow(10,n) next   TwinPrimes = []   for n = 1 to limit[7]-2 bool1 = isprime(n) bool2 = isprime(n+2) bool = bool1 and bool2 if bool =1 add(TwinPrimes,[n,n+2]) ok next   numTwin = list(7) len = len(TwinPrimes)   for n = 1 to len for p = 1 to 6 if TwinPrimes[n][2] < pow(10,p) and TwinPrimes[n+1][1] > pow(10,p)-2 numTwin[p] = n ok next next   numTwin[7] = len   for n = 1 to 7 see "Maximum: " + pow(10,n) + nl see "twin prime pairs below " + pow(10,n) + ": " + numTwin[n] + nl + nl next  
http://rosettacode.org/wiki/Twin_primes
Twin primes
Twin primes are pairs of natural numbers   (P1  and  P2)   that satisfy the following:     P1   and   P2   are primes     P1  +  2   =   P2 Task Write a program that displays the number of pairs of twin primes that can be found under a user-specified number (P1 < user-specified number & P2 < user-specified number). Extension Find all twin prime pairs under 100000, 10000000 and 1000000000. What is the time complexity of the program? Are there ways to reduce computation time? Examples > Search Size: 100 > 8 twin prime pairs. > Search Size: 1000 > 35 twin prime pairs. Also see   The OEIS entry: A001097: Twin primes.   The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.   The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.   The OEIS entry: A007508: Number of twin prime pairs below 10^n.
#Ruby
Ruby
require 'prime'   (1..8).each do |n| count = Prime.each(10**n).each_cons(2).count{|p1, p2| p2-p1 == 2} puts "Twin primes below 10**#{n}: #{count}" end  
http://rosettacode.org/wiki/Unprimeable_numbers
Unprimeable numbers
Definitions As used here, all unprimeable numbers   (positive integers)   are always expressed in base ten. ───── Definition from OEIS ─────: Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed. ───── Definition from Wiktionary   (referenced from Adam Spencer's book) ─────: (arithmetic)   that cannot be turned into a prime number by changing just one of its digits to any other digit.   (sic) Unprimeable numbers are also spelled:   unprimable. All one─ and two─digit numbers can be turned into primes by changing a single decimal digit. Examples 190   isn't unprimeable,   because by changing the zero digit into a three yields   193,   which is a prime. The number   200   is unprimeable,   since none of the numbers   201, 202, 203, ··· 209   are prime, and all the other numbers obtained by changing a single digit to produce   100, 300, 400, ··· 900,   or   210, 220, 230, ··· 290   which are all even. It is valid to change   189   into   089   by changing the   1   (one)   into a   0   (zero),   which then the leading zero can be removed,   and then treated as if the   "new"   number is   89. Task   show the first   35   unprimeable numbers   (horizontally, on one line, preferably with a title)   show the   600th   unprimeable number   (optional) show the lowest unprimeable number ending in a specific decimal digit   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)   (optional) use commas in the numbers where appropriate Show all output here, on this page. Also see   the     OEIS     entry:   A118118 (unprimeable)   with some useful counts to compare unprimeable number   the Wiktionary entry (reference from below):   (arithmetic definition) unprimeable   from the Adam Spencer book   (page 200):   Adam Spencer's World of Numbers       (Xoum Publishing)
#Rust
Rust
// main.rs mod bit_array; mod prime_sieve;   use prime_sieve::PrimeSieve;   // return number of decimal digits fn count_digits(mut n: u32) -> u32 { let mut digits = 0; while n > 0 { n /= 10; digits += 1; } digits }   // return the number with one digit replaced fn change_digit(mut n: u32, mut index: u32, new_digit: u32) -> u32 { let mut p = 1; let mut changed = 0; while index > 0 { changed += p * (n % 10); p *= 10; n /= 10; index -= 1; } changed += (10 * (n / 10) + new_digit) * p; changed }   fn unprimeable(sieve: &PrimeSieve, n: u32) -> bool { if sieve.is_prime(n as usize) { return false; } let d = count_digits(n); for i in 0..d { for j in 0..10 { let m = change_digit(n, i, j); if m != n && sieve.is_prime(m as usize) { return false; } } } true }   fn main() { let mut count = 0; let mut n = 100; let mut lowest = vec![0; 10]; let mut found = 0; let sieve = PrimeSieve::new(10000000); println!("First 35 unprimeable numbers:"); while count < 600 || found < 10 { if unprimeable(&sieve, n) { if count < 35 { if count > 0 { print!(", "); } print!("{}", n); } count += 1; if count == 600 { println!("\n600th unprimeable number: {}", n); } let last_digit = n as usize % 10; if lowest[last_digit] == 0 { lowest[last_digit] = n; found += 1; } } n += 1; } for i in 0..10 { println!("Least unprimeable number ending in {}: {}", i, lowest[i]); } }
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.]
#Arturo
Arturo
leftTruncatable?: function [n][ every? map 0..(size s)-1 'z -> to :integer slice s z (size s)-1 => prime? ]   rightTruncatable?: function [n][ every? map 0..(size s)-1 'z -> to :integer slice s 0 z => prime? ]   upperLimit: 999999   loop range upperLimit .step:2 0 'x [ s: to :string x if and? not? contains? s "0" leftTruncatable? x [ print ["highest left-truncatable:" x] break ] ]   loop range upperLimit .step:2 0 'x [ s: to :string x if and? not? contains? s "0" rightTruncatable? x [ print ["highest right-truncatable:" x] break ] ]
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.
#Racket
Racket
  #lang racket ;; Using boolean #t/#f instead of 1/0 (define ((randN n)) (zero? (random n))) (define ((unbiased biased)) (let loop () (let ([r (biased)]) (if (eq? r (biased)) (loop) r))))   ;; Counts (define N 1000000) (for ([n (in-range 3 7)]) (define (try% R) (round (/ (for/sum ([i N]) (if (R) 1 0)) N 1/100))) (define biased (randN n)) (printf "Count: ~a => Biased: ~a%; Unbiased: ~a%.\n" n (try% biased) (try% (unbiased biased))))  
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.
#Raku
Raku
sub randN ( $n where 3..6 ) { return ( $n.rand / ($n - 1) ).Int; }   sub unbiased ( $n where 3..6 ) { my $n1; repeat { $n1 = randN($n) } until $n1 != randN($n); return $n1; }   my $iterations = 1000; for 3 .. 6 -> $n { my ( @raw, @fixed ); for ^$iterations { @raw[ randN($n) ]++; @fixed[ unbiased($n) ]++; } printf "N=%d randN: %s, %4.1f%% unbiased: %s, %4.1f%%\n", $n, map { .raku, .[1] * 100 / $iterations }, @raw, @fixed; }
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.
#Kotlin
Kotlin
// version 1.1.2   import java.io.FileOutputStream import java.nio.channels.FileChannel   fun truncateFile(fileName: String, newSize: Long) { var fc: FileChannel? = null try { fc = FileOutputStream(fileName, true).channel if (newSize >= fc.size()) println("Requested file size isn't less than existing size") else fc.truncate(newSize) } catch (ex: Exception) { println(ex.message) } finally { fc!!.close() } }   fun main(args: Array<String>) { truncateFile("test.txt", 10) }
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.
#Lasso
Lasso
define file_truncate(path::string, size::integer) => {   local(file = file(#path))   fail_if(not(#file -> exists), -1, 'There is no file at the given path') fail_if(#file -> size < #size, -1, 'No point in truncating a file to a larger size than it already is')   #file -> setSize(#size)   } local(filepath = '//Library/WebServer/Documents/Lasso9cli/trunk/testing/lorem_ipsum_long.txt')   stdoutnl(file(#filepath) -> readbytes) stdoutnl('Original size: ' + file(#filepath) -> size)   file_truncate(#filepath, 300)   stdoutnl(file(#filepath) -> readbytes) stdout(file('Truncated size: ' + #filepath) -> size)
http://rosettacode.org/wiki/Tree_datastructures
Tree datastructures
The following shows a tree of data with nesting denoted by visual levels of indentation: RosettaCode rocks code comparison wiki mocks trolling A common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of nodes captures the indentation of the tree. Lets call this the nest form. # E.g. if child nodes are surrounded by brackets # and separated by commas then: RosettaCode(rocks(code, ...), ...) # But only an _example_ Another datastructure for trees is to construct from the root an ordered list of the nodes level of indentation and the name of that node. The indentation for the root node is zero; node 'rocks is indented by one level from the left, and so on. Lets call this the indent form. 0 RosettaCode 1 rocks 2 code ... Task Create/use a nest datastructure format and textual representation for arbitrary trees. Create/use an indent datastructure format and textual representation for arbitrary trees. Create methods/classes/proceedures/routines etc to: Change from a nest tree datastructure to an indent one. Change from an indent tree datastructure to a nest one Use the above to encode the example at the start into the nest format, and show it. transform the initial nest format to indent format and show it. transform the indent format to final nest format and show it. Compare initial and final nest formats which should be the same. Note It's all about showing aspects of the contrasting datastructures as they hold the tree. Comparing nested datastructures is secondary - saving formatted output as a string then a string compare would suffice for this task, if its easier. Show all output on this page.
#Julia
Julia
const nesttext = """ RosettaCode rocks code comparison wiki mocks trolling """   function nesttoindent(txt) ret = "" windent = gcd(length.([x.match for x in eachmatch(r"\s+", txt)]) .- 1) for lin in split(txt, "\n") ret *= isempty(lin) ? "\n" : isspace(lin[1]) ? replace(lin, r"\s+" => (s) -> "$(length(s)÷windent) ") * "\n" : "0 " * lin * "\n" end return ret, " "^windent end   function indenttonest(txt, indenttext) ret = "" for lin in filter(x -> length(x) > 1, split(txt, "\n")) (num, name) = split(lin, r"\s+", limit=2) indentnum = parse(Int, num) ret *= indentnum == 0 ? name * "\n" : indenttext^indentnum * name * "\n" end return ret end   indenttext, itext = nesttoindent(nesttext) restorednesttext = indenttonest(indenttext, itext)   println("Original:\n", nesttext, "\n") println("Indent form:\n", indenttext, "\n") println("Back to nest form:\n", restorednesttext, "\n") println("original == restored: ", strip(nesttext) == strip(restorednesttext))  
http://rosettacode.org/wiki/Tree_datastructures
Tree datastructures
The following shows a tree of data with nesting denoted by visual levels of indentation: RosettaCode rocks code comparison wiki mocks trolling A common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of nodes captures the indentation of the tree. Lets call this the nest form. # E.g. if child nodes are surrounded by brackets # and separated by commas then: RosettaCode(rocks(code, ...), ...) # But only an _example_ Another datastructure for trees is to construct from the root an ordered list of the nodes level of indentation and the name of that node. The indentation for the root node is zero; node 'rocks is indented by one level from the left, and so on. Lets call this the indent form. 0 RosettaCode 1 rocks 2 code ... Task Create/use a nest datastructure format and textual representation for arbitrary trees. Create/use an indent datastructure format and textual representation for arbitrary trees. Create methods/classes/proceedures/routines etc to: Change from a nest tree datastructure to an indent one. Change from an indent tree datastructure to a nest one Use the above to encode the example at the start into the nest format, and show it. transform the initial nest format to indent format and show it. transform the indent format to final nest format and show it. Compare initial and final nest formats which should be the same. Note It's all about showing aspects of the contrasting datastructures as they hold the tree. Comparing nested datastructures is secondary - saving formatted output as a string then a string compare would suffice for this task, if its easier. Show all output on this page.
#Nim
Nim
import strformat, strutils     #################################################################################################### # Nested representation of trees. # The tree is simply the first node.   type   NNode*[T] = ref object value*: T children*: seq[NNode[T]]     proc newNNode*[T](value: T; children: varargs[NNode[T]]): NNode[T] = ## Create a node. NNode[T](value: value, children: @children)     proc add*[T](node: NNode[T]; children: varargs[NNode[T]]) = ## Add a list of chlidren to a node. node.children.add children     proc `$`*[T](node: NNode[T]; depth = 0): string = ## Return a string representation of a tree/node. result = repeat(' ', 2 * depth) & $node.value & '\n' for child in node.children: result.add `$`(child, depth + 1)     #################################################################################################### # Indented representation of trees. # The tree is described as the list of the nodes.   type   INode*[T] = object value*: T level*: Natural   ITree*[T] = seq[INode[T]]     proc initINode*[T](value: T; level: Natural): INode[T] = ## Return a new node. INode[T](value: value, level: level)     proc initItree*[T](value: T): ITree[T] = ## Return a new tree initialized with the first node (root node). result = @[initINode(value, 0)]     proc add*[T](tree: var ITree[T]; nodes: varargs[INode[T]]) = ## Add a list of nodes to the tree. for node in nodes: if node.level - tree[^1].level > 1: raise newException(ValueError, &"wrong level {node.level} in node {node.value}.") tree.add node     proc `$`*[T](tree: ITree[T]): string = ## Return a string representation of a tree. for node in tree: result.add $node.level & ' ' & $node.value & '\n'     #################################################################################################### # Conversion between nested form and indented form.   proc toIndented*[T](node: NNode[T]): Itree[T] = ## Convert a tree in nested form to a tree in indented form.   proc addNode[T](tree: var Itree[T]; node: NNode[T]; level: Natural) = ## Add a node to the tree at the given level. tree.add initINode(node.value, level) for child in node.children: tree.addNode(child, level + 1)   result.addNode(node, 0)     proc toNested*[T](tree: Itree[T]): NNode[T] = ## Convert a tree in indented form to a tree in nested form.   var stack: seq[NNode[T]] # Note that stack.len is equal to the current level. var nnode = newNNode(tree[0].value) # Root. for i in 1..tree.high: let inode = tree[i] if inode.level > stack.len: # Child. stack.add nnode elif inode.level == stack.len: # Sibling. stack[^1].children.add nnode else: # Branch terminated. while inode.level < stack.len: stack[^1].children.add nnode nnode = stack.pop() stack[^1].children.add nnode   nnode = newNNode(inode.value)   # Empty the stack. while stack.len > 0: stack[^1].children.add nnode nnode = stack.pop()   result = nnode     #———————————————————————————————————————————————————————————————————————————————————————————————————   when isMainModule:   echo "Displaying tree built using nested structure:" let nestedTree = newNNode("RosettaCode") let rocks = newNNode("rocks") rocks.add newNNode("code"), newNNode("comparison"), newNNode("wiki") let mocks = newNNode("mocks", newNNode("trolling")) nestedTree.add rocks, mocks echo nestedTree   echo "Displaying tree converted to indented structure:" let indentedTree = nestedTree.toIndented echo indentedTree   echo "Displaying tree converted back to nested structure:" echo indentedTree.toNested   echo "Are they equal? ", if $nestedTree == $indentedTree.toNested: "yes" else: "no"
http://rosettacode.org/wiki/Tree_datastructures
Tree datastructures
The following shows a tree of data with nesting denoted by visual levels of indentation: RosettaCode rocks code comparison wiki mocks trolling A common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of nodes captures the indentation of the tree. Lets call this the nest form. # E.g. if child nodes are surrounded by brackets # and separated by commas then: RosettaCode(rocks(code, ...), ...) # But only an _example_ Another datastructure for trees is to construct from the root an ordered list of the nodes level of indentation and the name of that node. The indentation for the root node is zero; node 'rocks is indented by one level from the left, and so on. Lets call this the indent form. 0 RosettaCode 1 rocks 2 code ... Task Create/use a nest datastructure format and textual representation for arbitrary trees. Create/use an indent datastructure format and textual representation for arbitrary trees. Create methods/classes/proceedures/routines etc to: Change from a nest tree datastructure to an indent one. Change from an indent tree datastructure to a nest one Use the above to encode the example at the start into the nest format, and show it. transform the initial nest format to indent format and show it. transform the indent format to final nest format and show it. Compare initial and final nest formats which should be the same. Note It's all about showing aspects of the contrasting datastructures as they hold the tree. Comparing nested datastructures is secondary - saving formatted output as a string then a string compare would suffice for this task, if its easier. Show all output on this page.
#Perl
Perl
use strict; use warnings; use feature 'say'; use JSON; use Data::Printer;   my $trees = <<~END; RosettaCode encourages code diversity comparison discourages golfing trolling emphasising execution speed code-golf.io encourages golfing discourages comparison END   my $level = ' '; sub nested_to_indent { shift =~ s#^($level*)# ($1 ? length($1)/length $level : 0) . ' ' #egmr } sub indent_to_nested { shift =~ s#^(\d+)\s*# $level x $1 #egmr }   say my $indent = nested_to_indent $trees; my $nest = indent_to_nested $indent;   use Test::More; is($trees, $nest, 'Round-trip'); done_testing();   # Import outline paragraph into native data structure sub import { my($trees) = @_; my $level = ' '; my $forest; my $last = -999;   for my $branch (split /\n/, $trees) { $branch =~ m/(($level*))*/; my $this = $1 ? length($1)/length($level) : 0; $forest .= do { if ($this gt $last) { '[' . trim_and_quote($branch) } elsif ($this lt $last) { ']'x($last-$this).',' . trim_and_quote($branch) } else { trim_and_quote($branch) } }; $last = $this; } sub trim_and_quote { shift =~ s/^\s*(.*\S)\s*$/"$1",/r }   eval $forest . ']' x (1+$last); }   my $forest = import $trees; say "Native data structure:\n" . np $forest; say "\nJSON:\n" . encode_json($forest);
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]
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import "fmt"   type any = interface{}   func toTree(list []int) any { s := []any{[]any{}} for _, n := range list { for n != len(s) { if n > len(s) { inner := []any{} s[len(s)-1] = append(s[len(s)-1].([]any), inner) s = append(s, inner) } else { s = s[0 : len(s)-1] } } s[len(s)-1] = append(s[len(s)-1].([]any), n) for i := len(s) - 2; i >= 0; i-- { le := len(s[i].([]any)) s[i].([]any)[le-1] = s[i+1] } } return s[0] }   func main() { tests := [][]int{ {}, {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 := range tests { nest := toTree(test) fmt.Printf("%17s => %v\n", fmt.Sprintf("%v", 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.
#Common_Lisp
Common Lisp
  (defparameter *state* (make-list 12))   (defparameter *statements* '(t ; 1 (= (count-true '(7 8 9 10 11 12)) 3) ; 2 (= (count-true '(2 4 6 8 10 12)) 2) ; 3 (or (not (p 5)) (and (p 6) (p 7))) ; 4 (and (not (p 2)) (not (p 3)) (not (p 4))) ; 5 (= (count-true '(1 3 5 7 9 11)) 4) ; 6 (or (and (p 2) (not (p 3))) (and (not (p 2)) (p 3))) ; 7 (or (not (p 7)) (and (p 5) (p 6))) ; 8 (= (count-true '(1 2 3 4 5 6)) 3) ; 9 (and (p 11) (p 12)) ;10 (= (count-true '(7 8 9)) 1) ;11 (= (count-true '(1 2 3 4 5 6 7 8 9 10 11)) 4))) ;12   (defun start () (loop while (not (equal *state* '(t t t t t t t t t t t t))) do (progn (let ((true-stats (check))) (cond ((= true-stats 11) (result nil)) ((= true-stats 12) (result t)))) (new-state))))   (defun check () (loop for el in *state* for stat in *statements* counting (eq el (eval stat)) into true-stats finally (return true-stats)))   (defun count-true (lst) (loop for i in lst counting (nth (- i 1) *state*) into total finally (return total)))   (defun p (n) (nth (- n 1) *state*))   (defun new-state () (let ((contr t)) (loop for i from 0 to 11 do (progn (setf (nth i *state*) (not (eq (nth i *state*) contr))) (setq contr (and contr (not (nth i *state*))))))))   (defun result (?) (format t "~:[Missed by one~;Solution:~] ~%~{~:[F~;T~] ~}~%" ? *state*))
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.
#Clojure
Clojure
(ns clojure-sandbox.truthtables (:require [clojure.string :as s] [clojure.pprint :as pprint]))   ;; Definitions of the logical operators (defn !op [expr] (not expr))   (defn |op [e1 e2] (not (and (not e1) (not e2))))   (defn &op [e1 e2] (and e1 e2))   (defn ->op [e1 e2] (if e1 e2 true))   (def operators {"!" !op "|" |op "&" &op "->" ->op})   ;; The evaluations of expressions always call the value method on sub-expressions (defn evaluate-unary [operator operand valuemap] (let [operand-value (value operand valuemap) operator (get operators operator)] (operator operand-value)))   (defn evaluate-binary [o1 op o2 valuemap] (let [op1-value (value o1 valuemap) op2-value (value o2 valuemap) operator (get operators op)] (operator op1-value op2-value)))   ;; Protocol to handle all kinds of expressions : unary (!x), binary (x & y), symbolic (x) (defprotocol Expression (value [_ valuemap] "Returns boolean value of expression")) ;; this value map specifies the variables' truth values   (defrecord UnaryExpression [operator operand] Expression (value [self valuemap] (evaluate-unary operator operand valuemap)))   (defrecord BinaryExpression [op1 operator op2] Expression (value [self valuemap] (evaluate-binary op1 operator op2 valuemap)))   (defrecord SymbolExpression [operand] Expression (value [self valuemap] (get valuemap operand)))     ;; Recursively create the right kind of boolean expression, evaluating from the right (defn expression [inputs] (if (contains? operators (first inputs)) (->UnaryExpression (first inputs) (expression (rest inputs))) (if (= 1 (count inputs)) (->SymbolExpression (first inputs)) (->BinaryExpression (->SymbolExpression (first inputs)) (nth inputs 1) (expression (nthrest inputs (- (count inputs) 1)))))))   ;; This won't handle brackets, so it is all evaluated right to left (defn parse [input-str] (-> input-str s/trim ;; remove leading/trailing space (s/split #"\s+"))) ;;remove intermediate spaces   (defn extract-var-names [inputs] "Get a list of variables that can have truth value" (->> inputs (filter (fn[i] (not (contains? operators i)))) set))   (defn all-var-values [inputs] "Returns a list of all potential variable assignments" (let [vars (extract-var-names inputs)] (loop [vars-left vars outputs []] (if (empty? vars-left) outputs (let [this-var (first vars-left)] (if (empty? outputs) (recur (rest vars-left) [{this-var true} {this-var false}]) (recur (rest vars-left) (concat (map (fn[x] (assoc x this-var true)) outputs) (map (fn[x] (assoc x this-var false)) outputs)))))))))   (defn truth-table [input] "Print out the truth table for an input string" (let [input-values (parse input) value-maps (all-var-values input-values) expression (expression input-values)] (value expression (first value-maps)) (->> value-maps (map (fn [x] (assoc x input (value expression x)))) pprint/print-table)))   (truth-table "! a | b") ;; interpreted as ! (a | b)  
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
#Forth
Forth
  43 constant border \ grid size is border x border border border * constant size   variable crawler \ position of the crawler    : set.crawler border 2 mod 0= if \ positions the crawler in the middle of the grid size 2 / border 2/ + 1 - crawler ! else size 2 / crawler ! then ;   set.crawler create Grid size cells allot \ creates the grid here constant GridEnd \ used for debugging    : is.divisor over 2over mod 0= swap drop + ;    : sub.one swap 1 - swap ;    : next.div is.divisor sub.one ;    : three.test \ counts divisors for numbers bigger than 2 dup 0 begin next.div over 1 = until swap drop swap drop 1 + ;    : not.prime \ counts the number of divisors. Primes have exactly two. dup 2 < if drop true else three.test then ;    : sub.four \ the crawler takes a number from the stack as direction dup 4 > if 4 - then ; \ this word makes the number roll over. \ 1-right 2-up 3-left 4-down  : craw.left \ rotates the crawler 90 degrees counter-clockwise 1 + sub.four ;    : scan.right grid crawler @ 1 + cells + @ 0= ; \ checks if cell to the right of the crawler is zero    : scan.left grid crawler @ 1 - cells + @ 0= ; \ cell to the left    : scan.up grid crawler @ border - cells + @ 0= ; \ cell above    : scan.down grid crawler @ border + cells + @ 0= ; \ and cell below    : crawler.go \ moves crawler one cell ahead checks cell to the left... dup \ ...of the direction the crawler is facing, if zero, turns 1 = if crawler @ 1 + crawler ! scan.up if craw.left then else dup 2 = if crawler @ border - crawler ! scan.left if craw.left then else dup 3 = if crawler @ 1 - crawler ! scan.down if craw.left then else dup 4 = if crawler @ border + crawler ! scan.right if craw.left then else   then then then then ;    : run.crawler \ crawler moves through the grid and fills it with numbers border 2 < if 1 grid 0 cells + ! else \ if the grid is a single cell, puts 1 in it crawler @ border - crawler ! \ crawler moves one step and turn before setting the first... 4 \ ...number so it is repositioned one cell up facing down size -1 * 0 do i i -1 * grid crawler @ cells + ! drop crawler.go -1 +loop then drop ;    : leave.primes \ removes non-primes from the grid size 0 do i grid i cells + @ not.prime if 0 grid i cells + ! then drop loop ;    : star.draw1 \ draws a "*" where number is not zero 0> if 42 emit else 32 emit then ;    : star.draw2 0> if 42 emit 32 emit else 32 emit 32 emit \ same but adds a space for better presentation then ;    : star.draw3 0> if 32 emit 42 emit 32 emit else 32 emit 32 emit 32 emit \ adds two spaces then ;    : draw.grid \ cuts the array into lines and displays it page size 0 do i i border mod 0= if cr then grid i cells + @ star.draw2 drop \ may use star.draw1 or 3 here loop ;    : ulam.spiral run.crawler leave.primes draw.grid ; \ draws the spiral. Execute this word to run.  
http://rosettacode.org/wiki/Twin_primes
Twin primes
Twin primes are pairs of natural numbers   (P1  and  P2)   that satisfy the following:     P1   and   P2   are primes     P1  +  2   =   P2 Task Write a program that displays the number of pairs of twin primes that can be found under a user-specified number (P1 < user-specified number & P2 < user-specified number). Extension Find all twin prime pairs under 100000, 10000000 and 1000000000. What is the time complexity of the program? Are there ways to reduce computation time? Examples > Search Size: 100 > 8 twin prime pairs. > Search Size: 1000 > 35 twin prime pairs. Also see   The OEIS entry: A001097: Twin primes.   The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.   The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.   The OEIS entry: A007508: Number of twin prime pairs below 10^n.
#Rust
Rust
// [dependencies] // primal = "0.3" // num-format = "0.4"   use num_format::{Locale, ToFormattedString};   fn twin_prime_count_for_powers_of_ten(max_power: u32) { let mut count = 0; let mut previous = 0; let mut power = 1; let mut limit = 10; for prime in primal::Primes::all() { if prime > limit { println!( "Number of twin prime pairs less than {} is {}", limit.to_formatted_string(&Locale::en), count.to_formatted_string(&Locale::en) ); limit *= 10; power += 1; if power > max_power { break; } } if previous > 0 && prime == previous + 2 { count += 1; } previous = prime; } }   fn twin_prime_count(limit: usize) { let mut count = 0; let mut previous = 0; for prime in primal::Primes::all().take_while(|x| *x < limit) { if previous > 0 && prime == previous + 2 { count += 1; } previous = prime; } println!( "Number of twin prime pairs less than {} is {}", limit.to_formatted_string(&Locale::en), count.to_formatted_string(&Locale::en) ); }   fn main() { let args: Vec<String> = std::env::args().collect(); if args.len() > 1 { for i in 1..args.len() { if let Ok(limit) = args[i].parse::<usize>() { twin_prime_count(limit); } else { eprintln!("Cannot parse limit from string {}", args[i]); } } } else { twin_prime_count_for_powers_of_ten(10); } }
http://rosettacode.org/wiki/Twin_primes
Twin primes
Twin primes are pairs of natural numbers   (P1  and  P2)   that satisfy the following:     P1   and   P2   are primes     P1  +  2   =   P2 Task Write a program that displays the number of pairs of twin primes that can be found under a user-specified number (P1 < user-specified number & P2 < user-specified number). Extension Find all twin prime pairs under 100000, 10000000 and 1000000000. What is the time complexity of the program? Are there ways to reduce computation time? Examples > Search Size: 100 > 8 twin prime pairs. > Search Size: 1000 > 35 twin prime pairs. Also see   The OEIS entry: A001097: Twin primes.   The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.   The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.   The OEIS entry: A007508: Number of twin prime pairs below 10^n.
#Sidef
Sidef
func twin_primes_count(upto) { var count = 0 var p1 = 2 each_prime(3, upto, {|p2| if (p2 - p1 == 2) { ++count } p1 = p2 }) return count }   for n in (1..9) { var count = twin_primes_count(10**n) say "There are #{count} twin primes <= 10^#{n}" }
http://rosettacode.org/wiki/Unprimeable_numbers
Unprimeable numbers
Definitions As used here, all unprimeable numbers   (positive integers)   are always expressed in base ten. ───── Definition from OEIS ─────: Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed. ───── Definition from Wiktionary   (referenced from Adam Spencer's book) ─────: (arithmetic)   that cannot be turned into a prime number by changing just one of its digits to any other digit.   (sic) Unprimeable numbers are also spelled:   unprimable. All one─ and two─digit numbers can be turned into primes by changing a single decimal digit. Examples 190   isn't unprimeable,   because by changing the zero digit into a three yields   193,   which is a prime. The number   200   is unprimeable,   since none of the numbers   201, 202, 203, ··· 209   are prime, and all the other numbers obtained by changing a single digit to produce   100, 300, 400, ··· 900,   or   210, 220, 230, ··· 290   which are all even. It is valid to change   189   into   089   by changing the   1   (one)   into a   0   (zero),   which then the leading zero can be removed,   and then treated as if the   "new"   number is   89. Task   show the first   35   unprimeable numbers   (horizontally, on one line, preferably with a title)   show the   600th   unprimeable number   (optional) show the lowest unprimeable number ending in a specific decimal digit   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)   (optional) use commas in the numbers where appropriate Show all output here, on this page. Also see   the     OEIS     entry:   A118118 (unprimeable)   with some useful counts to compare unprimeable number   the Wiktionary entry (reference from below):   (arithmetic definition) unprimeable   from the Adam Spencer book   (page 200):   Adam Spencer's World of Numbers       (Xoum Publishing)
#Sidef
Sidef
func is_unprimeable(n) { var t = 10*floor(n/10) for k in (t+1 .. t+9 `by` 2) { return false if k.is_prime }   if (n.is_div(2) || n.is_div(5)) { return true if !is_prime(n%10) return true if (n % 10**n.ilog(10) > 9) }   for k in (1 .. n.ilog(10)) { var u = 10**k var v = (n - (u * (floor(n/u) % 10))) 0..9 -> any {|d| is_prime(v + d*u) } && return false }   return true }   with (35) {|n| say ("First #{n} unprimeables:\n", is_unprimeable.first(n).join(' ')) }   with (600) {|n| say ("\n#{n}th unprimeable: ", is_unprimeable.nth(n), "\n") }   for d in (0..9) { say ("First unprimeable that ends with #{d}: ", 1..Inf -> lazy.map {|k| k*10 + d }.grep(is_unprimeable).first) }
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.]
#AutoHotkey
AutoHotkey
SetBatchLines, -1 MsgBox, % "Largest left-truncatable and right-truncatable primes less than one million:`n" . "Left:`t" LTP(10 ** 6) "`nRight:`t" RTP(10 ** 6)   LTP(n) { while n { n-- if (!Instr(n, "0") && IsPrime(n)) { Loop, % StrLen(n) if (!IsPrime(SubStr(n, A_Index))) continue, 2 break } } return, n }   RTP(n) { while n { n-- if (!IsPrime(SubStr(n, 1, 1))) n -= 10 ** (StrLen(n) - 1) if (!Instr(n, "0") && IsPrime(n)) { Loop, % StrLen(n) if (!IsPrime(SubStr(n, 1, A_Index))) continue, 2 break } } return, n }   IsPrime(n) { if (n < 2) return, 0 else if (n < 4) return, 1 else if (!Mod(n, 2)) return, 0 else if (n < 9) return 1 else if (!Mod(n, 3)) return, 0 else { r := Floor(Sqrt(n)) f := 5 while (f <= r) { if (!Mod(n, f)) return, 0 if (!Mod(n, (f + 2))) return, 0 f += 6 } return, 1 } }
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.
#REXX
REXX
/*REXX program generates unbiased random numbers and displays the results to terminal.*/ parse arg # R seed . /*obtain optional arguments from the CL*/ if #=='' | #=="," then #=1000 /*#: the number of SAMPLES to be used.*/ if R=='' | R=="," then R=6 /*R: the high number for the range. */ if datatype(seed, 'W') then call random ,,seed /*Specified? Then use for RANDOM seed.*/ dash='─'; @b="biased"; @ub='un'@b /*literals for the SAY column headers. */ say left('',5) ctr("N",5) ctr(@b) ctr(@b'%') ctr(@ub) ctr(@ub"%") ctr('samples') dash= do N=3 to R; b=0; u=0 do j=1 for #; b=b + randN(N); u=u + unbiased() end /*j*/ say left('', 5) ctr(N, 5) ctr(b) pct(b) ctr(u) pct(u) ctr(#) end /*N*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ ctr: return center( arg(1), word(arg(2) 12, 1), left(dash, 1)) /*show hdr│numbers.*/ pct: return ctr( format(arg(1) / # * 100, , 2)'%' ) /*2 decimal digits.*/ randN: parse arg z; return random(1, z)==z /*ret 1 if rand==Z.*/ unbiased: do until x\==randN(N); x=randN(N); end; return x /* " unbiased RAND*/
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.
#Liberty_BASIC
Liberty BASIC
  dim info$( 50, 50) ' NB pre-dimension before calling file-exists ' needed for file-exists function open "test.dat" for output as #1 'create file for i = 1 to 10000 #1 chr$( int( 256 *rnd( 1))); next close #1   call truncateFile, "test.dat", 5000   wait   sub truncateFile fn$, length if fileExists( DefaultDir$, fn$) =0 then notice "No such file": exit sub open fn$ for input as #i file$ =input$( #i, lof( #i)) if len( file$) <length then notice "Too short": close #i: exit sub file$ =left$( file$, length) close #i open "test.dat" for output as #o #o file$ close #o end sub   function fileExists( path$, filename$) files path$, filename$, info$() fileExists =val( info$( 0, 0)) 'non zero is true end function   end  
http://rosettacode.org/wiki/Tree_datastructures
Tree datastructures
The following shows a tree of data with nesting denoted by visual levels of indentation: RosettaCode rocks code comparison wiki mocks trolling A common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of nodes captures the indentation of the tree. Lets call this the nest form. # E.g. if child nodes are surrounded by brackets # and separated by commas then: RosettaCode(rocks(code, ...), ...) # But only an _example_ Another datastructure for trees is to construct from the root an ordered list of the nodes level of indentation and the name of that node. The indentation for the root node is zero; node 'rocks is indented by one level from the left, and so on. Lets call this the indent form. 0 RosettaCode 1 rocks 2 code ... Task Create/use a nest datastructure format and textual representation for arbitrary trees. Create/use an indent datastructure format and textual representation for arbitrary trees. Create methods/classes/proceedures/routines etc to: Change from a nest tree datastructure to an indent one. Change from an indent tree datastructure to a nest one Use the above to encode the example at the start into the nest format, and show it. transform the initial nest format to indent format and show it. transform the indent format to final nest format and show it. Compare initial and final nest formats which should be the same. Note It's all about showing aspects of the contrasting datastructures as they hold the tree. Comparing nested datastructures is secondary - saving formatted output as a string then a string compare would suffice for this task, if its easier. Show all output on this page.
#Phix
Phix
function text_to_indent(string plain_text) sequence lines = split(plain_text,"\n",no_empty:=true), parents = {} for i=1 to length(lines) do string line = trim_tail(lines[i]), text = trim_head(line) integer indent = length(line)-length(text) -- remove any completed parents while length(parents) and indent<=parents[$] do parents = parents[1..$-1] end while -- append potential new parent parents &= indent integer depth = length(parents) lines[i] = {depth,text} end for return lines end function function indent_to_nested(sequence indent, integer idx=1, level=1) sequence res = {} while idx<=length(indent) do {integer lvl, string text} = indent[idx] if lvl<level then exit end if {sequence children,idx} = indent_to_nested(indent,idx+1,level+1) res = append(res,{text,children}) end while return {res,idx} end function function nested_to_indent(sequence nested, integer level=1) sequence res = {} for i=1 to length(nested) do {string text, sequence children} = nested[i] res = append(res,{level,text}) res &= nested_to_indent(children,level+1) end for return res end function constant text = """ RosettaCode encourages code diversity comparison discourages emphasising execution speed code-golf.io encourages golfing discourages comparison""" sequence indent = text_to_indent(text), nested = indent_to_nested(indent)[1], n2ichk = nested_to_indent(nested) puts(1,"Indent form:\n") pp(indent,{pp_Nest,1}) puts(1,"\nNested form:\n") pp(nested,{pp_Nest,8}) printf(1,"\nNested to indent:%s\n",{iff(n2ichk==indent?"same":"***ERROR***")})
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]
#Go
Go
package main   import "fmt"   type any = interface{}   func toTree(list []int) any { s := []any{[]any{}} for _, n := range list { for n != len(s) { if n > len(s) { inner := []any{} s[len(s)-1] = append(s[len(s)-1].([]any), inner) s = append(s, inner) } else { s = s[0 : len(s)-1] } } s[len(s)-1] = append(s[len(s)-1].([]any), n) for i := len(s) - 2; i >= 0; i-- { le := len(s[i].([]any)) s[i].([]any)[le-1] = s[i+1] } } return s[0] }   func main() { tests := [][]int{ {}, {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 := range tests { nest := toTree(test) fmt.Printf("%17s => %v\n", fmt.Sprintf("%v", 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.
#D
D
import std.stdio, std.algorithm, std.range, std.functional;   immutable texts = [ "this is a numbered list of twelve statements", "exactly 3 of the last 6 statements are true", "exactly 2 of the even-numbered statements are true", "if statement 5 is true, then statements 6 and 7 are both true", "the 3 preceding statements are all false", "exactly 4 of the odd-numbered statements are true", "either statement 2 or 3 is true, but not both", "if statement 7 is true, then 5 and 6 are both true", "exactly 3 of the first 6 statements are true", "the next two statements are both true", "exactly 1 of statements 7, 8 and 9 are true", "exactly 4 of the preceding statements are true"];   immutable pure @safe @nogc bool function(in bool[])[12] predicates = [ s => s.length == 12, s => s[$ - 6 .. $].sum == 3, s => s.dropOne.stride(2).sum == 2, s => s[4] ? (s[5] && s[6]) : true, s => s[1 .. 4].sum == 0, s => s.stride(2).sum == 4, s => s[1 .. 3].sum == 1, s => s[6] ? (s[4] && s[5]) : true, s => s[0 .. 6].sum == 3, s => s[10] && s[11], s => s[6 .. 9].sum == 1, s => s[0 .. 11].sum == 4];   void main() @safe { enum nStats = predicates.length;   foreach (immutable n; 0 .. 2 ^^ nStats) { bool[nStats] st, matches; nStats.iota.map!(i => !!(n & (2 ^^ i))).copy(st[]); st[].zip(predicates[].map!(f => f(st))) .map!(s_t => s_t[0] == s_t[1]).copy(matches[]); if (matches[].sum >= nStats - 1) { if (matches[].all) ">>> Solution:".writeln; else writefln("Missed by statement: %d", matches[].countUntil(false) + 1); writefln("%-(%s %)", st[].map!q{ "FT"[a] }); } } }
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.
#Cowgol
Cowgol
# Truth table generator in Cowgol # - # This program will generate a truth table for the Boolean expression # given on the command line. # # The expression is in infix notation, and operator precedence is impemented, # i.e., the following expression: # A & B | C & D => E # is parsed as: # ((A & B) | (C & D)) => E. # # Syntax: # * Variables are single letters (A-Z). They are case-insensitive. # * 0 and 1 can be used as constant true or false. # * Operators are ~ (not), & (and), | (or), ^ (xor), and => (implies). # * Parentheses may be used to override the normal precedence.   include "cowgol.coh"; include "strings.coh"; include "argv.coh"; ArgvInit();   # Concatenate all command line arguments together, skipping whitespace var code: uint8[512]; var codeptr := &code[0]; loop var argmt := ArgvNext(); if argmt == 0 as [uint8] then break; end if; loop var char := [argmt]; argmt := @next argmt; if char == 0 then break; elseif char == ' ' then continue; end if; [codeptr] := char; codeptr := @next codeptr; end loop; end loop; [codeptr] := 0;   # If no code given, print an error and stop if StrLen(&code[0]) == 0 then print("Error: no boolean expression given\n"); ExitWithError(); end if;   interface TokenReader(str: [uint8]): (next: [uint8], tok: uint8);   # Operators interface OpFn(l: uint8, r: uint8): (v: uint8); sub And implements OpFn is v := l & r; end sub; sub Or implements OpFn is v := l | r; end sub; sub Xor implements OpFn is v := l ^ r; end sub; sub Not implements OpFn is v := ~l; end sub; sub Impl implements OpFn is if l == 0 then v := 1; else v := r; end if; end sub; record Operator is fn: OpFn; name: [uint8]; val: uint8; prec: uint8; end record; var ops: Operator[] := { {Not, "~", 1, 5}, {And, "&", 2, 4}, {Or, "|", 2, 3}, {Xor, "^", 2, 3}, {Impl, "=>", 2, 2} };   const TOKEN_MASK := (1<<5)-1; const TOKEN_OP := 1<<5; sub ReadOp implements TokenReader is tok := 0; next := str; while tok < @sizeof ops loop var find := ops[tok].name; while [find] == [next] loop next := @next next; find := @next find; end loop; if [find] == 0 then tok := tok | TOKEN_OP; return; end if; next := str; tok := tok + 1; end loop; tok := 0; end sub;     # Values (constants, variables) const TOKEN_VAR := 2<<5; const TOKEN_CONST := 3<<5; const CONST_TRUE := 0; const CONST_FALSE := 1; sub ReadValue implements TokenReader is var cur := [str]; next := str; tok := 0; if cur == '0' or cur == '1' then next := @next str; tok := TOKEN_CONST | cur - '0'; elseif (cur >= 'A' and cur <= 'Z') or (cur >= 'a' and cur <= 'z') then next := @next str; tok := TOKEN_VAR | (cur | 32) - 'a'; end if; end sub;   # Parentheses const TOKEN_PAR := 4<<5; const PAR_OPEN := 0; const PAR_CLOSE := 1; sub ReadParen implements TokenReader is case [str] is when '(': next := @next str; tok := TOKEN_PAR | PAR_OPEN; when ')': next := @next str; tok := TOKEN_PAR | PAR_CLOSE; when else: next := str; tok := 0; end case; end sub;   # Read next token sub NextToken(str: [uint8]): (next: [uint8], tok: uint8) is var toks: TokenReader[] := {ReadOp, ReadValue, ReadParen}; var i: uint8 := 0; while i < @sizeof toks loop (next, tok) := (toks[i]) (str); if tok != 0 then return; end if; i := i + 1; end loop; # Invalid token print("cannot tokenize: "); print(str); print_nl(); ExitWithError(); end sub;   # Use shunting yard algorithm to parse the input var expression: uint8[512]; var oprstack: uint8[512]; var expr_ptr := &expression[0]; var ostop := &oprstack[0]; var varmask: uint32 := 0; # mark which variables are in use var one: uint32 := 1; # cannot shift constant by variable   sub GetOp(o: uint8): (r: [Operator]) is r := &ops[o]; end sub;   codeptr := &code[0]; while [codeptr] != 0 loop var tok: uint8; (codeptr, tok) := NextToken(codeptr); var toktype := tok & ~TOKEN_MASK; var tokval := tok & TOKEN_MASK; case toktype is # constants and variables get pushed to output queue when TOKEN_CONST: [expr_ptr] := tok; expr_ptr := @next expr_ptr; when TOKEN_VAR: [expr_ptr] := tok; expr_ptr := @next expr_ptr; varmask := varmask | one << tokval; # operators when TOKEN_OP: if ops[tokval].val == 1 then # unary operator binds immediately [ostop] := tok; ostop := @next ostop; else while ostop > &oprstack[0] and [@prev ostop] != TOKEN_PAR|PAR_OPEN and [GetOp([@prev ostop] & TOKEN_MASK)].prec >= ops[tokval].prec loop ostop := @prev ostop; [expr_ptr] := [ostop]; expr_ptr := @next expr_ptr; end loop; [ostop] := tok; ostop := @next ostop; end if; # parenthesis when TOKEN_PAR: if tokval == PAR_OPEN then # push left parenthesis onto operator stack [ostop] := tok; ostop := @next ostop; else # pop whole operator stack until left parenthesis while ostop > &oprstack[0] and [@prev ostop] != TOKEN_PAR|PAR_OPEN loop ostop := @prev ostop; [expr_ptr] := [ostop]; expr_ptr := @next expr_ptr; end loop; # if we run out of stack, mismatched parenthesis if ostop == &oprstack[0] then print("Error: missing ("); print_nl(); ExitWithError(); else ostop := @prev ostop; end if; end if; end case; end loop;   # push remaining operators onto expression while ostop != &oprstack[0] loop ostop := @prev ostop; [expr_ptr] := [ostop]; if [expr_ptr] & ~TOKEN_MASK == TOKEN_PAR then print("Error: missing )"); print_nl(); ExitWithError(); end if; expr_ptr := @next expr_ptr; end loop;   # terminate expression [expr_ptr] := 0;   # Evaluate expression given set of variables sub Eval(varset: uint32): (r: uint8) is # We can reuse the operator stack as the evaluation stack var ptr := &oprstack[0]; var exp := &expression[0]; var one: uint32 := 1;   while [exp] != 0 loop var toktype := [exp] & ~TOKEN_MASK; var tokval := [exp] & TOKEN_MASK; case toktype is when TOKEN_CONST: [ptr] := tokval; ptr := @next ptr; when TOKEN_VAR: [ptr] := ((varset & (one << tokval)) >> tokval) as uint8; ptr := @next ptr; when TOKEN_OP: var op := GetOp(tokval); ptr := ptr - ([op].val as intptr); if ptr < &oprstack[0] then # not enough values on the stack print("Missing operand\n"); ExitWithError(); end if; [ptr] := ([op].fn)([ptr], [@next ptr]) & 1; ptr := @next ptr; when else: # wrong token left in the expression print("invalid expression token "); print_hex_i8([exp]); print_nl(); ExitWithError(); end case; exp := @next exp; end loop;   # There should be exactly one item on the stack ptr := @prev ptr; if ptr != &oprstack[0] then print("Too many operands\n"); ExitWithError(); else r := [ptr]; end if; end sub;   var v := Eval(0); # evaluate once to catch errors   # Print header and count variables var ch: uint8 := 'A'; var vcount: uint8 := 0; var vars := varmask;   while vars != 0 loop if vars & 1 != 0 then print_char(ch); print_char(' '); vcount := vcount + 1; end if; ch := ch + 1; vars := vars >> 1; end loop; print("| "); print(&code[0]); print_nl();   ch := 2 + vcount * 2 + StrLen(&code[0]) as uint8; while ch != 0 loop print_char('-'); ch := ch - 1; end loop; print_nl();   # Given configuration number, generate variable configuration sub distr(val: uint32): (r: uint32) is var vars := varmask; r := 0; var n: uint8 := 0; while vars != 0 loop r := r >> 1; if vars & 1 != 0 then r := r | ((val & 1) << 31); val := val >> 1; end if; vars := vars >> 1; n := n + 1; end loop; r := r >> (32-n); end sub;   vars := 0; # start with F F F F F var bools: uint8[] := {'F', 'T'}; while vars != one << vcount loop var dist := distr(vars); var rslt := Eval(dist);   # print configuration var vmask := varmask; while vmask != 0 loop if vmask & 1 != 0 then print_char(bools[(dist & 1) as uint8]); print_char(' '); end if; vmask := vmask >> 1; dist := dist >> 1; end loop;   # print result print("| "); print_char(bools[rslt]); print_nl();   # next configuration vars := vars + 1; end loop;
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
#Fortran
Fortran
program ulam implicit none   integer, parameter :: nsize = 49 integer :: i, j, n, x, y integer :: a(nsize*nsize) = (/ (i, i = 1, nsize*nsize) /) character(1) :: spiral(nsize, nsize) = " " character(2) :: sstr character(10) :: fmt   n = 1 x = nsize / 2 + 1 y = x if(isprime(a(n))) spiral(x, y) = "O" n = n + 1   do i = 1, nsize-1, 2 do j = 1, i x = x + 1 if(isprime(a(n))) spiral(x, y) = "O" n = n + 1 end do   do j = 1, i y = y - 1 if(isprime(a(n))) spiral(x, y) = "O" n = n + 1 end do   do j = 1, i+1 x = x - 1 if(isprime(a(n))) spiral(x, y) = "O" n = n + 1 end do   do j = 1, i+1 y = y + 1 if(isprime(a(n))) spiral(x, y) = "O" n = n + 1 end do end do   do j = 1, nsize-1 x = x + 1 if(isprime(a(n))) spiral(x, y) = "O" n = n + 1 end do   write(sstr, "(i0)") nsize fmt = "(" // sstr // "(a,1x))" do i = 1, nsize write(*, fmt) spiral(:, i) end do   contains   function isprime(number) logical :: isprime integer, intent(in) :: number integer :: i   if(number == 2) then isprime = .true. else if(number < 2 .or. mod(number,2) == 0) then isprime = .false. else isprime = .true. do i = 3, int(sqrt(real(number))), 2 if(mod(number,i) == 0) then isprime = .false. exit end if end do end if end function end program
http://rosettacode.org/wiki/Twin_primes
Twin primes
Twin primes are pairs of natural numbers   (P1  and  P2)   that satisfy the following:     P1   and   P2   are primes     P1  +  2   =   P2 Task Write a program that displays the number of pairs of twin primes that can be found under a user-specified number (P1 < user-specified number & P2 < user-specified number). Extension Find all twin prime pairs under 100000, 10000000 and 1000000000. What is the time complexity of the program? Are there ways to reduce computation time? Examples > Search Size: 100 > 8 twin prime pairs. > Search Size: 1000 > 35 twin prime pairs. Also see   The OEIS entry: A001097: Twin primes.   The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.   The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.   The OEIS entry: A007508: Number of twin prime pairs below 10^n.
#Visual_Basic
Visual Basic
Function IsPrime(x As Long) As Boolean Dim i As Long If x Mod 2 = 0 Then Exit Function Else For i = 3 To Int(Sqr(x)) Step 2 If x Mod i = 0 Then Exit Function Next i End If IsPrime = True End Function   Function TwinPrimePairs(max As Long) As Long Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long p2 = True For i = 5 To max Step 2 p1 = p2 p2 = IsPrime(i) If p1 And p2 Then count = count + 1 Next i TwinPrimePairs = count End Function   Sub Test(x As Long) Debug.Print "Twin prime pairs below" + Str(x) + ":" + Str(TwinPrimePairs(x)) End Sub   Sub Main() Test 10 Test 100 Test 1000 Test 10000 Test 100000 Test 1000000 Test 10000000 End Sub
http://rosettacode.org/wiki/Twin_primes
Twin primes
Twin primes are pairs of natural numbers   (P1  and  P2)   that satisfy the following:     P1   and   P2   are primes     P1  +  2   =   P2 Task Write a program that displays the number of pairs of twin primes that can be found under a user-specified number (P1 < user-specified number & P2 < user-specified number). Extension Find all twin prime pairs under 100000, 10000000 and 1000000000. What is the time complexity of the program? Are there ways to reduce computation time? Examples > Search Size: 100 > 8 twin prime pairs. > Search Size: 1000 > 35 twin prime pairs. Also see   The OEIS entry: A001097: Twin primes.   The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.   The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.   The OEIS entry: A007508: Number of twin prime pairs below 10^n.
#Wren
Wren
import "/math" for Int import "/fmt" for Fmt   var c = Int.primeSieve(1e8-1, false) var limit = 10 var start = 3 var twins = 0 for (i in 1..8) { var j = start while (j < limit) { if (!c[j] && !c[j-2]) twins = twins + 1 j = j + 2 } Fmt.print("Under $,11d there are $,7d pairs of twin primes.", limit, twins) start = limit + 1 limit = limit * 10 }
http://rosettacode.org/wiki/Unprimeable_numbers
Unprimeable numbers
Definitions As used here, all unprimeable numbers   (positive integers)   are always expressed in base ten. ───── Definition from OEIS ─────: Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed. ───── Definition from Wiktionary   (referenced from Adam Spencer's book) ─────: (arithmetic)   that cannot be turned into a prime number by changing just one of its digits to any other digit.   (sic) Unprimeable numbers are also spelled:   unprimable. All one─ and two─digit numbers can be turned into primes by changing a single decimal digit. Examples 190   isn't unprimeable,   because by changing the zero digit into a three yields   193,   which is a prime. The number   200   is unprimeable,   since none of the numbers   201, 202, 203, ··· 209   are prime, and all the other numbers obtained by changing a single digit to produce   100, 300, 400, ··· 900,   or   210, 220, 230, ··· 290   which are all even. It is valid to change   189   into   089   by changing the   1   (one)   into a   0   (zero),   which then the leading zero can be removed,   and then treated as if the   "new"   number is   89. Task   show the first   35   unprimeable numbers   (horizontally, on one line, preferably with a title)   show the   600th   unprimeable number   (optional) show the lowest unprimeable number ending in a specific decimal digit   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)   (optional) use commas in the numbers where appropriate Show all output here, on this page. Also see   the     OEIS     entry:   A118118 (unprimeable)   with some useful counts to compare unprimeable number   the Wiktionary entry (reference from below):   (arithmetic definition) unprimeable   from the Adam Spencer book   (page 200):   Adam Spencer's World of Numbers       (Xoum Publishing)
#Swift
Swift
import Foundation   class BitArray { var array: [UInt32]   init(size: Int) { array = Array(repeating: 0, count: (size + 31)/32) }   func get(index: Int) -> Bool { let bit = UInt32(1) << (index & 31) return (array[index >> 5] & bit) != 0 }   func set(index: Int, value: Bool) { let bit = UInt32(1) << (index & 31) if value { array[index >> 5] |= bit } else { array[index >> 5] &= ~bit } } }   class PrimeSieve { let composite: BitArray   init(size: Int) { composite = BitArray(size: size/2) var p = 3 while p * p <= size { if !composite.get(index: p/2 - 1) { let inc = p * 2 var q = p * p while q <= size { composite.set(index: q/2 - 1, value: true) q += inc } } p += 2 } }   func isPrime(number: Int) -> Bool { if number < 2 { return false } if (number & 1) == 0 { return number == 2 } return !composite.get(index: number/2 - 1) } }   // return number of decimal digits func countDigits(number: Int) -> Int { var digits = 0 var n = number while n > 0 { n /= 10 digits += 1 } return digits }   // return the number with one digit replaced func changeDigit(number: Int, index: Int, digit: Int) -> Int { var p = 1 var changed = 0 var n = number var i = index while i > 0 { changed += p * (n % 10) p *= 10 n /= 10 i -= 1 } changed += (10 * (n / 10) + digit) * p return changed }   func unprimeable(sieve: PrimeSieve, number: Int) -> Bool { if sieve.isPrime(number: number) { return false } for i in 0..<countDigits(number: number) { for j in 0..<10 { let n = changeDigit(number: number, index: i, digit: j) if n != number && sieve.isPrime(number: n) { return false } } } return true }   var count = 0 var n = 100 var lowest = Array(repeating: 0, count: 10) var found = 0 let sieve = PrimeSieve(size: 10000000) print("First 35 unprimeable numbers:") while count < 600 || found < 10 { if unprimeable(sieve: sieve, number: n) { if count < 35 { if count > 0 { print(", ", terminator: "") } print(n, terminator: "") } count += 1 if count == 600 { print("\n600th unprimeable number: \(n)") } let lastDigit = n % 10 if lowest[lastDigit] == 0 { lowest[lastDigit] = n found += 1 } } n += 1 } for i in 0..<10 { let number = NSNumber(value: lowest[i]) let str = NumberFormatter.localizedString(from: number, number: .decimal) print("Least unprimeable number ending in \(i): \(str)") }
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.]
#AWK
AWK
  # syntax: GAWK -f TRUNCATABLE_PRIMES.AWK BEGIN { limit = 1000000 for (i=1; i<=limit; i++) { if (is_prime(i)) { prime_count++ arr[i] = "" if (truncate_left(i) == 1) { max_left = max(max_left,i) } if (truncate_right(i) == 1) { max_right = max(max_right,i) } } } printf("1-%d: %d primes\n",limit,prime_count) printf("largest L truncatable: %d\n",max_left) printf("largest R truncatable: %d\n",max_right) exit(0) } function is_prime(x, i) { if (x <= 1) { return(0) } for (i=2; i<=int(sqrt(x)); i++) { if (x % i == 0) { return(0) } } return(1) } function truncate_left(n) { while (n != "") { if (!(n in arr)) { return(0) } n = substr(n,2) } return(1) } function truncate_right(n) { while (n != "") { if (!(n in arr)) { return(0) } n = substr(n,1,length(n)-1) } return(1) } function max(x,y) { return((x > y) ? x : y) }  
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.
#Ring
Ring
  for n = 3 to 6 biased = 0 unb = 0 for i = 1 to 10000 biased += randN(n) unb += unbiased(n) next see "N = " + n + " : biased = " + biased/100 + "%, unbiased = " + unb/100 + "%" + nl next   func unbiased nr while 1 a = randN(nr) if a != randN(nr) return a ok end   func randN m m = (random(m) = 1) return m  
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.
#Ruby
Ruby
def rand_n(bias) rand(bias) == 0 ? 1 : 0 end   def unbiased(bias) a, b = rand_n(bias), rand_n(bias) until a != b #loop until a and b are 0,1 or 1,0 a end   runs = 1_000_000 keys = %i(bias biased unbiased) #use [:bias,:biased,:unbiased] in Ruby < 2.0 puts keys.join("\t")   (3..6).each do |bias| counter = Hash.new(0) # counter will respond with 0 when key is not known runs.times do counter[:biased] += 1 if rand_n(bias) == 1 #the first time, counter has no key for :biased, so it will respond 0 counter[:unbiased] += 1 if unbiased(bias) == 1 end counter[:bias] = bias puts counter.values_at(*keys).join("\t") 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.
#Lingo
Lingo
---------------------------------------- -- Truncates file -- @param {string} filename -- @param {integer} length -- @return {bool} success ---------------------------------------- on truncate (filename, length) fp = xtra("fileIO").new() fp.openFile(filename, 0) if fp.status() then return false if fp.getLength()=length then -- nothing to do fp.closeFile() return true end if data = fp.readByteArray(length) if data.length<>length then fp.closeFile() return false end if fp.delete() fp.createFile(filename) fp.openFile(filename, 2) fp.writeByteArray(data) ok = fp.status()=0 fp.closeFile() return ok 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.
#Lua
Lua
function truncate (filename, length) local inFile = io.open(filename, 'r') if not inFile then error("Specified filename does not exist") end local wholeFile = inFile:read("*all") inFile:close() if length >= wholeFile:len() then error("Provided length is not less than current file length") end local outFile = io.open(filename, 'w') outFile:write(wholeFile:sub(1, length)) outFile:close() 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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Truncate[file_, n_] := Module[{filename = file, nbbytes = n, temp}, temp = $TemporaryPrefix <> filename; BinaryWrite[temp, BinaryReadList[filename, "Byte", nbbytes]]; Close[temp]; DeleteFile[filename]; RenameFile[temp, filename]; ]
http://rosettacode.org/wiki/Tree_datastructures
Tree datastructures
The following shows a tree of data with nesting denoted by visual levels of indentation: RosettaCode rocks code comparison wiki mocks trolling A common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of nodes captures the indentation of the tree. Lets call this the nest form. # E.g. if child nodes are surrounded by brackets # and separated by commas then: RosettaCode(rocks(code, ...), ...) # But only an _example_ Another datastructure for trees is to construct from the root an ordered list of the nodes level of indentation and the name of that node. The indentation for the root node is zero; node 'rocks is indented by one level from the left, and so on. Lets call this the indent form. 0 RosettaCode 1 rocks 2 code ... Task Create/use a nest datastructure format and textual representation for arbitrary trees. Create/use an indent datastructure format and textual representation for arbitrary trees. Create methods/classes/proceedures/routines etc to: Change from a nest tree datastructure to an indent one. Change from an indent tree datastructure to a nest one Use the above to encode the example at the start into the nest format, and show it. transform the initial nest format to indent format and show it. transform the indent format to final nest format and show it. Compare initial and final nest formats which should be the same. Note It's all about showing aspects of the contrasting datastructures as they hold the tree. Comparing nested datastructures is secondary - saving formatted output as a string then a string compare would suffice for this task, if its easier. Show all output on this page.
#Python
Python
from pprint import pprint as pp   def to_indent(node, depth=0, flat=None): if flat is None: flat = [] if node: flat.append((depth, node[0])) for child in node[1]: to_indent(child, depth + 1, flat) return flat   def to_nest(lst, depth=0, level=None): if level is None: level = [] while lst: d, name = lst[0] if d == depth: children = [] level.append((name, children)) lst.pop(0) elif d > depth: # down to_nest(lst, d, children) elif d < depth: # up return return level[0] if level else None   if __name__ == '__main__': print('Start Nest format:') nest = ('RosettaCode', [('rocks', [('code', []), ('comparison', []), ('wiki', [])]), ('mocks', [('trolling', [])])]) pp(nest, width=25)   print('\n... To Indent format:') as_ind = to_indent(nest) pp(as_ind, width=25)   print('\n... To Nest format:') as_nest = to_nest(as_ind) pp(as_nest, width=25)   if nest != as_nest: print("Whoops round-trip issues")
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]
#Guile
Guile
;; helper function that finds the rest that are less than or equal (define (rest-less-eq x ls) (cond ((null? ls) #f) ((<= (car ls) x) ls) (else (rest-less-eq x (cdr ls)))))   ;; nest the input as a tree (define (make-tree input depth) (cond ((null? input) '()) ((eq? input #f ) '()) ((= depth (car input)) (cons (car input)(make-tree(cdr input) depth))) ((< depth (car input)) (cons (make-tree input (+ depth 1)) (make-tree (rest-less-eq depth input) depth))) (#t '()) ))   (define examples '(() (1 2 4) (3 1 3 1) (1 2 3 1) (3 2 1 3) (3 3 3 1 1 3 3 3)))   (define (run-examples x) (if (null? x) '() (begin (display (car x))(display " -> ") (display (make-tree(car x) 1))(display "\n") (run-examples (cdr x)))))   (run-examples examples)  
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.
#Eiffel
Eiffel
  class APPLICATION   create make   feature   make -- Possible solutions. do create s.make_filled (False, 1, 12) s [1] := True recurseAll (2) io.put_string (counter.out + " solution found. ") end   feature {NONE}   s: ARRAY [BOOLEAN]   check2: BOOLEAN -- Is statement 2 fulfilled? local count: INTEGER do across 7 |..| 12 as c loop if s [c.item] then count := count + 1 end end Result := s [2] = (count = 3) end   check3: BOOLEAN -- Is statement 3 fulfilled? local count, i: INTEGER do from i := 2 until i > 12 loop if s [i] then count := count + 1 end i := i + 2 end Result := s [3] = (count = 2) end   check4: BOOLEAN -- Is statement 4 fulfilled? do Result := s [4] = ((not s [5]) or (s [6] and s [7])) end   check5: BOOLEAN -- Is statement 5 fulfilled? do Result := s [5] = ((not s [2]) and (not s [3]) and (not s [4])) end   check6: BOOLEAN -- Is statement 6 fulfilled? local count, i: INTEGER do from i := 1 until i > 11 loop if s [i] then count := count + 1 end i := i + 2 end Result := s [6] = (count = 4) end   check7: BOOLEAN -- Is statement 7 fulfilled? do Result := s [7] = ((s [2] or s [3]) and not (s [2] and s [3])) end   check8: BOOLEAN -- Is statement 8 fulfilled? do Result := s [8] = (not s [7] or (s [5] and s [6])) end   check9: BOOLEAN -- Is statement 9 fulfilled? local count: INTEGER do across 1 |..| 6 as c loop if s [c.item] then count := count + 1 end end Result := s [9] = (count = 3) end   check10: BOOLEAN -- Is statement 10 fulfilled? do Result := s [10] = (s [11] and s [12]) end   check11: BOOLEAN -- Is statement 11 fulfilled? local count: INTEGER do across 7 |..| 9 as c loop if s [c.item] then count := count + 1 end end Result := s [11] = (count = 1) end   check12: BOOLEAN -- Is statement 12 fulfilled? local count: INTEGER do across 1 |..| 11 as c loop if s [c.item] then count := count + 1 end end Result := (s [12] = (count = 4)) end   counter: INTEGER   checkit -- Check if all statements are correctly solved. do if check2 and check3 and check4 and check5 and check6 and check7 and check8 and check9 and check10 and check11 and check12 then across 1 |..| 12 as c loop if s [c.item] then io.put_string (c.item.out + "%T") end end io.new_line counter := counter + 1 end end   recurseAll (k: INTEGER) -- All possible True and False combinations to check for a solution. do if k = 13 then checkit else s [k] := False recurseAll (k + 1) s [k] := True recurseAll (k + 1) end end   end  
http://rosettacode.org/wiki/Truth_table
Truth table
A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function. Task Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function. (One can assume that the user input is correct). Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function. Either reverse-polish or infix notation expressions are allowed. Related tasks   Boolean values   Ternary logic See also   Wolfram MathWorld entry on truth tables.   some "truth table" examples from Google.
#D
D
import std.stdio, std.string, std.array, std.algorithm, std.typecons;   struct Var { const char name; bool val; } const string expr; Var[] vars;   bool pop(ref bool[] arr) pure nothrow { const last = arr.back; arr.popBack; return last; }   enum isOperator = (in char c) pure => "&|!^".canFind(c);   enum varsCountUntil = (in char c) nothrow => .vars.map!(v => v.name).countUntil(c).Nullable!(int, -1);   bool evalExp() { bool[] stack;   foreach (immutable e; .expr) { if (e == 'T') stack ~= true; else if (e == 'F') stack ~= false; else if (!e.varsCountUntil.isNull) stack ~= .vars[e.varsCountUntil.get].val; else switch (e) { case '&': stack ~= stack.pop & stack.pop; break; case '|': stack ~= stack.pop | stack.pop; break; case '!': stack ~= !stack.pop; break; case '^': stack ~= stack.pop ^ stack.pop; break; default: throw new Exception("Non-conformant character '" ~ e ~ "' in expression."); } }   assert(stack.length == 1); return stack.back; }   void setVariables(in size_t pos) in { assert(pos <= .vars.length); } body { if (pos == .vars.length) return writefln("%-(%s %) %s", .vars.map!(v => v.val ? "T" : "F"), evalExp ? "T" : "F");   .vars[pos].val = false; setVariables(pos + 1); .vars[pos].val = true; setVariables(pos + 1); }   static this() { "Accepts 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.".writeln;   "Boolean expression: ".write; .expr = readln.split.join; }   void main() { foreach (immutable e; expr) if (!e.isOperator && !"TF".canFind(e) && e.varsCountUntil.isNull) .vars ~= Var(e); if (.vars.empty) return;   writefln("%-(%s %) %s", .vars.map!(v => v.name), .expr); 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
#FreeBASIC
FreeBASIC
  #define SIZE 639   screenres SIZE, SIZE, 4   function is_prime( n as ulongint ) as boolean if n < 2 then return false if n = 2 then return true if n mod 2 = 0 then return false for i as uinteger = 3 to int(sqr(n))+1 step 2 if n mod i = 0 then return false next i return true end function   function is_turn( byval n as unsigned integer ) as boolean n -= 1 if int(sqr(n))^2 = n then return true n = n - int(sqr(n)) if int(sqr(n))^2 = n then return true return false end function   dim as integer n = 1, x=SIZE/2, y=SIZE/2, dx = 1, dy = 0   do if is_prime(n) then pset (x, y), 15 x = x + dx y = y + dy if x >= SIZE orelse y >= SIZE orelse x < 0 orelse y < 0 then exit do n = n + 1 if is_turn(n) then dx = -dx swap dx, dy end if loop   sleep end
http://rosettacode.org/wiki/Twin_primes
Twin primes
Twin primes are pairs of natural numbers   (P1  and  P2)   that satisfy the following:     P1   and   P2   are primes     P1  +  2   =   P2 Task Write a program that displays the number of pairs of twin primes that can be found under a user-specified number (P1 < user-specified number & P2 < user-specified number). Extension Find all twin prime pairs under 100000, 10000000 and 1000000000. What is the time complexity of the program? Are there ways to reduce computation time? Examples > Search Size: 100 > 8 twin prime pairs. > Search Size: 1000 > 35 twin prime pairs. Also see   The OEIS entry: A001097: Twin primes.   The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.   The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.   The OEIS entry: A007508: Number of twin prime pairs below 10^n.
#XPL0
XPL0
func IsPrime(N); \Return 'true' if N is prime int N, I; [if N <= 2 then return N = 2; if (N&1) = 0 then \even >2\ return false; for I:= 3 to sqrt(N) do [if rem(N/I) = 0 then return false; I:= I+1; ]; return true; ];   func Twins(Limit); int Limit, C, N; [C:= 0; N:= 3; repeat if IsPrime(N) then loop [N:= N+2; if N >= Limit then return C; if not IsPrime(N) then quit; C:= C+1; ]; N:= N+2; until N >= Limit; return C; ];   [IntOut(0, Twins(100_000)); CrLf(0); IntOut(0, Twins(10_000_000)); CrLf(0); IntOut(0, Twins(100_000_000)); CrLf(0); ]
http://rosettacode.org/wiki/Twin_primes
Twin primes
Twin primes are pairs of natural numbers   (P1  and  P2)   that satisfy the following:     P1   and   P2   are primes     P1  +  2   =   P2 Task Write a program that displays the number of pairs of twin primes that can be found under a user-specified number (P1 < user-specified number & P2 < user-specified number). Extension Find all twin prime pairs under 100000, 10000000 and 1000000000. What is the time complexity of the program? Are there ways to reduce computation time? Examples > Search Size: 100 > 8 twin prime pairs. > Search Size: 1000 > 35 twin prime pairs. Also see   The OEIS entry: A001097: Twin primes.   The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.   The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.   The OEIS entry: A007508: Number of twin prime pairs below 10^n.
#Yabasic
Yabasic
  sub isPrime(v) if v < 2 then return False : fi if mod(v, 2) = 0 then return v = 2 : fi if mod(v, 3) = 0 then return v = 3 : fi d = 5 while d * d <= v if mod(v, d) = 0 then return False else d = d + 2 : fi wend return True end sub   sub paresDePrimos(limite) p1 = 0 : p2 = 1 : p3 = 1 : count = 0 for i = 5 to limite p3 = p2 p2 = p1 p1 = isPrime(i) if (p3 and p1) then count = count + 1 : fi next i return count end sub   n = 1 for i = 1 to 6 n = n * 10 print "pares de primos gemelos por debajo de < ", n, " : ", paresDePrimos(n) next i end  
http://rosettacode.org/wiki/Unprimeable_numbers
Unprimeable numbers
Definitions As used here, all unprimeable numbers   (positive integers)   are always expressed in base ten. ───── Definition from OEIS ─────: Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed. ───── Definition from Wiktionary   (referenced from Adam Spencer's book) ─────: (arithmetic)   that cannot be turned into a prime number by changing just one of its digits to any other digit.   (sic) Unprimeable numbers are also spelled:   unprimable. All one─ and two─digit numbers can be turned into primes by changing a single decimal digit. Examples 190   isn't unprimeable,   because by changing the zero digit into a three yields   193,   which is a prime. The number   200   is unprimeable,   since none of the numbers   201, 202, 203, ··· 209   are prime, and all the other numbers obtained by changing a single digit to produce   100, 300, 400, ··· 900,   or   210, 220, 230, ··· 290   which are all even. It is valid to change   189   into   089   by changing the   1   (one)   into a   0   (zero),   which then the leading zero can be removed,   and then treated as if the   "new"   number is   89. Task   show the first   35   unprimeable numbers   (horizontally, on one line, preferably with a title)   show the   600th   unprimeable number   (optional) show the lowest unprimeable number ending in a specific decimal digit   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)   (optional) use commas in the numbers where appropriate Show all output here, on this page. Also see   the     OEIS     entry:   A118118 (unprimeable)   with some useful counts to compare unprimeable number   the Wiktionary entry (reference from below):   (arithmetic definition) unprimeable   from the Adam Spencer book   (page 200):   Adam Spencer's World of Numbers       (Xoum Publishing)
#Wren
Wren
import "/fmt" for Fmt import "/math" for Int   System.print("The first 35 unprimeable numbers are:") var count = 0 // counts all unprimeable numbers var firstNum = List.filled(10, 0) // stores the first unprimeable number ending with each digit var i = 100 var countFirst = 0 while (countFirst < 10) { if (!Int.isPrime(i)) { // unprimeable number must be composite var s = "%(i)" var le = s.count var b = s.bytes.toList var outer = false for (j in 0...le) { for (k in 48..57) { if (s[j].bytes[0] != k) { b[j] = k var bb = b.reduce("") { |acc, byte| acc + String.fromByte(byte) } var n = Num.fromString(bb) if (Int.isPrime(n)) { outer = true break } } } if (outer) break b[j] = s[j].bytes[0] // restore j'th digit to what it was originally } if (!outer) { var lastDigit = s[-1].bytes[0] - 48 if (firstNum[lastDigit] == 0) { firstNum[lastDigit] = i countFirst = countFirst + 1 } count = count + 1 if (count <= 35) System.write("%(i) ") if (count == 35) System.write("\n\nThe 600th unprimeable number is: ") if (count == 600) System.print("%(Fmt.dc(0, i))\n") } } i = i + 1 }   System.print("The first unprimeable number that ends in:") for (i in 0...10) System.print("  %(i) is:  %(Fmt.dc(9, firstNum[i]))")
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.]
#Bracmat
Bracmat
( 1000001:?i & whl ' ( !i+-2:>0:?i & !i:?L & whl'(!L^1/2:#?^1/2&@(!L:% ?L)) & !L:~ ) & out$("left:" !i) & 1000001:?i & whl ' ( !i+-2:>0:?i & !i:?R & whl'(!R^1/2:#?^1/2&@(!R:?R %@)) & !R:~ ) & out$("right:" !i) )
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.
#Rust
Rust
#![feature(inclusive_range_syntax)]   extern crate rand;   use rand::Rng;   fn rand_n<R: Rng>(rng: &mut R, n: u32) -> usize { rng.gen_weighted_bool(n) as usize // maps `false` to 0 and `true` to 1 }   fn unbiased<R: Rng>(rng: &mut R, n: u32) -> usize { let mut bit = rand_n(rng, n); while bit == rand_n(rng, n) { bit = rand_n(rng, n); } bit }   fn main() { const SAMPLES: usize = 100_000; let mut rng = rand::weak_rng();   println!(" Bias rand_n unbiased"); for n in 3..=6 { let mut count_biased = 0; let mut count_unbiased = 0; for _ in 0..SAMPLES { count_biased += rand_n(&mut rng, n); count_unbiased += unbiased(&mut rng, n); }   let b_percentage = 100.0 * count_biased as f64 / SAMPLES as f64; let ub_percentage = 100.0 * count_unbiased as f64 / SAMPLES as f64; println!( "bias {}: {:0.2}% {:0.2}%", n, b_percentage, ub_percentage ); } }
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.
#Scala
Scala
def biased( n:Int ) = scala.util.Random.nextFloat < 1.0 / n   def unbiased( n:Int ) = { def loop : Boolean = { val a = biased(n); if( a != biased(n) ) a else loop }; loop }   for( i <- (3 until 7) ) println {   val m = 50000 var c1,c2 = 0   (0 until m) foreach { j => if( biased(i) ) c1 += 1; if( unbiased(i) ) c2 += 1 }   "%d: %2.2f%%  %2.2f%%".format(i, 100.0*c1/m, 100.0*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.
#MATLAB_.2F_Octave
MATLAB / Octave
function truncate_a_file(fn,count);   fid=fopen(fn,'r'); s = fread(fid,count,'uint8'); fclose(fid);   fid=fopen(fn,'w'); s = fwrite(fid,s,'uint8'); fclose(fid);
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.
#Nim
Nim
import posix   discard truncate("filename", 1024)
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.
#OCaml
OCaml
val truncate : string -> int -> unit (** Truncates the named file to the given size. *)
http://rosettacode.org/wiki/Tree_datastructures
Tree datastructures
The following shows a tree of data with nesting denoted by visual levels of indentation: RosettaCode rocks code comparison wiki mocks trolling A common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of nodes captures the indentation of the tree. Lets call this the nest form. # E.g. if child nodes are surrounded by brackets # and separated by commas then: RosettaCode(rocks(code, ...), ...) # But only an _example_ Another datastructure for trees is to construct from the root an ordered list of the nodes level of indentation and the name of that node. The indentation for the root node is zero; node 'rocks is indented by one level from the left, and so on. Lets call this the indent form. 0 RosettaCode 1 rocks 2 code ... Task Create/use a nest datastructure format and textual representation for arbitrary trees. Create/use an indent datastructure format and textual representation for arbitrary trees. Create methods/classes/proceedures/routines etc to: Change from a nest tree datastructure to an indent one. Change from an indent tree datastructure to a nest one Use the above to encode the example at the start into the nest format, and show it. transform the initial nest format to indent format and show it. transform the indent format to final nest format and show it. Compare initial and final nest formats which should be the same. Note It's all about showing aspects of the contrasting datastructures as they hold the tree. Comparing nested datastructures is secondary - saving formatted output as a string then a string compare would suffice for this task, if its easier. Show all output on this page.
#Raku
Raku
#`( Sort of vague as to what we are trying to accomplish here. If we are just trying to transform from one format to another, probably easiest to just perform string manipulations. )   my $level = ' ';   my $trees = q:to/END/; RosettaCode encourages code diversity comparison discourages golfing trolling emphasising execution speed code-golf.io encourages golfing discourages comparison END   sub nested-to-indent { $^str.subst: / ^^ ($($level))* /, -> $/ { "{+$0} " }, :g } sub indent-to-nested { $^str.subst: / ^^ (\d+) \s* /, -> $/ { "{$level x +$0}" }, :g }   say $trees; say my $indent = $trees.&nested-to-indent; say my $nest = $indent.&indent-to-nested;   use Test; is($trees, $nest, 'Round-trip equals original');   #`( If, on the other hand, we want perform more complex transformations; better to load it into a native data structure which will then allow us to manipulate it however we like. )   # Import outline paragraph into native data structure sub import (Str $trees, $level = ' ') { my $forest; my $last = -Inf;   for $trees.lines -> $branch { $branch ~~ / ($($level))* /; my $this = +$0; $forest ~= do { given $this cmp $last { when More { "\['{esc $branch.trim}', " } when Same { "'{esc $branch.trim}', " } when Less { "{']' x $last - $this}, '{esc $branch.trim}', " } } } $last = $this; }   sub esc { $^s.subst( /(<['\\]>)/, -> $/ { "\\$0" }, :g) }   $forest ~= ']' x 1 + $last; $forest.EVAL; }   my $forest = import $trees;   say "\nNative data structure:\n", $forest.raku;   { use JSON::Fast; say "\nJSON:\n", $forest.&to-json; }   { use YAML; say "\nYAML:\n", $forest.&dump; }
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.
#11l
11l
F run_utm(halt, state, Char blank; rules_in, [Char] &tape = [Char](); =pos = 0) V st = state I tape.empty tape.append(blank) I pos < 0 pos += tape.len V rules = Dict(rules_in, r -> ((r[0], Char(r[1])), (Char(r[2]), r[3], r[4])))   L print(st.ljust(4), end' ‘ ’) L(v) tape V i = L.index I i == pos print(‘[’v‘]’, end' ‘ ’) E print(v, end' ‘ ’) print()   I st == halt L.break I (st, tape[pos]) !C rules L.break   V (v1, dr, s1) = rules[(st, tape[pos])] tape[pos] = v1 I dr == ‘left’ I pos > 0 pos-- E tape.insert(0, blank) I dr == ‘right’ pos++ I pos >= tape.len tape.append(blank) st = s1   print("incr machine\n") run_utm( halt' ‘qf’, state' ‘q0’, blank' Char(‘B’), rules_in' [‘q0 1 1 right q0’.split(‘ ’, group_delimiters' 1B), ‘q0 B 1 stay qf’.split(‘ ’, group_delimiters' 1B)], tape' &[‘1’, ‘1’, ‘1’] )   print("\nbusy beaver\n") run_utm( halt' ‘halt’, state' ‘a’, blank' Char(‘0’), rules_in' [‘a 0 1 right b’.split(‘ ’, group_delimiters' 1B), ‘a 1 1 left c’.split(‘ ’, group_delimiters' 1B), ‘b 0 1 left a’.split(‘ ’, group_delimiters' 1B), ‘b 1 1 right b’.split(‘ ’, group_delimiters' 1B), ‘c 0 1 left b’.split(‘ ’, group_delimiters' 1B), ‘c 1 1 stay halt’.split(‘ ’, group_delimiters' 1B)] )   print("\nsorting test\n") run_utm( halt' ‘STOP’, state' ‘A’, blank' Char(‘0’), rules_in' [‘A 1 1 right A’.split(‘ ’, group_delimiters' 1B), ‘A 2 3 right B’.split(‘ ’, group_delimiters' 1B), ‘A 0 0 left E’.split(‘ ’, group_delimiters' 1B), ‘B 1 1 right B’.split(‘ ’, group_delimiters' 1B), ‘B 2 2 right B’.split(‘ ’, group_delimiters' 1B), ‘B 0 0 left C’.split(‘ ’, group_delimiters' 1B), ‘C 1 2 left D’.split(‘ ’, group_delimiters' 1B), ‘C 2 2 left C’.split(‘ ’, group_delimiters' 1B), ‘C 3 2 left E’.split(‘ ’, group_delimiters' 1B), ‘D 1 1 left D’.split(‘ ’, group_delimiters' 1B), ‘D 2 2 left D’.split(‘ ’, group_delimiters' 1B), ‘D 3 1 right A’.split(‘ ’, group_delimiters' 1B), ‘E 1 1 left E’.split(‘ ’, group_delimiters' 1B), ‘E 0 0 right STOP’.split(‘ ’, group_delimiters' 1B)], tape' &‘2 2 2 1 2 2 1 2 1 2 1 2 1 2’.split(‘ ’).map(Char) )
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]
#Haskell
Haskell
{-# LANGUAGE TupleSections #-}   import Data.Bifunctor (bimap) import Data.Tree (Forest, Tree (..), drawTree, foldTree)   ------------- TREE FROM NEST LEVELS (AND BACK) -----------   treeFromSparseLevels :: [Int] -> Tree (Maybe Int) treeFromSparseLevels = Node Nothing . forestFromNestLevels . rooted . normalised   sparseLevelsFromTree :: Tree (Maybe Int) -> [Int] sparseLevelsFromTree = foldTree go where go Nothing xs = concat xs go (Just x) xs = x : concat xs   forestFromNestLevels :: [(Int, a)] -> Forest a forestFromNestLevels = go where go [] = [] go ((n, v) : xs) = uncurry (:) $ bimap (Node v . go) go (span ((n <) . fst) xs)   --------------------- TEST AND DISPLAY ------------------- main :: IO () main = mapM_ ( \xs -> putStrLn ("From: " <> show xs) >> let tree = treeFromSparseLevels xs in putStrLn ((drawTree . fmap show) tree) >> putStrLn ( "Back to: " <> show (sparseLevelsFromTree tree) <> "\n\n" ) ) [ [], [1, 2, 4], [3, 1, 3, 1], [1, 2, 3, 1], [3, 2, 1, 3], [3, 3, 3, 1, 1, 3, 3, 3] ]   ----------- MAPPING TO A STRICTER DATA STRUCTURE ---------   -- Path from the virtual root to the first explicit node. rooted :: [(Int, Maybe Int)] -> [(Int, Maybe Int)] rooted [] = [] rooted xs = go $ filter ((1 <=) . fst) xs where go xs@((1, mb) : _) = xs go xs@((n, mb) : _) = fmap (,Nothing) [1 .. pred n] <> xs   -- Representation of implicit nodes. normalised [] = [] normalised [x] = [(x, Just x)] normalised (x : y : xs) | 1 < (y - x) = (x, Just x) : (succ x, Nothing) : normalised (y : xs) | otherwise = (x, Just x) : normalised (y : xs)
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.
#Elena
Elena
import system'routines; import extensions; import extensions'text;   extension op { printSolution(bits) = self.zipBy(bits, (s,b => s.iif("T","F") + (s.xor:b).iif("* "," "))).summarize(new StringWriter());   toBit() = self.iif(1,0); }   puzzle = new Func1[] { (bits => bits.Length == 12),   (bits => bits.last(6).selectBy:(x => x.toBit()).summarize() == 3 ),   (bits => bits.zipBy(new Range(1, 12), (x,i => (i.toInt().isEven()).and:x.toBit())).summarize() == 2 ),   (bits => bits[4].iif(bits[5] && bits[6],true) ),   (bits => ((bits[1] || bits[2]) || bits[3]).Inverted ),   (bits => bits.zipBy(new Range(1, 12), (x,i => (i.toInt().isOdd()).and:x.toBit() )).summarize() == 4 ),   (bits => bits[1].xor(bits[2]) ),   (bits => bits[6].iif(bits[5] && bits[4],true) ),   (bits => bits.top(6).selectBy:(x => x.toBit() ).summarize() == 3 ),   (bits => bits[10] && bits[11] ),   (bits => (bits[6].toBit() + bits[7].toBit() + bits[8].toBit())==1 ),   (bits => bits.top(11).selectBy:(x => x.toBit()).summarize() == 4 ) };   public program() { console.writeLine();   for(int n := 0, n < 2.power(12), n += 1) { var bits := BitArray32.load(n).top(12).toArray(); var results := puzzle.selectBy:(r => r(bits)).toArray();   var counts := bits.zipBy(results, (b,r => b.xor:r.toBit() )).summarize();   counts => 0 { console.printLine("Total hit :",results.printSolution:bits) } 1 { console.printLine("Near miss :",results.printSolution:bits) } 12 { console.printLine("Total miss:",results.printSolution:bits) }; };   console.readChar() }
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.
#ERRE
ERRE
  PROGRAM TWELVE_STMS   !$DYNAMIC DIM PASS%[0],T%[0]   FUNCTION EOR(X,Y) EOR=(X AND NOT(Y)) OR (NOT(X) AND Y) END FUNCTION   BEGIN NSTATEMENTS%=12  !$DIM PASS%[NSTATEMENTS%],T%[NSTATEMENTS%]   FOR TRY%=0 TO 2^NSTATEMENTS%-1 DO    ! Postulate answer: FOR STMT%=1 TO 12 DO T%[STMT%]=(TRY% AND 2^(STMT%-1))<>0 END FOR    ! Test consistency: PASS%[1]=T%[1]=(NSTATEMENTS%=12) PASS%[2]=T%[2]=((T%[7]+T%[8]+T%[9]+T%[10]+T%[11]+T%[12])=-3) PASS%[3]=T%[3]=((T%[2]+T%[4]+T%[6]+T%[8]+T%[10]+T%[12])=-2) PASS%[4]=T%[4]=((NOT T%[5] OR (T%[6] AND T%[7]))) PASS%[5]=T%[5]=(NOT T%[2] AND NOT T%[3] AND NOT T%[4]) PASS%[6]=T%[6]=((T%[1]+T%[3]+T%[5]+T%[7]+T%[9]+T%[11])=-4) PASS%[7]=T%[7]=(EOR(T%[2],T%[3])) PASS%[8]=T%[8]=((NOT T%[7] OR (T%[5] AND T%[6]))) PASS%[9]=T%[9]=((T%[1]+T%[2]+T%[3]+T%[4]+T%[5]+T%[6])=-3) PASS%[10]=T%[10]=(T%[11] AND T%[12]) PASS%[11]=T%[11]=((T%[7]+T%[8]+T%[9])=-1) PASS%[12]=T%[12]=((T%[1]+T%[2]+T%[3]+T%[4]+T%[5]+T%[6]+T%[7]+T%[8]+T%[9]+T%[10]+T%[11])=-4)   SUM=0 FOR I%=1 TO 12 DO SUM=SUM+PASS%[I%] END FOR   CASE SUM OF -11-> PRINT("Near miss with statements ";) FOR STMT%=1 TO 12 DO IF T%[STMT%] THEN PRINT(STMT%;) END IF IF NOT PASS%[STMT%] THEN MISS%=STMT% END IF END FOR PRINT("true (failed ";MISS%;").") END -> -12-> PRINT("Solution! with statements ";) FOR STMT%=1 TO 12 DO IF T%[STMT%] THEN PRINT(STMT%;) END IF END FOR PRINT("true.") END -> END CASE   END FOR ! TRY% END PROGRAM
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.
#D.C3.A9j.C3.A0_Vu
Déjà Vu
print-line lst end: for v in reversed copy lst: print\( v chr 9 ) print end   (print-truth-table) t n func: if n: (print-truth-table) push-through copy t 0 -- n @func (print-truth-table) push-through copy t 1 -- n @func else: print-line t func for in copy t   print-truth-table vars name func: print-line vars name (print-truth-table) [] len vars @func print "" # extra new line   stu s t u: or s /= t u   abcd a b c d: /= a /= b /= c d   print-truth-table [ "A" "B" ] "A ^ B" @/= print-truth-table [ "S" "T" "U" ] "S | (T ^ U)" @stu print-truth-table [ "A" "B" "C" "D" ] "A ^ (B ^ (C ^ D))" @abcd
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
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "math" "fmt" )   type Direction byte   const ( RIGHT Direction = iota UP LEFT DOWN )   func generate(n,i int, c byte) { s := make([][]string, n) for i := 0; i < n; i++ { s[i] = make([]string, n) } dir := RIGHT y := n / 2 var x int if (n % 2 == 0) { x = y - 1 } else { x = y } // shift left for even n's   for j := i; j <= n * n - 1 + i; j++ { if (isPrime(j)) { if (c == 0) { s[y][x] = fmt.Sprintf("%3d", j) } else { s[y][x] = fmt.Sprintf("%2c ", c) } } else { s[y][x] = "---" }   switch dir { case RIGHT : if (x <= n - 1 && s[y - 1][x] == "" && j > i) { dir = UP } case UP : if (s[y][x - 1] == "") { dir = LEFT } case LEFT : if (x == 0 || s[y + 1][x] == "") { dir = DOWN } case DOWN : if (s[y][x + 1] == "") { dir = RIGHT } }   switch dir { case RIGHT : x += 1 case UP : y -= 1 case LEFT : x -= 1 case DOWN : y += 1 } }   for _, row := range s { fmt.Println(fmt.Sprintf("%v", row)) } fmt.Println() }   func isPrime(a int) bool { if (a == 2) { return true } if (a <= 1 || a % 2 == 0) { return false } max := int(math.Sqrt(float64(a))) for n := 3; n <= max; n += 2 { if (a % n == 0) { return false } } return true }   func main() { generate(9, 1, 0) // with digits generate(9, 1, '*') // with * }
http://rosettacode.org/wiki/Unprimeable_numbers
Unprimeable numbers
Definitions As used here, all unprimeable numbers   (positive integers)   are always expressed in base ten. ───── Definition from OEIS ─────: Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed. ───── Definition from Wiktionary   (referenced from Adam Spencer's book) ─────: (arithmetic)   that cannot be turned into a prime number by changing just one of its digits to any other digit.   (sic) Unprimeable numbers are also spelled:   unprimable. All one─ and two─digit numbers can be turned into primes by changing a single decimal digit. Examples 190   isn't unprimeable,   because by changing the zero digit into a three yields   193,   which is a prime. The number   200   is unprimeable,   since none of the numbers   201, 202, 203, ··· 209   are prime, and all the other numbers obtained by changing a single digit to produce   100, 300, 400, ··· 900,   or   210, 220, 230, ··· 290   which are all even. It is valid to change   189   into   089   by changing the   1   (one)   into a   0   (zero),   which then the leading zero can be removed,   and then treated as if the   "new"   number is   89. Task   show the first   35   unprimeable numbers   (horizontally, on one line, preferably with a title)   show the   600th   unprimeable number   (optional) show the lowest unprimeable number ending in a specific decimal digit   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)   (optional) use commas in the numbers where appropriate Show all output here, on this page. Also see   the     OEIS     entry:   A118118 (unprimeable)   with some useful counts to compare unprimeable number   the Wiktionary entry (reference from below):   (arithmetic definition) unprimeable   from the Adam Spencer book   (page 200):   Adam Spencer's World of Numbers       (Xoum Publishing)
#XPL0
XPL0
func IsPrime(N); \Return 'true' if N is prime int N, I; [if N <= 2 then return N = 2; if (N&1) = 0 then \even >2\ return false; for I:= 3 to sqrt(N) do [if rem(N/I) = 0 then return false; I:= I+1; ]; return true; ];   func Unprimeable(N); \Return 'true' if N is unprimeable int N, I, J, Len, D, SD; char Num(10); [I:= 0; \take N apart repeat N:= N/10; Num(I):= rem(0); I:= I+1; until N = 0; Len:= I; \number of digits in N (length) for J:= 0 to Len-1 do [SD:= Num(J); \save digit for D:= 0 to 9 do \replace with all digits [Num(J):= D; N:= 0; \rebuild N for I:= Len-1 downto 0 do N:= N*10 + Num(I); if IsPrime(N) then return false; ]; Num(J):= SD; \restore saved digit ]; return true; ];   int C, N, D; [Text(0, "First 35 unprimeables:^m^j"); C:= 0; N:= 100; loop [if Unprimeable(N) then [C:= C+1; if C <= 35 then [IntOut(0, N); ChOut(0, ^ )]; if C = 600 then quit; ]; N:= N+1; ]; Text(0, "^m^j600th unprimeable: "); IntOut(0, N); CrLf(0); for D:= 0 to 9 do [IntOut(0, D); Text(0, ": "); N:= 100 + D; loop [if Unprimeable(N) then [IntOut(0, N); CrLf(0); quit; ]; N:= N+10; ]; ]; ]
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
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   #define MAX_PRIME 1000000 char *primes; int n_primes;   /* Sieve. If we were to handle 10^9 range, use bit field. Regardless, * if a large amount of prime numbers need to be tested, sieve is fast. */ void init_primes() { int j; primes = malloc(sizeof(char) * MAX_PRIME); memset(primes, 1, MAX_PRIME); primes[0] = primes[1] = 0; int i = 2; while (i * i < MAX_PRIME) { for (j = i * 2; j < MAX_PRIME; j += i) primes[j] = 0; while (++i < MAX_PRIME && !primes[i]); } }   int left_trunc(int n) { int tens = 1; while (tens < n) tens *= 10;   while (n) { if (!primes[n]) return 0; tens /= 10; if (n < tens) return 0; n %= tens; } return 1; }   int right_trunc(int n) { while (n) { if (!primes[n]) return 0; n /= 10; } return 1; }   int main() { int n; int max_left = 0, max_right = 0; init_primes();   for (n = MAX_PRIME - 1; !max_left; n -= 2) if (left_trunc(n)) max_left = n;   for (n = MAX_PRIME - 1; !max_right; n -= 2) if (right_trunc(n)) max_right = n;   printf("Left: %d; right: %d\n", max_left, max_right); 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.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const func integer: randN (in integer: n) is return ord(rand(1, n) = 1);   const func integer: unbiased (in integer: n) is func result var integer: unbiased is 0; begin repeat unbiased := randN(n); until unbiased <> randN(n); end func;   const proc: main is func local const integer: tests is 50000; var integer: n is 0; var integer: sumBiased is 0; var integer: sumUnbiased is 0; var integer: count is 0; begin for n range 3 to 6 do sumBiased := 0; sumUnbiased := 0; for count range 1 to tests do sumBiased +:= randN(n); sumUnbiased +:= unbiased(n); end for; writeln(n <& ": " <& flt(100 * sumBiased) / flt(tests) digits 3 lpad 6 <& " " <& flt(100 * sumUnbiased) / flt(tests) digits 3 lpad 6); end for; end func;
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.
#Sidef
Sidef
func randN (n) { n.rand / (n-1) -> int }   func unbiased(n) { var n1 = nil do { n1 = randN(n) } while (n1 == randN(n)) return n1 }   var iterations = 1000   for n in (3..6) { var raw = [] var fixed = [] iterations.times { raw[ randN(n) ] := 0 ++ fixed[ unbiased(n) ] := 0 ++ } printf("N=%d randN: %s, %4.1f%% unbiased: %s, %4.1f%%\n", n, [raw, fixed].map {|a| (a.dump, a[1] * 100 / iterations) }...) }
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.
#PARI.2FGP
PARI/GP
install("truncate", "isL", "trunc")   trunc("/tmp/test.file", 20)
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.
#Pascal
Pascal
  Program FileTruncate;   uses SysUtils;   var myfile: file of byte; filename: string; position: integer;   begin write('File for truncation: '); readln(filename); if not FileExists(filename) then begin writeln('Error: File does not exist.'); exit; end;   write('Truncate position: '); readln(position);   Assign(myfile, filename); Reset(myfile); if FileSize(myfile) < position then begin writeln('Warning: The file "', filename, '" is too short. No need to truncate at position ', position); Close(myfile); exit; end;   Seek(myfile, position); Truncate(myfile); Close(myfile); writeln('File "', filename, '" truncated at position ', position, '.'); end.  
http://rosettacode.org/wiki/Tree_datastructures
Tree datastructures
The following shows a tree of data with nesting denoted by visual levels of indentation: RosettaCode rocks code comparison wiki mocks trolling A common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of nodes captures the indentation of the tree. Lets call this the nest form. # E.g. if child nodes are surrounded by brackets # and separated by commas then: RosettaCode(rocks(code, ...), ...) # But only an _example_ Another datastructure for trees is to construct from the root an ordered list of the nodes level of indentation and the name of that node. The indentation for the root node is zero; node 'rocks is indented by one level from the left, and so on. Lets call this the indent form. 0 RosettaCode 1 rocks 2 code ... Task Create/use a nest datastructure format and textual representation for arbitrary trees. Create/use an indent datastructure format and textual representation for arbitrary trees. Create methods/classes/proceedures/routines etc to: Change from a nest tree datastructure to an indent one. Change from an indent tree datastructure to a nest one Use the above to encode the example at the start into the nest format, and show it. transform the initial nest format to indent format and show it. transform the indent format to final nest format and show it. Compare initial and final nest formats which should be the same. Note It's all about showing aspects of the contrasting datastructures as they hold the tree. Comparing nested datastructures is secondary - saving formatted output as a string then a string compare would suffice for this task, if its easier. Show all output on this page.
#Wren
Wren
import "/dynamic" for Struct import "/fmt" for Fmt   var NNode = Struct.create("NNode", ["name", "children"]) var INode = Struct.create("INode", ["level", "name"])   var sw = ""   var printNest // recursive printNest = Fn.new { |n, level| if (level == 0) sw = sw + "\n==Nest form==\n\n" sw = sw + Fmt.swrite("$0s$s\n", " " * level, n.name) for (c in n.children) { sw = sw + (" " * (level + 1)) printNest.call(c, level+1) } }   var toNest // recursive toNest = Fn.new { |iNodes, start, level, n| if (level == 0) n.name = iNodes[0].name var i = start + 1 while (i < iNodes.count) { if (iNodes[i].level == level + 1) { var c = NNode.new(iNodes[i].name, []) toNest.call(iNodes, i, level+1, c) n.children.add(c) } else if (iNodes[i].level <= level) return i = i + 1 } }   var printIndent = Fn.new { |iNodes| sw = sw + "\n==Indent form==\n\n" for (n in iNodes) sw = sw + Fmt.swrite("$d $s\n", n.level, n.name) }   var toIndent // recursive toIndent = Fn.new { |n, level, iNodes| iNodes.add(INode.new(level, n.name)) for (c in n.children) toIndent.call(c, level+1, iNodes) }   var n1 = NNode.new("RosettaCode", []) var n2 = NNode.new("rocks", [NNode.new("code", []), NNode.new("comparison", []), NNode.new("wiki", [])]) var n3 = NNode.new("mocks", [NNode.new("trolling", [])]) n1.children.add(n2) n1.children.add(n3)   printNest.call(n1, 0) var s1 = sw System.print(s1)   var iNodes = [] toIndent.call(n1, 0, iNodes) sw = "" printIndent.call(iNodes) System.print(sw)   var n = NNode.new("", []) toNest.call(iNodes, 0, 0, n) sw = "" printNest.call(n, 0) var s2 = sw System.print(s2)   System.print("\nRound trip test satisfied? %(s1 == s2)")
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.
#Ada
Ada
private with Ada.Containers.Doubly_Linked_Lists;   generic type State is (<>); -- State'First is starting state type Symbol is (<>); -- Symbol'First is blank package Turing is   Start: constant State := State'First; Halt: constant State := State'Last; subtype Action_State is State range Start .. State'Pred(Halt);   Blank: constant Symbol := Symbol'First;   type Movement is (Left, Stay, Right);   type Action is record New_State: State; Move_To: Movement; New_Symbol: Symbol; end record;   type Rules_Type is array(Action_State, Symbol) of Action;   type Tape_Type is limited private;   type Symbol_Map is array(Symbol) of Character;   function To_String(Tape: Tape_Type; Map: Symbol_Map) return String; function Position_To_String(Tape: Tape_Type; Marker: Character := '^') return String; function To_Tape(Str: String; Map: Symbol_Map) return Tape_Type;   procedure Single_Step(Current: in out State; Tape: in out Tape_Type; Rules: Rules_Type);   procedure Run(The_Tape: in out Tape_Type; Rules: Rules_Type; Max_Steps: Natural := Natural'Last; Print: access procedure(Tape: Tape_Type; Current: State)); -- runs from Start State until either Halt or # Steps exceeds Max_Steps -- if # of steps exceeds Max_Steps, Constrained_Error is raised; -- if Print is not null, Print is called at the beginning of each step   private package Symbol_Lists is new Ada.Containers.Doubly_Linked_Lists(Symbol); subtype List is Symbol_Lists.List;   type Tape_Type is record Left: List; Here: Symbol; Right: List; end record; end Turing;
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.
#11l
11l
V rad = math:pi / 4 V deg = 45.0 print(‘Sine: ’sin(rad)‘ ’sin(radians(deg))) print(‘Cosine: ’cos(rad)‘ ’cos(radians(deg))) print(‘Tangent: ’tan(rad)‘ ’tan(radians(deg))) V arcsine = asin(sin(rad)) print(‘Arcsine: ’arcsine‘ ’degrees(arcsine)) V arccosine = acos(cos(rad)) print(‘Arccosine: ’arccosine‘ ’degrees(arccosine)) V arctangent = atan(tan(rad)) print(‘Arctangent: ’arctangent‘ ’degrees(arctangent))
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).
#11l
11l
F f(x) R sqrt(abs(x)) + 5 * x ^ 3   V s = Array(1..11) s.reverse() L(x) s V result = f(x) I result > 400 print(‘#.: #.’.format(x, ‘TOO LARGE!’)) E print(‘#.: #.’.format(x, result)) print()
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]
#J
J
[[[3]], 1, [[3]], 1 1 1 [[[3]], 1, [[3]], 1] |syntax error
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]
#Julia
Julia
function makenested(list) nesting = 0 str = isempty(list) ? "[]" : "" for n in list if n > nesting str *= "["^(n - nesting) nesting = n elseif n < nesting str *= "]"^(nesting - n) * ", " nesting = n end str *= "$n, " end str *= "]"^nesting return eval(Meta.parse(str)) end   for test in [[], [1, 2, 4], [3, 1, 3, 1], [1, 2, 3, 1], [3, 2, 1, 3], [3, 3, 3, 1, 1, 3, 3, 3]] result = "$test => $(makenested(test))" println(replace(result, "Any" => "")) 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]
#Nim
Nim
import sequtils, strutils   type Kind = enum kValue, kList Node = ref object case kind: Kind of kValue: value: int of kList: list: seq[Node]     proc newTree(s: varargs[int]): Node = ## Build a tree from a list of level values. var level = 1 result = Node(kind: kList) var stack = @[result] for n in s: if n <= 0: raise newException(ValueError, "expected a positive integer, got " & $n) let node = Node(kind: kValue, value: n) if n < level: # Unstack lists. stack.setLen(n) level = n else: while n > level: # Create intermediate lists. let newList = Node(kind: kList) stack[^1].list.add newList stack.add newList inc level # Add value. stack[^1].list.add node     proc `$`(node: Node): string = ## Display a tree using a nested lists representation. if node.kind == kValue: $node.value else: '[' & node.list.mapIt($it).join(", ") & ']'     for list in [newSeq[int](), # Empty list (== @[]). @[1, 2, 4], @[3, 1, 3, 1], @[1, 2, 3, 1], @[3, 2, 1, 3], @[3, 3, 3, 1, 1, 3, 3, 3]]: echo ($list).align(25), " → ", newTree(list)
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.
#Forth
Forth
: lastbit ( n1 -- n2) dup if 1 swap begin dup 1 <> while swap 1+ swap 1 rshift repeat drop then ;   : bit 1 swap lshift and 0<> ; ( n1 n2 -- f) : bitcount 0 swap begin dup while dup 1- and swap 1+ swap repeat drop ;   12 constant #stat \ number of statements \ encoding of the statements : s1 >r #stat 12 = r> 0 bit = ; \ heavy use of binary : s2 >r r@ 4032 and bitcount 3 = r> 1 bit = ; : s3 >r r@ 2730 and bitcount 2 = r> 2 bit = ; : s4 >r r@ 4 bit 0= 96 r@ over and = or r> 3 bit = ; : s5 >r r@ 14 and 0= r> 4 bit = ; : s6 >r r@ 1365 and bitcount 4 = r> 5 bit = ; : s7 >r r@ 1 bit r@ 2 bit xor r> 6 bit = ; : s8 >r r@ 6 bit 0= 48 r@ over and = or r> 7 bit = ; : s9 >r r@ 63 and bitcount 3 = r> 8 bit = ; : s10 >r 3072 r@ over and = r> 9 bit = ; : s11 >r r@ 448 and bitcount 1 = r> 10 bit = ; : s12 >r r@ 2047 and bitcount 4 = r> 11 bit = ; : list #stat 0 do dup i bit if i 1+ . then loop drop ;   : nearmiss? \ do we have a near miss? over #stat 1- = if ( true-pattern #true stat-pattern) ." Near miss with statements " dup list ." true (failed " >r over invert 1 #stat lshift 1- and lastbit 0 .r ." )" cr r> then \ extract the failed statement ; \ have we found a solution? : solution? ( true-pattern #true stat-pattern) over #stat = if ." Solution! with statements " dup list ." true." cr then ;   : 12statements \ test the twelve patterns 1 #stat lshift 0 do \ create another bit pattern i s12 2* i s11 + 2* i s10 + 2* i s9 + 2* i s8 + 2* i s7 + 2* i s6 + 2* i s5 + 2* i s4 + 2* i s3 + 2* i s2 + 2* i s1 + abs dup bitcount i solution? nearmiss? drop drop drop loop \ count number of bytes and evaluate ;   12statements
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.
#Factor
Factor
USING: arrays combinators eval formatting io kernel listener math.combinatorics prettyprint qw sequences splitting vocabs.parser ; IN: rosetta-code.truth-table   : prompt ( -- str ) "Please enter a boolean expression using 1-long" print "variable names and postfix notation. Available" print "operators are and, or, not, and xor. Example:" print "> a b and" print nl "> " write readln nl ;   : replace-var ( str -- str' ) dup length 1 = [ drop "%s" ] when ;   : replace-vars ( str -- str' ) " " split [ replace-var ] map " " join ;   : extract-vars ( str -- seq ) " " split [ length 1 = ] filter ;   : count-vars ( str -- n ) " " split [ "%s" = ] count ;   : truth-table ( n -- seq ) qw{ t f } swap selections ;   : print-row ( seq -- ) [ write bl ] each ;   : print-table ( seq -- ) [ print-row nl ] each ;   ! Adds a column to the end of a two-dimensional array. : add-col ( seq col -- seq' ) [ flip ] dip 1array append flip ;   : header ( str -- ) [ extract-vars ] [ ] bi [ print-row "| " write ] [ print ] bi* "=================" print ;   : solve-expr ( seq str -- ? ) vsprintf [ "kernel" use-vocab ( -- x ) (eval) ] with-interactive-vocabs ;   : results ( str -- seq ) replace-vars dup count-vars truth-table [ swap solve-expr unparse ] with map ;   : main ( -- ) prompt [ header t ] [ replace-vars count-vars truth-table ] [ results [ "| " prepend ] map ] tri add-col print-table drop ;   MAIN: main
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
#Go
Go
package main   import ( "math" "fmt" )   type Direction byte   const ( RIGHT Direction = iota UP LEFT DOWN )   func generate(n,i int, c byte) { s := make([][]string, n) for i := 0; i < n; i++ { s[i] = make([]string, n) } dir := RIGHT y := n / 2 var x int if (n % 2 == 0) { x = y - 1 } else { x = y } // shift left for even n's   for j := i; j <= n * n - 1 + i; j++ { if (isPrime(j)) { if (c == 0) { s[y][x] = fmt.Sprintf("%3d", j) } else { s[y][x] = fmt.Sprintf("%2c ", c) } } else { s[y][x] = "---" }   switch dir { case RIGHT : if (x <= n - 1 && s[y - 1][x] == "" && j > i) { dir = UP } case UP : if (s[y][x - 1] == "") { dir = LEFT } case LEFT : if (x == 0 || s[y + 1][x] == "") { dir = DOWN } case DOWN : if (s[y][x + 1] == "") { dir = RIGHT } }   switch dir { case RIGHT : x += 1 case UP : y -= 1 case LEFT : x -= 1 case DOWN : y += 1 } }   for _, row := range s { fmt.Println(fmt.Sprintf("%v", row)) } fmt.Println() }   func isPrime(a int) bool { if (a == 2) { return true } if (a <= 1 || a % 2 == 0) { return false } max := int(math.Sqrt(float64(a))) for n := 3; n <= max; n += 2 { if (a % n == 0) { return false } } return true }   func main() { generate(9, 1, 0) // with digits generate(9, 1, '*') // with * }
http://rosettacode.org/wiki/Unprimeable_numbers
Unprimeable numbers
Definitions As used here, all unprimeable numbers   (positive integers)   are always expressed in base ten. ───── Definition from OEIS ─────: Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed. ───── Definition from Wiktionary   (referenced from Adam Spencer's book) ─────: (arithmetic)   that cannot be turned into a prime number by changing just one of its digits to any other digit.   (sic) Unprimeable numbers are also spelled:   unprimable. All one─ and two─digit numbers can be turned into primes by changing a single decimal digit. Examples 190   isn't unprimeable,   because by changing the zero digit into a three yields   193,   which is a prime. The number   200   is unprimeable,   since none of the numbers   201, 202, 203, ··· 209   are prime, and all the other numbers obtained by changing a single digit to produce   100, 300, 400, ··· 900,   or   210, 220, 230, ··· 290   which are all even. It is valid to change   189   into   089   by changing the   1   (one)   into a   0   (zero),   which then the leading zero can be removed,   and then treated as if the   "new"   number is   89. Task   show the first   35   unprimeable numbers   (horizontally, on one line, preferably with a title)   show the   600th   unprimeable number   (optional) show the lowest unprimeable number ending in a specific decimal digit   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)   (optional) use commas in the numbers where appropriate Show all output here, on this page. Also see   the     OEIS     entry:   A118118 (unprimeable)   with some useful counts to compare unprimeable number   the Wiktionary entry (reference from below):   (arithmetic definition) unprimeable   from the Adam Spencer book   (page 200):   Adam Spencer's World of Numbers       (Xoum Publishing)
#zkl
zkl
var [const] BI=Import("zklBigNum"); // libGMP   fcn isUnprimeable(n){ //--> n (!0) or Void, a filter bn,t := BI(0),n/10*10; foreach k in ([t+1..t+9,2]){ if(bn.set(k).probablyPrime()) return(Void.Skip) } if(n==n/2*2 or n==n/5*5){ if(not bn.set(n%10).probablyPrime()) return(n); if( (n % (10).pow(n.toFloat().log10()) ) > 9) return(n); } foreach k in ([1 .. n.toFloat().log10()]){ u,v := (10).pow(k), (n - (u * ((n/u) % 10))); foreach d in (10){ if(bn.set(v + d*u).probablyPrime()) return(Void.Skip); } } n } fcn isUnprimeableW{ [100..].tweak(isUnprimeable) } // --> iterator
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.23
C#
using System; // [email protected] using System.Collections.Generic; class truncatable_primes { static void Main() { uint m = 1000000; Console.Write("L " + L(m) + " R " + R(m) + " "); var sw = System.Diagnostics.Stopwatch.StartNew(); for (int i = 1000; i > 0; i--) { L(m); R(m); } Console.Write(sw.Elapsed); Console.Read(); }   static uint L(uint n) { n -= n & 1; n--; for (uint d, d1 = 100; ; n -= 2) { while (n % 3 == 0 || n % 5 == 0 || n % 7 == 0) n -= 2; if ((d = n % 10) == 3 || d == 7) { while (d1 < n && d < (d = n % d1) && isP(d)) d1 *= 10; if (d1 > n && isP(n)) return n; d1 = 100; } } }   static uint R(uint m) { var p = new List<uint>() { 2, 3, 5, 7 }; uint n = 20, np; for (int i = 1; i < p.Count; n = 10 * p[i++]) { if ((np = n + 1) >= m) break; if (isP(np)) p.Add(np); if ((np = n + 3) >= m) break; if (isP(np)) p.Add(np); if ((np = n + 7) >= m) break; if (isP(np)) p.Add(np); if ((np = n + 9) >= m) break; if (isP(np)) p.Add(np); } return p[p.Count - 1]; }   static bool isP(uint n) { if (n < 7) return n == 2 || n == 3 || n == 5; if ((n & 1) == 0 || n % 3 == 0 || n % 5 == 0) return false; for (uint r = (uint)Math.Sqrt(n), d = 7; d <= r; d += 30) if (n % (d + 00) == 0 || n % (d + 04) == 0 || n % (d + 06) == 0 || n % (d + 10) == 0 || n % (d + 12) == 0 || n % (d + 16) == 0 || n % (d + 22) == 0 || n % (d + 24) == 0) return false; return true; } }
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.
#Tcl
Tcl
# 1,0 random generator factory with 1 appearing 1/N'th of the time proc randN n {expr {rand()*$n < 1}}   # uses a biased generator of 1 or 0, to create an unbiased one proc unbiased {biased} { while 1 { if {[set a [eval $biased]] != [eval $biased]} {return $a} } }   for {set n 3} {$n <= 6} {incr n} { set biased [list randN $n] for {set i 0;array set c {0 0 1 0}} {$i < 1000000} {incr i} { incr c([eval $biased]) } puts [format " biased %d => #0=%d #1=%d ratio=%.2f%%" $n $c(0) $c(1) \ [expr {100.*$c(1)/$i}]] for {set i 0;array set c {0 0 1 0}} {$i < 1000000} {incr i} { incr c([unbiased $biased]) } puts [format "unbiased %d => #0=%d #1=%d ratio=%.2f%%" $n $c(0) $c(1) \ [expr {100.*$c(1)/$i}]] }
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.
#Perl
Perl
# Open a file for writing, and truncate it to 1234 bytes. open FOO, ">>file" or die; truncate(FOO, 1234); close FOO;   # Truncate a file to 567 bytes. 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.
#Phix
Phix
without js -- (file i/o) ?get_file_size("test.txt") ?set_file_size("test.txt",100) ?get_file_size("test.txt") ?set_file_size("test.txt",1024) ?get_file_size("test.txt")
http://rosettacode.org/wiki/Tree_datastructures
Tree datastructures
The following shows a tree of data with nesting denoted by visual levels of indentation: RosettaCode rocks code comparison wiki mocks trolling A common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of nodes captures the indentation of the tree. Lets call this the nest form. # E.g. if child nodes are surrounded by brackets # and separated by commas then: RosettaCode(rocks(code, ...), ...) # But only an _example_ Another datastructure for trees is to construct from the root an ordered list of the nodes level of indentation and the name of that node. The indentation for the root node is zero; node 'rocks is indented by one level from the left, and so on. Lets call this the indent form. 0 RosettaCode 1 rocks 2 code ... Task Create/use a nest datastructure format and textual representation for arbitrary trees. Create/use an indent datastructure format and textual representation for arbitrary trees. Create methods/classes/proceedures/routines etc to: Change from a nest tree datastructure to an indent one. Change from an indent tree datastructure to a nest one Use the above to encode the example at the start into the nest format, and show it. transform the initial nest format to indent format and show it. transform the indent format to final nest format and show it. Compare initial and final nest formats which should be the same. Note It's all about showing aspects of the contrasting datastructures as they hold the tree. Comparing nested datastructures is secondary - saving formatted output as a string then a string compare would suffice for this task, if its easier. Show all output on this page.
#zkl
zkl
fcn nestToIndent(nestTree){ fcn(out,node,level){ out.append(List(level,node[0])); // (n,name) or ("..",name) if(node.len()>1){ // (name children), (name, (tree)) level+=1; foreach child in (node[1,*]){ if(String.isType(child)) out.append(List(level,child)); else self.fcn(out,child,level) } } out }(List(),nestTree,0) } fcn nestToString(nestTree,dot="."){ fcn(out,dot,node,level){ out.writeln(dot*level,node[0]); // (name) if(node.len()>1){ // (name children), (name, (tree)) level+=1; foreach child in (node[1,*]){ if(String.isType(child)) out.writeln(dot*level,child); else self.fcn(out,dot,child,level) } } out }(Data(),dot,nestTree,0).text }   fcn indentToNest(iTree,depth=0,nTree=List()){ while(iTree){ // (n,name) d, name := iTree[0]; if(d==depth){ nTree.append(name); iTree.pop(0); } else if(d>depth){ // assume can't skip levels down if(nTree.len()>1 and not List.isType((nm:=nTree[-1]))){ nTree[-1]=(children:=List(nm)); indentToNest(iTree,d,children); }else{ nTree.append(children:=List(name)); iTree.pop(0); indentToNest(iTree,d+1,children); } } else break; // d<depth } return(nTree) } fcn indentToString(indentTree){ indentTree.apply("concat"," ").concat("\n") }
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such a machine capable of taking the definition of any other Turing machine and executing it. Of course, you will not have an infinite tape, but you should emulate this as much as is possible. The three permissible actions on the tape are "left", "right" and "stay". To test your universal Turing machine (and prove your programming language is Turing complete!), you should execute the following two Turing machines based on the following definitions. Simple incrementer States: q0, qf Initial state: q0 Terminating states: qf Permissible symbols: B, 1 Blank symbol: B Rules: (q0, 1, 1, right, q0) (q0, B, 1, stay, qf) The input for this machine should be a tape of 1 1 1 Three-state busy beaver States: a, b, c, halt Initial state: a Terminating states: halt Permissible symbols: 0, 1 Blank symbol: 0 Rules: (a, 0, 1, right, b) (a, 1, 1, left, c) (b, 0, 1, left, a) (b, 1, 1, right, b) (c, 0, 1, left, b) (c, 1, 1, stay, halt) The input for this machine should be an empty tape. Bonus: 5-state, 2-symbol probable Busy Beaver machine from Wikipedia States: A, B, C, D, E, H Initial state: A Terminating states: H Permissible symbols: 0, 1 Blank symbol: 0 Rules: (A, 0, 1, right, B) (A, 1, 1, left, C) (B, 0, 1, right, C) (B, 1, 1, right, B) (C, 0, 1, right, D) (C, 1, 0, left, E) (D, 0, 1, left, A) (D, 1, 1, left, D) (E, 0, 1, stay, H) (E, 1, 0, left, A) The input for this machine should be an empty tape. This machine runs for more than 47 millions steps.
#Amazing_Hopper
Amazing Hopper
  #include <hopper.h> #proto UniversalTuringMachine(_X_)   main: .ctrlc   stbegin=0,stEnd=0,state=0,ptr=0 tape=0,states=0,rules=0,long=0,tapeSize=0 file="turing/prg03.tm"   // load program, rules & states: jsub(load Archive)   // RUN Universal Turing Machine program: i=1 __TURING_RUN__: _Universal Turing Machine ([i,1:end]get(rules)) ++i,{long,i}gt? do{ i=1 } jt(__TURING_RUN__) println exit(0)   .locals   printTape: #hl{ print(tape[1:(ptr-1)],"\R",tape[ptr],"\OFF",tape[(ptr+1):end],"\n") //sleep(0.1) } up(1) clear mark back   Universal Turing Machine(rules) cont=1 clear mark   #hl{ if( rules[1] == state ) if( tape[ptr] == rules[2] ) tape[ptr] = rules[3] ptr += rules[4] if(ptr==0) } ++tapeSize {0,1,tape}, array(INSERT), ++ptr #hl{ else if(ptr>tapeSize) } ++tapeSize {tapeSize,tape},array(RESIZE), [tapeSize]{0},put(tape),clear mark #hl{ endif state = rules[5] if(state == stEnd) cont=0 endif } jsub(print Tape) #hl{ endif endif }, {cont} back   load Archive: {","}tok sep {file} stats file [1,1:end],{file},!(5),load, mov(tape) [2,1:3],  !(5),load, mov(states) [3:end,1:5], load, mov(rules) clear mark [1:end,4]get(rules),colMoving=0, mov(colMoving) {"1","RIGHT",colMoving} transform, mov(colMoving) {"-1","LEFT",colMoving} transform, mov(colMoving) {"0","STAY",colMoving} transform, xtonum, put(rules) clear mark {0}reshape(tape) size(tape),lengthTape=0,mov(lengthTape),[2]get(lengthTape),mov(tapeSize) #hl{ stbegin=states[1,1] stEnd=states[1,2] ptr=states[1,3] state=stbegin } data rules=0, size(rules), mov(datarules), [2]get(data rules), mov(long) {""}tok sep back  
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.
#ACL2
ACL2
(defun fac (n) (if (zp n) 1 (* n (fac (1- n)))))   (defconst *pi-approx* (/ 3141592653589793238462643383279 (expt 10 30)))   (include-book "arithmetic-3/floor-mod/floor-mod" :dir :system)   (defun dgt-to-str (d) (case d (1 "1") (2 "2") (3 "3") (4 "4") (5 "5") (6 "6") (7 "7") (8 "8") (9 "9") (0 "0")))   (defmacro cat (&rest args) `(concatenate 'string ,@args))   (defun num-to-str-r (n) (if (zp n) "" (cat (num-to-str-r (floor n 10)) (dgt-to-str (mod n 10)))))   (defun num-to-str (n) (cond ((= n 0) "0") ((< n 0) (cat "-" (num-to-str-r (- n)))) (t (num-to-str-r n))))   (defun pad-with-zeros (places str lngth) (declare (xargs :measure (nfix (- places lngth)))) (if (zp (- places lngth)) str (pad-with-zeros places (cat "0" str) (1+ lngth))))   (defun as-decimal-str (r places) (let ((before (floor r 1)) (after (floor (* (expt 10 places) (mod r 1)) 1))) (cat (num-to-str before) "." (let ((afterstr (num-to-str after))) (pad-with-zeros places afterstr (length afterstr))))))   (defun taylor-sine (theta terms term) (declare (xargs :measure (nfix (- terms term)))) (if (zp (- terms term)) 0 (+ (/ (*(expt -1 term) (expt theta (1+ (* 2 term)))) (fac (1+ (* 2 term)))) (taylor-sine theta terms (1+ term)))))   (defun sine (theta) (taylor-sine (mod theta (* 2 *pi-approx*)) 20 0)) ; About 30 places of accuracy   (defun cosine (theta) (sine (+ theta (/ *pi-approx* 2))))   (defun tangent (theta) (/ (sine theta) (cosine theta)))   (defun rad->deg (rad) (* 180 (/ rad *pi-approx*)))   (defun deg->rad (deg) (* *pi-approx* (/ deg 180)))   (defun trig-demo () (progn$ (cw "sine of pi / 4 radians: ") (cw (as-decimal-str (sine (/ *pi-approx* 4)) 20)) (cw "~%sine of 45 degrees: ") (cw (as-decimal-str (sine (deg->rad 45)) 20)) (cw "~%cosine of pi / 4 radians: ") (cw (as-decimal-str (cosine (/ *pi-approx* 4)) 20)) (cw "~%tangent of pi / 4 radians: ") (cw (as-decimal-str (tangent (/ *pi-approx* 4)) 20)) (cw "~%")))
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).
#Ada
Ada
with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions;   procedure Trabb_Pardo_Knuth is   type Real is digits 6 range -400.0 .. 400.0;   package TIO renames Ada.Text_IO; package FIO is new TIO.Float_IO(Real); package Math is new Ada.Numerics.Generic_Elementary_Functions(Real);   function F(X: Real) return Real is begin return (Math.Sqrt(abs(X)) + 5.0 * X**3); end F;   Values: array(1 .. 11) of Real;   begin TIO.Put("Please enter 11 Numbers:"); for I in Values'Range loop FIO.Get(Values(I)); end loop;   for I in reverse Values'Range loop TIO.Put("f("); FIO.Put(Values(I), Fore => 2, Aft => 3, Exp => 0); TIO.Put(")="); begin FIO.Put(F(Values(I)), Fore=> 4, Aft => 3, Exp => 0); exception when Constraint_Error => TIO.Put("-->too large<--"); end; TIO.New_Line; end loop;   end Trabb_Pardo_Knuth;
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]
#OxygenBasic
OxygenBasic
  uses console declare DemoTree(string src) DemoTree "[]" DemoTree "[1, 2, 4]" DemoTree "[3, 1, 3, 1]" DemoTree "[1, 2, 3, 1]" DemoTree "[3, 2, 1, 3]" DemoTree "[3, 3, 3, 1, 1, 3, 3, 3]" pause end   /* RESULTS: ========   [] []   [1, 2, 4] [ 1,[ 2,[[ 4]]]]   [3, 1, 3, 1] [[[ 3]], 1,[[ 3]], 1]   [1, 2, 3, 1] [ 1,[ 2,[ 3]], 1]   [3, 2, 1, 3] [[[ 3], 2], 1,[[ 3]]]   [3, 3, 3, 1, 1, 3, 3, 3] [[[ 3, 3, 3]], 1, 1,[[ 3, 3, 3]]] */       sub DemoTree(string src) ========================   string tree=nuls 1000 'TREE OUTPUT int i=1 'src char iterator int j=1 'tree char iterator byte bs at strptr src 'src bytes byte bt at strptr tree 'tree bytes int bl=len src 'end of src int lvl 'current tree level int olv 'prior tree level int v 'number value string vs 'number in string form   do exit if i>bl select bs[i] case 91 '[' i++ case 93 ']' if i=bl gosub writex endif i++ case 44 ',' i++ gosub writex case 0 to 32 'white space i++ 'bt[j]=" " : j++ case 48 to 57 '0..9' gosub ReadDigits case else i++ end select loop tree=left(tree,j-1) output src cr output tree cr cr exit sub   'SUBROUTINES OF DEMOTREE: =========================   writex: ======= olv=lvl if i>=bl if v=0 and olv=0 tree="[]" : j=3 ret endif endif if v<olv gosub WriteRbr endif if olv gosub WriteComma endif if v>olv gosub WriteLbr endif gosub WriteDigits '3]]' if i>=bl v=0 gosub WriteRbr endif ret   ReadDigits: =========== v=0 while i<=bl select bs[i] case 48 to 57 '1..9 v*=10 : v+=bs[i]-48 'digit case else exit while end select i++ wend ret ' WriteDigits: ============ vs=" "+str(v) : mid(tree,j,vs) : j+=len vs ret   WriteLbr: ========= while v>lvl bt[j]=91 : j++ : lvl++ wend ret   WriteRbr: ========= while v<lvl bt[j]=93 : j++ : lvl-- wend ret   WriteComma: =========== bt[j]=44 : j++ ',' ret   end sub  
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]
#Perl
Perl
#!/usr/bin/perl   use strict; use warnings; use Data::Dump qw(dd pp);   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] );   for my $before ( @tests ) { dd { before => $before }; local $_ = (pp $before) =~ s/\d+/ '['x($&-1) . $& . ']'x($&-1) /ger; 1 while s/\](,\s*)\[/$1/; my $after = eval; dd { after => $after }; }
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.
#FreeBASIC
FreeBASIC
Dim As Integer nEnunciados = 12, intento, enun, errado Dim As Integer Afirm(nEnunciados), T(nEnunciados)   For intento = 0 To 2^nEnunciados-1 REM Postular respuesta: For enun = 1 To 12 T(enun) = (intento And 2^(enun-1)) <> 0 Next enum   REM Prueba de consistencia: Afirm(1) = T(1) = (nEnunciados = 12) Afirm(2) = T(2) = ((T(7)+T(8)+T(9)+T(10)+T(11)+T(12)) = -3) Afirm(3) = T(3) = ((T(2)+T(4)+T(6)+T(8)+T(10)+T(12)) = -2) Afirm(4) = T(4) = ((Not T(5) Or (T(6) And T(7)))) Afirm(5) = T(5) = (Not T(2) And Not T(3) And Not T(4)) Afirm(6) = T(6) = ((T(1)+T(3)+T(5)+T(7)+T(9)+T(11)) = -4) Afirm(7) = T(7) = ((T(2) Or T(3))) Afirm(8) = T(8) = ((Not T(7) Or (T(5) And T(6)))) Afirm(9) = T(9) = ((T(1)+T(2)+T(3)+T(4)+T(5)+T(6)) = -3) Afirm(10) = T(10) = (T(11) And T(12)) Afirm(11) = T(11) = ((T(7)+T(8)+T(9)) = -1) Afirm(12) = T(12) = ((T(1)+T(2)+T(3)+T(4)+T(5)+T(6) + T(7)+T(8)+T(9)+T(10)+T(11)) = -4)   Dim As Integer suma = 0 For cont As Integer = 1 To 12 suma += Afirm(cont) Next cont   Select Case suma Case -11 Color 7: Print "Casi resuelto, con los enunciados "; For enun = 1 To 12 If T(enun) Then Print ; enun; " "; If Not Afirm(enun) Then errado = enun Next enun Print "verdaderos (falsos"; errado; ")." Case -12 Color 10: Print "­Resuelto! con los enunciados "; For enun = 1 To 12 If T(enun) Then Print ; enun; " "; Next enun Print "verdaderos." End Select Next intento Sleep
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.
#F.C5.8Drmul.C3.A6
Fōrmulæ
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)) }