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/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#Seed7
Seed7
# International class; name and street class 国際( なまえ, Straße ) {   # Say who am I! method 言え { say "I am #{self.なまえ} from #{self.Straße}"; } }   # all the people of the world! var 民族 = [ 国際( "高田 Friederich", "台湾" ), 国際( "Smith Σωκράτης", "Cantù" ), 国際( "Stanisław Lec", "południow" ), ];   民族.each { |garçon| garçon.言え; }
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#Sidef
Sidef
# International class; name and street class 国際( なまえ, Straße ) {   # Say who am I! method 言え { say "I am #{self.なまえ} from #{self.Straße}"; } }   # all the people of the world! var 民族 = [ 国際( "高田 Friederich", "台湾" ), 国際( "Smith Σωκράτης", "Cantù" ), 国際( "Stanisław Lec", "południow" ), ];   民族.each { |garçon| garçon.言え; }
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.
#J
J
tp=: 3 : '+/ (*. _2&(|.!.0)) 1 p: i. y'   NB. 3 : '' explicitly define a "monad" (a one-argument function) NB. i. y list integers up to the provided argument NB. 1 p: create list of 0s, 1s where those ints are prime NB. _2&(|.!.0) "shift" that list to the right by two, filling left side with 0 NB. (*. g) y create a "hook". "and" together the original and shifted lists NB. the result will have a 1 only if that i, and i-2, are both prime NB. +/ sum the and-ed list (get the number of twin pairs)
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.
#jq
jq
def odd_gt2_is_prime: . as $n | if ($n % 3 == 0) then $n == 3 elif ($n % 5 == 0) then $n == 5 elif ($n % 7 == 0) then $n == 7 elif ($n % 11 == 0) then $n == 11 elif ($n % 13 == 0) then $n == 13 elif ($n % 17 == 0) then $n == 17 elif ($n % 19 == 0) then $n == 19 else {i:23} | until( (.i * .i) > $n or ($n % .i == 0); .i += 2) | .i * .i > $n end;   def twin_primes($max): {count:0, i:3, isprime:true} | until(.i >= $max; .i += 2 | if .isprime then if .i|odd_gt2_is_prime then .count+=1 else .isprime = false end else .isprime = (.i|odd_gt2_is_prime) end ) | .count;   pow(10; range(1;8)) | "Number of twin primes less than \(.) is \(twin_primes(.))."
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.
#Julia
Julia
using Formatting, Primes   function counttwinprimepairsbetween(n1, n2) npairs, t = 0, nextprime(n1) while t < n2 p = nextprime(t + 1) if p - t == 2 npairs += 1 end t = p end return npairs end   for t2 in (10).^collect(2:8) paircount = counttwinprimepairsbetween(1, t2) println("Under", lpad(format(t2, commas=true), 12), " there are", lpad(format(paircount, commas=true), 8), " pairs of twin primes.") 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)
#Perl
Perl
use strict; use warnings; use feature 'say'; use ntheory 'is_prime'; use enum qw(False True);   sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }   sub is_unprimeable { my($n) = @_; return False if is_prime($n); my $chrs = length $n; for my $place (0..$chrs-1) { my $pow = 10**($chrs - $place - 1); my $this = substr($n, $place, 1) * $pow; map { return False if $this != $_ and is_prime($n - $this + $_ * $pow) } 0..9; } True }   my($n, @ups); do { push @ups, $n if is_unprimeable(++$n); } until @ups == 600; say "First 35 unprimeables:\n" . join ' ', @ups[0..34]; printf "\n600th unprimeable: %s\n", comma $ups[599];   map { my $x = $_; while ($x += 10) { last if is_unprimeable($x) } say "First unprimeable that ends with $_: " . sprintf "%9s", comma $x; } 0..9;
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identifiers
#zkl
zkl
delta:="\U0394;"; // UTF-8 delta klass:= // embryo(names, numFcns, numClasses, numParents, ...) self.embryo(L("","",delta),0,0,0).cook(); klass.setVar(0,Ref(1)); // indirect set since delta not valid var name klass.vars.println();   dv:=klass.setVar(0); // which actually gets the var, go figure dv.inc(); // ie (*ptr)++ dv.value.println();
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.
#Nim
Nim
import random, sequtils, strformat   type randProc = proc: range[0..1]   randomize()   proc randN(n: Positive): randProc = result = proc: range[0..1] = ord(rand(n) == 0)   proc unbiased(biased: randProc): range[0..1] = result = biased() var that = biased() while result == that: result = biased() that = biased()   for n in 3..6: var biased = randN(n) var v = newSeqWith(1_000_000, biased()) var cnt0, cnt1 = 0 for x in v: if x == 0: inc cnt0 else: inc cnt1 echo &"Biased({n}) → count1 = {cnt1}, count0 = {cnt0}, percent = {100*cnt1 / (cnt1+cnt0):.3f}"   v = newSeqWith(1_000_000, unbiased(biased)) cnt0 = 0 cnt1 = 0 for x in v: if x == 0: inc cnt0 else: inc cnt1 echo &"Unbiased → count1 = {cnt1}, count0 = {cnt0}, percent = {100*cnt1 / (cnt1+cnt0):.3f}"
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.
#OCaml
OCaml
let randN n = if Random.int n = 0 then 1 else 0   let rec unbiased n = let a = randN n in if a <> randN n then a else unbiased n   let () = Random.self_init(); let n = 50_000 in for b = 3 to 6 do let cb = ref 0 in let cu = ref 0 in for i = 1 to n do cb := !cb + (randN b); cu := !cu + (unbiased b); done; Printf.printf "%d: %5.2f%%  %5.2f%%\n" b (100.0 *. float !cb /. float n) (100.0 *. float !cu /. float n) done
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.
#Clojure
Clojure
(defn truncate [file size] (with-open [chan (.getChannel (java.io.FileOutputStream. file true))] (.truncate chan size)))   (truncate "truncate_test.txt" 2)
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.
#D
D
import std.file, std.exception;   void truncateFile(in string name, in size_t newSize) { if (!exists(name) || !isFile(name)) throw new Exception("File not found.");   auto size = getSize(name); if (size <= newSize) throw new Exception( "New size must be smaller than original size.");   auto content = cast(ubyte[])read(name, newSize); if (content.length != newSize) throw new Exception("Reading file failed.");   write(name, content); enforce(getSize(name) == newSize); }   void main() { truncateFile("truncate_test.txt", 0); }
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.
#11l
11l
[([Int] -> Bool)] predicates predicates [+]= st -> st.len == 12 predicates [+]= st -> sum(st[(len)-6 ..]) == 3 predicates [+]= st -> sum(st[(1..).step(2)]) == 2 predicates [+]= st -> I st[4] {(st[5] [&] st[6])} E 1 predicates [+]= st -> sum(st[1.<4]) == 0 predicates [+]= st -> sum(st[(0..).step(2)]) == 4 predicates [+]= st -> sum(st[1.<3]) == 1 predicates [+]= st -> I st[6] {(st[4] [&] st[5])} E 1 predicates [+]= st -> sum(st[0.<6]) == 3 predicates [+]= st -> (st[10] [&] st[11]) predicates [+]= st -> sum(st[6.<9]) == 1 predicates [+]= st -> sum(st[0.<11]) == 4   F to_str(b) R (0.<12).filter(i -> @b[i]).map(i -> i + 1).join(‘ ’)   print(‘Exact hits:’) L(n) 0 .< (1 << 12) V bools = [0] * 12 L(i) 12 I n [&] (1 << (11 - i)) != 0 bools[i] = 1   L(predicate) predicates I Int(predicate(bools)) != bools[L.index] L.break L.was_no_break print(‘ ’to_str(bools))   print("\nNear misses:") L(n) 0 .< (1 << 12) V bools = [0] * 12 L(i) 12 I n [&] (1 << (11 - i)) != 0 bools[i] = 1   V count = 0 L(predicate) predicates I Int(predicate(bools)) == bools[L.index] count++ I count == 11 L(predicate) predicates V i = L.index I Int(predicate(bools)) != bools[i] print(f:‘ (Fails at statement {i + 1:2}) {to_str(bools)}’) L.break
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.
#8080_Assembly
8080 Assembly
;;; CP/M truth table generator ;;; Supported operators: ;;; ~ (not), & (and), | (or), ^ (xor) and => (implies) ;;; Variables are A-Z, constants are 0 and 1. putch: equ 2 puts: equ 9 TVAR: equ 32 TCONST: equ 64 TOP: equ 96 TPAR: equ 128 TMASK: equ 31 TTYPE: equ 224 org 100h lxi h,80h ; Have we got a command line argument? mov a,m ana a lxi d,noarg ; If not, print error message and stop. mvi c,puts jz 5 add l ; Otherwise, 0-terminate the argument string inr a mov l,a mvi m,0 inx h mvi m,'$' ; And $-terminate it also for error messages lxi h,opstk ; Pointer to operator stack on the system stack push h lxi h,80h ; Start of command line lxi b,expr ; Start of expression (output queue for shunting yard) parse: inx h mvi a,' ' ; Ignore all whitespace cmp m jz parse mov a,m ; Load current character ana a ; Done? jz pdone mov d,a ; Store copy in D ori 32 ; Check for variable sui 'a' cpi 26 jnc pconst ; If not variable, go check constants ori TVAR ; It _is_ a variable stax b ; Store token inx b jmp parse ; Next token pconst: mov a,d ; Restore character sui '0' ; 0 or 1 are constants cpi 2 jnc pparen ; If not constant, go check parenthesis ori TCONST ; It _is_ a constant stax b ; Store token inx b jmp parse pparen: mov a,d ; Restore character sui '(' ; ( and ) are parentheses jz ppopen ; Open parenthesis dcr a jnz poper ; If not ( or ), check operators xthl ; Closing parenthesis - get operator stack closep: mov a,l ; If at beginning, missing ( - give error ana a jz emiss dcx h ; Back up pointer mov a,m ; Found it? cpi TPAR jnz closes ; If not, keep scanning xthl ; Get input string back jmp parse ; Keep parsing closes: stax b ; Not parenthesis - put token in output queue inx b jmp closep ; And keep going ppopen: xthl ; Get operator stack mvi m,TPAR ; Store open parenthesis inx h xthl ; Get input string jmp parse poper: push h ; Check tokens - keep input string mvi e,0 ; Counter lxi h,opers ; Operator pointer opscan: mov a,m ; Check against character cmp d ; Found it? jz opfind inr e ; Increment counter ana a ; Otherwise, is it zero? inx h jnz opscan ; If not, keep scanning eparse: lxi d,pserr ; It is zero - print a parse error mvi c,puts call 5 pop d mvi c,puts call 5 rst 0 opfind: cpi '=' ; Special case - is it '='? jnz opfin2 ; If so it should be followed by '>' xthl inx h mov a,m xthl cpi '>' jnz eparse ; '=' not part of '=>' is parse error opfin2: mvi d,0 ; Look up the precedence for this operator lxi h,prec dad d mov d,m ; Store it in D (D=prec E=operator number) pop h ; Restore input string xthl ; Get operator stack pointer oppop: mov a,l ; At beginning of operator stack? ana a jz oppush ; Then done - push current operator dcx h ; Check what's on top mov a,m inx h cpi TPAR ; Parenthesis? jz oppush ; Then done - push current operator push b ; Store output pointer for a while push h ; As well as operator stack pointer mvi b,0 ; Get index of operator from stack ani TMASK mov c,a lxi h,prec ; Find precedence dad b mov a,m ; Load precedence into A pop h ; Restore operator stack pointer pop b ; As well as output pointer cmp d ; Compare to operator from input jc oppush ; If input precedence higher, then push operator dcx h ; Otherwise, pop from operator stack, mov a,m stax b ; And store in output queue inx b jmp oppop ; Keep popping from operator stack oppush: mov a,e ; Get input operator ori TOP mov m,a ; Store on operator stack inx h xthl ; Switch to input string jmp parse emiss: lxi d,missp ; Error message for missing parentheses mvi c,puts call 5 rst 0 pdone: pop h ; Get operator stack pointer ppop: mov a,l ; Pop whatever is left off ana a jz cntvar dcx h mov a,m ; Get value cpi TPAR ; If we find a paranthesis then the parentheses jz emiss ; don't match stax b ; Store in output queue inx b jmp ppop cntvar: stax b ; Zero-terminate the expression lxi h,vused+25 ; See which variables are used in the expr xra a vzero: mov m,a dcr l jp vzero lxi d,expr vscan: ldax d ; Load expression element inx d ; Next one next time ana a ; Was it zero? jz vdone ; Then we're done mov b,a ; Store copy ani TTYPE ; Is it a variable? cpi TVAR jnz vscan ; If not, ignore it mov a,b ani TMASK mov l,a ; If so, mark it inr m jmp vscan vdone: call eval ; Run the evaluation once to catch errors lxi h,vused ; Print header mvi b,0 ; Character counter varhdr: mov a,m ; Current variable used? ana a jz varnxt ; If not, skip it inr b ; Two characters inr b push h ; Keep registers push b mvi c,putch ; Print letter mov a,l adi 'A' mov e,a call 5 mvi c,putch ; Print space mvi e,' ' call 5 pop b ; Restore registers pop h varnxt: inr l mov a,l cpi 26 jnz varhdr inr b ; Two characters for "| " inr b push b lxi d,dvdr mvi c,puts call 5 pop b lxi h,81h ; Print expression exhdr: inr b ; One character push b push h mov e,m mvi c,putch call 5 pop h pop b mov a,m ; Until zero reached ana a inx h jnz exhdr push b ; Keep count lxi d,nwln ; Print newline mvi c,puts call 5 pop b linhdr: push b ; Print dashes mvi c,putch mvi e,'-' call 5 pop b dcr b jnz linhdr lxi h,vars ; Set all variables to 0 xra a zero: mov m,a inr l jnz zero mloop: lxi d,nwln ; Print newline mvi c,puts call 5 lxi h,vars ; Print current state lxi d,vused lxi b,1A00h pstate: ldax d ; Is variable in use? ana a jz pnext ; If not, try next one mov c,e ; Keep highest used variable mov a,m ; Otherwise, get value ani 1 ; 0 or 1 ori '0' push b ; Keep state push d push h mvi c,putch ; Print variable mov e,a call 5 mvi c,putch ; And space mvi e,' ' call 5 pop h ; Restore state pop d pop b pnext: inx h ; Print next one inx d dcr b jnz pstate push b ; Keep last variable lxi d,dvdr ; Print "| " mvi c,puts call 5 call eval ; Evaluate expr using current state ani 1 ; Print result ori '0' mvi c,putch mov e,a call 5 pop b ; Restore last used variable inr c lxi h,vars ; Find next state lxi d,vused istate: ldax d ; Is variable in use? ana a jz inext ; If not, try next one mov a,m ; Otherwise, get value ana a ; Is it zero? jnz iinc ; If not, keep going, inr m ; But if so, set it to one jmp mloop ; And print next state iinc: dcr m ; If one, set it to zero inext: inx d ; And try next variable inx h dcr c ; Test if we have variables left jnz istate ; If not, try next one rst 0 ; But if so, we're done eval: lxi b,expr ; Evaluate the expression lxi h,opstk ; Evaluation stack eloop: ldax b ; Load expression element inx b ana a ; Done? jz edone mov d,a ; Keep copy ani TTYPE cpi TCONST ; Constant? jz econst cpi TVAR ; Variable? jz evar mov a,d ; Otherwise it's an operator ani TMASK mov d,a ana a ; Not? jnz e2 dcr l ; Error if stack empty jm errop mov a,m ; Not cma mov m,a inr l jmp eloop e2: dcr l ; 2 values needed - error if stack empty mov e,m ; Right hand value dcr l mov a,m ; Left hand value jm errop dcr d ; And? jz eand dcr d ; Or? jz eor dcr d ; Xor? jz exor eimpl: ana a ; Implies - if A=1 then E else 1 jnz e_lde mvi m,-1 inr l jmp eloop e_lde: mov m,e inr l jmp eloop exor: xra e jmp estore eor: ora e jmp estore eand: ana e estore: mov m,a inr l jmp eloop econst: mov a,d ; Constant ani TMASK mov m,a inr l jmp eloop evar: mov a,d ; Variable ani TMASK push h mvi h,vars/256 mov l,a mov a,m pop h mov m,a inr l jmp eloop edone: dcr l ; Should be at 0 mov a,m rz lxi d,mop ; Missing operator (not all values used) jmp errop+3 errop: lxi d,mval ; Missing operand (stack underflow) mvi c,puts call 5 rst 0 nwln: db 13,10,'$' dvdr: db '| $' noarg: db 'Please enter a boolean expression on the command line.$' missp: db 'Missing parenthesis.$' pserr: db 'Parse error at: $' mval: db 'Missing operand.$' mop: db 'Missing operator.$' opers: db '~&|^=',0 ; Operators - note that impl is actually => prec: db 4,3,2,2,1 ; Precedence opstk: equ ($/256)*256+256 ; Operator stack (for shunting yard) vars: equ opstk+256 ; Space for variables vused: equ vars+256 ; Marks which variables are used expr: equ vused+26 ; Parsed expression is stored here
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
#Common_Lisp
Common Lisp
  (defun ulam-spiral (n) (loop for a in (spiral n n (* n n)) do (format t "~{~d~}~%" a)))   (defun spiral (n m b &aux (row (loop for a below n collect (if (primep (- b a)) '* '#\space)))) (if (= m 1) (list row) (cons row (mapcar #'reverse (apply #'mapcar #'list (spiral (1- m) n (- b n))))))) (defun primep (n) (when (> n 1) (loop for a from 2 to (isqrt n) never (zerop (mod n a)))))  
http://rosettacode.org/wiki/Two_bullet_roulette
Two bullet roulette
The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street: A revolver handgun has a revolving cylinder with six chambers for bullets. It is loaded with the following procedure: 1. Check the first chamber to the right of the trigger for a bullet. If a bullet is seen, the cylinder is rotated one chamber clockwise and the next chamber checked until an empty chamber is found. 2. A cartridge containing a bullet is placed in the empty chamber. 3. The cylinder is then rotated one chamber clockwise. To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take a random position from 1 to 6 chamber rotations clockwise from its starting position. When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just counterclockwise from the loading position. The gun is unloaded by removing all cartridges from the cylinder. According to the legend, a suicidal Russian imperial military officer plays a game of Russian roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice. If the gun fires with a trigger pull, this is considered a successful suicide. The cylinder is always spun before the first shot, but it may or may not be spun after putting in the first bullet and may or may not be spun after taking the first shot. Which of the following situations produces the highest probability of suicide? A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot. B. Spinning the cylinder after loading the first bullet only. C. Spinning the cylinder after firing the first shot only. D. Not spinning the cylinder either after loading the first bullet or after the first shot. E. The probability is the same for all cases. Task Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios. Show the results as a percentage of deaths for each type of scenario. The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question. Reference Youtube video on the Russian 1895 Nagant revolver [[1]]
#Wren
Wren
import "random" for Random import "/fmt" for Fmt   var Rand = Random.new()   class Revolver { construct new() { _cylinder = List.filled(6, false) }   rshift() { var t = _cylinder[-1] for (i in 4..0) _cylinder[i+1] = _cylinder[i] _cylinder[0] = t }   unload() { for (i in 0..5) _cylinder[i] = false }   load() { while (_cylinder[0]) rshift() _cylinder[0] = true rshift() }   spin() { for (i in 1..Rand.int(1, 7)) rshift() }   fire() { var shot = _cylinder[0] rshift() return shot }   method(s) { unload() for (c in s) { if (c == "L") { load() } else if (c == "S") { spin() } else if (c == "F") { if (fire()) return 1 } } return 0 }   static mstring(s) { var l = [] for (c in s) { if (c == "L") { l.add("load") } else if (c == "S") { l.add("spin") } else if (c == "F") { l.add("fire") } } return l.join(", ") } }   var rev = Revolver.new() var tests = 100000 for (m in ["LSLSFSF", "LSLSFF", "LLSFSF", "LLSFF"]) { var sum = 0 for (t in 1..tests) sum = sum + rev.method(m) Fmt.print("$-40s produces $6.3f\% deaths.", Revolver.mstring(m), sum * 100 / tests) }
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Ruby
Ruby
  Dir.foreach("./"){|n| puts n}  
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Run_BASIC
Run BASIC
files #f, DefaultDir$ + "\*.*" ' RunBasic Default directory.. Can be any directroy print "rowcount: ";#f ROWCOUNT() ' how many rows in directory #f DATEFORMAT("mm/dd/yy") 'set format of file date or not #f TIMEFORMAT("hh:mm:ss") 'set format of file time or not count = #f rowcount() for i = 1 to count ' loop thru the row count print "info: ";#f nextfile$() ' file info print "name: ";#f NAME$() ' Name of file print "size: ";#f SIZE() ' size print "date: ";#f DATE$() ' date print "time: ";#f TIME$() ' time print "isdir: ";#f ISDIR() ' 1 = is a directory next
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Rust
Rust
use std::{env, fmt, fs, process}; use std::io::{self, Write}; use std::path::Path;   fn main() { let cur = env::current_dir().unwrap_or_else(|e| exit_err(e, 1)); let arg = env::args().nth(1); print_files(arg.as_ref().map_or(cur.as_path(), |p| Path::new(p))) .unwrap_or_else(|e| exit_err(e, 2)); }   #[inline] fn print_files(path: &Path) -> io::Result<()> { for x in try!(fs::read_dir(path)) { println!("{}", try!(x).file_name().to_string_lossy()); } Ok(()) }   #[inline] fn exit_err<T>(msg: T, code: i32) -> ! where T: fmt::Display { writeln!(&mut io::stderr(), "{}", msg).expect("Could not write to stderr"); process::exit(code) }
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
#Visual_Basic_.NET
Visual Basic .NET
Public Class Vector3D Private _x, _y, _z As Double   Public Sub New(ByVal X As Double, ByVal Y As Double, ByVal Z As Double) _x = X _y = Y _z = Z End Sub   Public Property X() As Double Get Return _x End Get Set(ByVal value As Double) _x = value End Set End Property   Public Property Y() As Double Get Return _y End Get Set(ByVal value As Double) _y = value End Set End Property   Public Property Z() As Double Get Return _z End Get Set(ByVal value As Double) _z = value End Set End Property   Public Function Dot(ByVal v2 As Vector3D) As Double Return (X * v2.X) + (Y * v2.Y) + (Z * v2.Z) End Function   Public Function Cross(ByVal v2 As Vector3D) As Vector3D Return New Vector3D((Y * v2.Z) - (Z * v2.Y), _ (Z * v2.X) - (X * v2.Z), _ (X * v2.Y) - (Y * v2.X)) End Function   Public Function ScalarTriple(ByVal v2 As Vector3D, ByVal v3 As Vector3D) As Double Return Me.Dot(v2.Cross(v3)) End Function   Public Function VectorTriple(ByRef v2 As Vector3D, ByVal v3 As Vector3D) As Vector3D Return Me.Cross(v2.Cross(v3)) End Function   Public Overrides Function ToString() As String Return String.Format("({0}, {1}, {2})", _x, _y, _z) End Function End Class
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Wren
Wren
var f = Fn.new { System.print("'f' called.") // note no return value }   var res = f.call() System.print("The value returned by 'f' is %(res).")   var m = {} // empty map System.print("m[1] is %(m[1]).")   var u // declared but not assigned a value System.print("u is %(u).")   var v = null // explicitly assigned null if (!v) System.print("v is %(v).")
http://rosettacode.org/wiki/Undefined_values
Undefined values
#zkl
zkl
println(Void); 1+Void if(Void){} else { 23 }
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#Stata
Stata
@{TITLE /[あ-ん一-耙]+/} (@ROMAJI/@ENGLISH) @(freeform) @(coll)@{STANZA /[^\n\x3000 ]+/}@(end)@/.*/  
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#Tcl
Tcl
@{TITLE /[あ-ん一-耙]+/} (@ROMAJI/@ENGLISH) @(freeform) @(coll)@{STANZA /[^\n\x3000 ]+/}@(end)@/.*/  
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#TXR
TXR
@{TITLE /[あ-ん一-耙]+/} (@ROMAJI/@ENGLISH) @(freeform) @(coll)@{STANZA /[^\n\x3000 ]+/}@(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.
#Kotlin
Kotlin
import java.math.BigInteger import java.util.*   fun main() { val input = Scanner(System.`in`) println("Search Size: ") val max = input.nextBigInteger() var counter = 0 var x = BigInteger("3") while (x <= max) { val sqrtNum = x.sqrt().add(BigInteger.ONE) if (x.add(BigInteger.TWO) <= max) { counter += if (findPrime( x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE) ) && findPrime(x, sqrtNum) ) 1 else 0 } x = x.add(BigInteger.ONE) } println("$counter twin prime pairs.") }   fun findPrime(x: BigInteger, sqrtNum: BigInteger?): Boolean { var divisor = BigInteger.TWO while (divisor <= sqrtNum) { if (x.remainder(divisor).compareTo(BigInteger.ZERO) == 0) { return false } divisor = divisor.add(BigInteger.ONE) } return true }
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)
#Phix
Phix
with javascript_semantics printf(1,"The first 35 unprimeable numbers are:\n") integer count := 0, -- counts all unprimeable numbers countFirst = 0, i = 100 sequence firstNum = repeat(0,10) -- stores the first unprimeable number ending with each digit atom t0 = time(), t1=t0+1 while countFirst<10 do if not is_prime(i) then -- unprimeable number must be composite string s = sprintf("%d",i), b = s integer le := length(s) bool primeable = false for j=1 to le do for k='0' to '9' do if s[j]!=k then b[j] = k integer n = to_integer(b) if is_prime(n) then primeable = true exit end if end if end for if primeable then exit end if b[j] = s[j] -- restore j'th digit to what it was originally end for if not primeable then integer lastDigit = s[le]-'0'+1 if firstNum[lastDigit] == 0 then firstNum[lastDigit] = i countFirst += 1 end if count += 1 if count <= 35 then printf(1,"%d ", i) elsif count == 600 then printf(1,"\n\nThe 600th unprimeable number is: %,d\n\n",i) end if end if end if if platform()!=JS and time()>t1 then printf(1,"checking %d, %d `endswiths` found\r",{i,countFirst}) t1 = time()+1 end if i += 1 end while printf(1,"The first unprimeable number that ends in:\n") for i=1 to 10 do printf(1,"  %d is: %,9d\n", {i-1, firstNum[i]}) end for ?elapsed(time()-t0)
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.
#PARI.2FGP
PARI/GP
randN(N)=!random(N); unbiased(N)={ my(a,b); while(1, a=randN(N); b=randN(N); if(a!=b, return(a)) ) }; for(n=3,6,print(n"\t"sum(k=1,1e5,unbiased(n))"\t"sum(k=1,1e5,randN(n))))
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.
#Perl
Perl
sub randn { my $n = shift; return int(rand($n) / ($n - 1)); }   for my $n (3 .. 6) { print "Bias $n: "; my (@raw, @fixed); for (1 .. 10000) { my $x = randn($n); $raw[$x]++; $fixed[$x]++ if randn($n) != $x } print "@raw, "; printf("%3g+-%.3g%%\tfixed: ", $raw[0]/100, 100 * sqrt($raw[0] * $raw[1]) / ($raw[0] + $raw[1])**1.5); print "@fixed, "; printf("%3g+-%.3g%%\n", 100*$fixed[0]/($fixed[0] + $fixed[1]), 100 * sqrt($fixed[0] * $fixed[1]) / ($fixed[0] + $fixed[1])**1.5);   }
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.
#Delphi
Delphi
procedure TruncateFile(FileName : string; NewSize : integer); var aFile: file of byte; begin Assign(aFile, FileName); Reset(aFile); try Seek(afile, NewSize); Truncate(aFile); finally Close(afile); end; end;
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#Elena
Elena
import system'io; import extensions;   extension fileOp : File { set Length(int len) { auto stream := FileStream.openForEdit(self);   stream.Length := len;   stream.close() } }   public program() { if (program_arguments.Length != 3) { console.printLine:"Please provide the path to the file and a new length"; AbortException.raise() };   auto file := File.assign(program_arguments[1]); var length := program_arguments[2].toInt();   ifnot(file.Available) { console.printLine("File ",file," does not exist"); AbortException.raise() };   file.Length := length }
http://rosettacode.org/wiki/Twelve_statements
Twelve statements
This puzzle is borrowed from   math-frolic.blogspot. Given the following twelve statements, which of them are true? 1. This is a numbered list of twelve statements. 2. Exactly 3 of the last 6 statements are true. 3. Exactly 2 of the even-numbered statements are true. 4. If statement 5 is true, then statements 6 and 7 are both true. 5. The 3 preceding statements are all false. 6. Exactly 4 of the odd-numbered statements are true. 7. Either statement 2 or 3 is true, but not both. 8. If statement 7 is true, then 5 and 6 are both true. 9. Exactly 3 of the first 6 statements are true. 10. The next two statements are both true. 11. Exactly 1 of statements 7, 8 and 9 are true. 12. Exactly 4 of the preceding statements are true. Task When you get tired of trying to figure it out in your head, write a program to solve it, and print the correct answer or answers. Extra credit Print out a table of near misses, that is, solutions that are contradicted by only a single statement.
#Ada
Ada
with Ada.Text_IO, Logic;   procedure Twelve_Statements is   package L is new Logic(Number_Of_Statements => 12); use L;   -- formally define the 12 statements as expression function predicates function P01(T: Table) return Boolean is (T'Length = 12); -- list of 12 statements function P02(T: Table) return Boolean is (Sum(T(7 .. 12)) = 3); -- three of last six function P03(T: Table) return Boolean is (Sum(Half(T, Even)) = 2); -- two of the even function P04(T: Table) return Boolean is (if T(5) then T(6) and T(7)); -- if 5 is true, then ... function P05(T: Table) return Boolean is ( (not T(2)) and (not T(3)) and (not T(4)) ); -- none of preceding three function P06(T: Table) return Boolean is (Sum(Half(T, Odd)) = 4); -- four of the odd function P07(T: Table) return Boolean is (T(2) xor T(3)); -- either 2 or 3, not both function P08(T: Table) return Boolean is (if T(7) then T(5) and T(6)); -- if 7 is true, then ... function P09(T: Table) return Boolean is (Sum(T(1 .. 6)) = 3); -- three of first six function P10(T: Table) return Boolean is (T(11) and T(12)); -- next two function P11(T: Table) return Boolean is (Sum(T(7..9)) = 1); -- one of 7, 8, 9 function P12(T: Table) return Boolean is (Sum(T(1 .. 11)) = 4); -- four of the preding   -- define a global list of statements Statement_List: constant Statements := (P01'Access, P02'Access, P03'Access, P04'Access, P05'Access, P06'Access, P07'Access, P08'Access, P09'Access, P10'Access, P11'Access, P12'Access);   -- try out all 2^12 possible choices for the table procedure Try(T: Table; Fail: Natural; Idx: Indices'Base := Indices'First) is   procedure Print_Table(T: Table) is use Ada.Text_IO; begin Put(" "); if Fail > 0 then Put("(wrong at"); for J in T'Range loop if Statement_List(J)(T) /= T(J) then Put(Integer'Image(J) & (if J < 10 then ") " else ") ")); end if; end loop; end if; if T = (1..12 => False) then Put_Line("All false!"); else Put("True are"); for J in T'Range loop if T(J) then Put(Integer'Image(J)); end if; end loop; New_Line; end if; end Print_Table;   Wrong_Entries: Natural := 0;   begin if Idx <= T'Last then Try(T(T'First .. Idx-1) & False & T(Idx+1 .. T'Last), Fail, Idx+1); Try(T(T'First .. Idx-1) & True & T(Idx+1 .. T'Last), Fail, Idx+1); else -- now Index > T'Last and we have one of the 2^12 choices to test for J in T'Range loop if Statement_List(J)(T) /= T(J) then Wrong_Entries := Wrong_Entries + 1; end if; end loop; if Wrong_Entries = Fail then Print_Table(T); end if; end if; end Try;   begin Ada.Text_IO.Put_Line("Exact hits:"); Try(T => (1..12 => False), Fail => 0); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line("Near Misses:"); Try(T => (1..12 => False), Fail => 1); end Twelve_Statements;
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.
#ALGOL_68
ALGOL 68
# prints the truth table of a boolean expression composed of the 26 lowercase variables a..z, # # the boolean operators AND, OR, XOR and NOT and the literal values TRUE and FALSE # # The evaluation is done with the Algol 68G evaluate function which is an extension # PROC print truth table = ( STRING expr )VOID: BEGIN   # recursively prints the truth table # PROC print line = ( INT v )VOID: IF v > UPB bv THEN # at the end of the variables - print the line # FOR e TO UPB bv DO IF used[ e ] THEN print( ( " ", bv[ e ], " " ) ) FI OD; print( ( " ", evaluate( expr ), newline ) ) ELIF used[ v ] THEN # have another variable # bv[ v ] := TRUE; print line( v + 1 ); bv[ v ] := FALSE; print line( v + 1 ) ELSE # this variable is not used # print line( v + 1 ) FI # print line # ;   # returns the name of the variable number # PROC variable name = ( INT number )CHAR: REPR ( number + ( ABS "a" - 1 ) );   # the 26 boolean variables # BOOL a := FALSE, b := FALSE, c := FALSE, d := FALSE, e := FALSE, f := FALSE; BOOL g := FALSE, h := FALSE, i := FALSE, j := FALSE, k := FALSE, l := FALSE; BOOL m := FALSE, n := FALSE, o := FALSE, p := FALSE, q := FALSE, r := FALSE; BOOL s := FALSE, t := FALSE, u := FALSE, v := FALSE, w := FALSE, x := FALSE; BOOL y := FALSE, z := FALSE; # table of the variables allowng access by number # []REF BOOL bv = ( a, b, c, d, e, f, g, h, i, j, k, l, m , n, o, p, q, r, s, t, u, v, w, x, y, z ); [ 26 ]BOOL used; BOOL at least one variable := FALSE; # determine which variables are used in the expression # FOR v TO UPB bv DO used[ v ] := char in string( variable name( v ), NIL, expr ); IF used[ v ]THEN at least one variable := TRUE FI OD; # print truth table headings # print( ( expr, ":", newline ) ); FOR v TO UPB bv DO IF used[ v ] THEN print( ( " ", variable name( v ), " " ) ) FI OD; print( ( " value", newline ) ); FOR v TO UPB bv DO IF used[ v ] THEN print( ( " - " ) ) FI OD; print( ( " -----", newline ) ); # evaluate the expression for each cobination of variables # IF at least one variable THEN # the expression does not consist of literals only # FOR v TO UPB bv DO bv[ v ] := FALSE OD; print line( LWB bv ) ELSE # the expression is constant # print( ( " ", evaluate( expr ), newline ) ) FI END # print truth table # ;   # print truth tables from the user's expressions # print( ( "Please enter Boolean expressions using variables a, b, c, ..., z,", newline ) ); print( ( "operators AND, OR, NOT and XOR and literals TRUE and FALSE", newline ) ); print( ( "(Note operators and TRUE/FALSE must be uppercase and variables must be lower case)", newline ) ); print( ( "Enter a blank line to quit", newline ) ); WHILE STRING expr; print( ( "expression> " ) ); read( ( expr, newline ) ); expr /= "" DO print truth table( expr ) OD
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
#Crystal
Crystal
enum Direction RIGHT UP LEFT DOWN end   def generate(n : Int32, i : Int32, c : Int32 | String) s = Array.new(n) { Array.new(n) { "" } }   dir = Direction::RIGHT y = n // 2 x = n % 2 == 0 ? y - 1 : y   j = 1 while j <= n * n - 1 + i s[y][x] = is_prime(j) ? j.to_s : c.to_s   # printf "j: %s, x: %s, y: %s \n", j, x, y   case dir when Direction::RIGHT dir = Direction::UP if x <= n - 1 && s[y - 1][x] == "" && j > i when Direction::UP dir = Direction::LEFT if s[y][x - 1] == "" when Direction::LEFT dir = Direction::DOWN if x == 0 || s[y + 1][x] == "" when Direction::DOWN dir = Direction::RIGHT if s[y][x + 1] == "" end   case dir when Direction::RIGHT x += 1 when Direction::UP y -= 1 when Direction::LEFT x -= 1 when Direction::DOWN y += 1 end   j += 1 end   s.map(&.join("\t")).join("\n") end   def is_prime(n : Int32) : Bool return true if n == 2 return false if n % 2 == 0 || n < 1   i = 3 while i <= Math.sqrt(n) return false if n % i == 0 i += 2 end   true end   puts generate 7, 1, "*"  
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#S-lang
S-lang
variable d = listdir(getcwd()), p; foreach p (array_sort(d)) () = printf("%s\n", d[p] );
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Scala
Scala
scala> new java.io.File("/").listFiles.sorted.foreach(println) /bin /boot /core /dev /etc /home /lib /lib64 /local /lost+found /media /mnt /opt /proc /root /run /sbin /selinux /srv /sys /tmp /user /usr /var
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Seed7
Seed7
$ include "seed7_05.s7i"; include "osfiles.s7i";   const proc: main is func local var string: name is ""; begin for name range readDir(".") do writeln(name); end for; end func;
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
#Vlang
Vlang
struct Vector { x f64 y f64 z f64 }   const ( a = Vector{3, 4, 5} b = Vector{4, 3, 5} c = Vector{-5, -12, -13} )   fn dot(a Vector, b Vector) f64 { return a.x*b.x + a.y*b.y + a.z*b.z }   fn cross(a Vector, b Vector) Vector { return Vector{a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x} }   fn s3(a Vector, b Vector, c Vector) f64 { return dot(a, cross(b, c)) }   fn v3(a Vector, b Vector, c Vector) Vector { return cross(a, cross(b, c)) }   fn main() { println(dot(a, b)) println(cross(a, b)) println(s3(a, b, c)) println(v3(a, b, c)) }
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#UNIX_Shell
UNIX Shell
stdout.printf ("UTF-8 encoded string. Let's go to a café!");
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#Vala
Vala
stdout.printf ("UTF-8 encoded string. Let's go to a café!");
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Sub Main() Console.OutputEncoding = Text.Encoding.Unicode   ' normal identifiers allowed Dim a = 0 ' unicode characters allowed Dim δ = 1   ' ascii strings Console.WriteLine("some text") ' unicode strings strings Console.WriteLine("こんにちは") Console.WriteLine("Здравствуйте") Console.WriteLine("שלום") ' escape sequences Console.WriteLine(vbTab + "text" + vbTab + ChrW(&H2708) + """blue") Console.ReadLine() End Sub   End Module
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[TwinPrimeCount] TwinPrimeCount[mx_] := Module[{pmax, min, max, total}, pmax = PrimePi[mx]; total = 0; Do[ min = 10^6 i; min = Max[min, 1]; max = 10^6 (i + 1); max = Min[max, pmax]; total += Count[Differences[Prime[Range[min, max]]], 2] , {i, 0, Ceiling[pmax/10^6]} ]; total ] Do[Print[{10^i, TwinPrimeCount[10^i]}], {i, 9}]
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.
#Nim
Nim
import math, strformat, strutils   const N = 1_000_000_000   proc sieve(n: Positive): seq[bool] = ## Build and fill a sieve of Erathosthenes. result.setLen(n + 1) # Default to false which means prime. result[0] = true result[1] = true for n in countup(3, sqrt(N.toFloat).int, 2): if not result[n]: for k in countup(n * n, N, 2 * n): result[k] = true   let composite = sieve(N)   proc findTwins(composite: openArray[bool]) = var lim = 10 count = 1 # Start with 3, 5 which is a special case. n = 7 # First prime congruent to 1 modulo 3. while true: if not composite[n] and not composite[n - 2]: inc count inc n, 6 # Next odd number congruent to 1 modulo 3. if n > lim: echo &"There are {insertSep($count)} pairs of twin primes under {insertSep($lim)}." lim *= 10 if lim > N: break   composite.findTwins()
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.
#Perl
Perl
use strict; use warnings;   use Primesieve;   sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }   printf "Twin prime pairs less than %14s: %s\n", comma(10**$_), comma count_twins(1, 10**$_) for 1..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)
#Pike
Pike
  bool is_unprimeable(int i) { string s = i->digits(); for(int offset; offset < sizeof(s); offset++) { foreach("0123456789"/1, string repl) { array chars = s/1; chars[offset] = repl; int testme = (int)(chars*""); if( testme->probably_prime_p() ) return false; } } return true; }   void main() { int i, count; array unprimes = ({}); mapping first_enders = ([]); // first unprimeable ending with each digit while(sizeof(first_enders) != 10) { i++; if( is_unprimeable(i) ) { count++; unprimes += ({ i }); string last_digit = i->digits()[<0..]; if( !first_enders[last_digit] ) first_enders[last_digit] = i; } werror("%d\r", i); // Progress output }   write("First 35 unprimeables: %s\n\n", (array(string))unprimes[0..34]*" "); write("The 600th unprimeable is %d\n\n", unprimes[599]); write("The first unprimeable number that ends in\n"); foreach(sort(indices(first_enders)), string e) { write("  %s is: %9d\n", e, first_enders[e]); } }
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.
#Phix
Phix
with javascript_semantics function randN(integer N) return rand(N) = 1 end function function unbiased(integer N) while true do integer a = randN(N) if a!=randN(N) then return a end if end while end function constant n = 100000 for b=3 to 6 do integer cb = 0, cu = 0 for i=1 to n do cb += randN(b) cu += unbiased(b) end for printf(1, "%d: biased:%.0f%% unbiased:%.0f%%\n", {b,(cb/n)*100,(cu/n)*100}) end for
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.
#Erlang
Erlang
  -module( truncate ).   -export( [file/2] ).   file( Name, Size ) -> {file_exists, true} = {file_exists, filelib:is_file( Name )}, {ok, IO} = file:open( Name, [read, write] ), {ok, Max} = file:position( IO, eof ), {correct_size, true} = {correct_size, (Size < Max)}, {ok, Size} = file:position( IO, {bof, Size} ), ok = file:truncate( IO ).  
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.
#F.23
F#
open System open System.IO   let truncateFile path length = if not (File.Exists(path)) then failwith ("File not found: " + path) use fileStream = new FileStream(path, FileMode.Open, FileAccess.Write) if (fileStream.Length < length) then failwith "The specified length is greater than the current file length." fileStream.SetLength(length)   [<EntryPoint>] let main args = truncateFile args.[0] (Int64.Parse(args.[1])) 0
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.
#ALGOL_W
ALGOL W
begin  % we have 12 statements to determine the truth/falsehood of (see task)  %   logical array stmt, expected( 1 :: 12 );    % logical (boolean) to integer utility procedure  % integer procedure toInteger ( logical value v ) ; if v then 1 else 0;    % procedure to determine whether the statements are true or not  % procedure findExpectedValues ; begin expected( 1 ) := true; expected( 2 ) := 3 = ( toInteger( stmt( 7 ) ) + toInteger( stmt( 8 ) ) + toInteger( stmt( 9 ) ) + toInteger( stmt( 10 ) ) + toInteger( stmt( 11 ) ) + toInteger( stmt( 12 ) ) ); expected( 3 ) := 2 = ( toInteger( stmt( 2 ) ) + toInteger( stmt( 4 ) ) + toInteger( stmt( 6 ) ) + toInteger( stmt( 8 ) ) + toInteger( stmt( 10 ) ) + toInteger( stmt( 12 ) ) ); expected( 4 ) := ( not stmt( 5 ) ) or ( stmt( 6 ) and stmt( 7 ) ); expected( 5 ) := not ( stmt( 2 ) or stmt( 3 ) or stmt( 4 ) ); expected( 6 ) := 4 = ( toInteger( stmt( 1 ) ) + toInteger( stmt( 3 ) ) + toInteger( stmt( 5 ) ) + toInteger( stmt( 7 ) ) + toInteger( stmt( 9 ) ) + toInteger( stmt( 11 ) ) ); expected( 7 ) := stmt( 2 ) not = stmt( 3 ); expected( 8 ) := ( not stmt( 7 ) ) or ( stmt( 5 ) and stmt( 6 ) ); expected( 9 ) := 3 = ( toInteger( stmt( 1 ) ) + toInteger( stmt( 2 ) ) + toInteger( stmt( 3 ) ) + toInteger( stmt( 4 ) ) + toInteger( stmt( 5 ) ) + toInteger( stmt( 6 ) ) ); expected( 10 ) := stmt( 11 ) and stmt( 12 ); expected( 11 ) := 1 = ( toInteger( stmt( 7 ) ) + toInteger( stmt( 8 ) ) + toInteger( stmt( 9 ) ) ); expected( 12 ) := 4 = ( toInteger( stmt( 1 ) ) + toInteger( stmt( 2 ) ) + toInteger( stmt( 3 ) ) + toInteger( stmt( 4 ) ) + toInteger( stmt( 5 ) ) + toInteger( stmt( 6 ) ) + toInteger( stmt( 7 ) ) + toInteger( stmt( 8 ) ) + toInteger( stmt( 9 ) ) + toInteger( stmt( 10 ) ) + toInteger( stmt( 11 ) ) ); end expected ;    % clearly, statement 1 is true, however to enumerate the near  %  % solutions, we need to consider "solutions" where statement 1 is false %  % we iterate through the possibilities for the statements,  %  % looking for a non-contradictory set of values  %  % we print the solutions with allowedContradictions contradictions  % procedure printSolutions ( integer value allowedContradictions  ; string(60) value heading ) ; begin logical array wrong( 1 :: 12 ); write( heading ); write( " 1 2 3 4 5 6 7 8 9 10 11 12" ); write( " ====================================" );  % there are 12 statements, so we have 2^12 possible combinations  % for solution := 1 until 4096 do begin integer n, incorrect;  % convert the number to the set of true/false values  % n := solution; for dPos := 1 until 12 do begin stmt( dPos ) := odd( n ); n := n div 2; end for_dPos ;  % get the expected values of the statements, based on the  %  % suggested values  % findExpectedValues;  % count the contradictions, if we have the required number,  %  % print the solution  % incorrect := 0; for dPos := 1 until 12 do begin wrong( dPos ) := expected( dPos ) not = stmt( dPos ); incorrect  := incorrect + toInteger( wrong( dPos ) ); end for_dPos ; if incorrect = allowedContradictions then begin  % have a solution  % write( " " ); for s := 1 until 12 do writeon( s_w := 0 , " " , if stmt( s ) then "T" else "-" , if wrong( s ) then "*" else " " ); end ; end for_solution ; end printSolutions ;    % find complete solutions  % printSolutions( 0, "Solutions" );  % find near solutions  % printSolutions( 1, "Near solutions (incorrect values marked ""*"")" );   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.
#APL
APL
truth←{ op←⍉↑'~∧∨≠→('(4 3 2 2 1 0) order←⍬⍬{ out stk←⍺ 0=≢⍵:out,⌽stk c rst←(⊃⍵) (1↓⍵) c∊⎕A:((out,c)stk)∇rst c∊'01':((out,⍎c)stk)∇rst (c≠'(')∧(≢op)≥n←op[;1]⍳c:rst∇⍨out{ cnd←⌽∧\⌽(⍵≠'(')∧op[op[;1]⍳⍵;2]≥op[n;2] (⍺,⌽cnd/⍵)(((~cnd)/⍵),c) }stk c='(':(out(stk,c))∇rst c=')':rst∇⍨out{ ⍬≡par←⍸'('=⍵:'Missing ('⎕SIGNAL 11 n←⌈/par (⍺,n↓⍵)((n-1)↑⍵) }stk ('Invalid character ',c)⎕SIGNAL 11 }1(819⌶)⍵~4↑⎕TC '('∊order:'Missing )'⎕SIGNAL 11 nvar←≢vars←∪(order∊⎕A)/order eval←{ ⍺←⍬ 0=≢⍵:{ 1≠≢⍵:'Missing operator'⎕SIGNAL 11 ⋄ ⊃⍵ }⍺ c rst←(⊃⍵) (1↓⍵) c∊⎕A:(⍺⍺[vars⍳c],⍺)∇rst c∊0 1:(c,⍺)∇rst c='~':(⍺≠1 0↑⍨≢⍺)∇rst ⊣ 'Missing operand'⎕SIGNAL(0=≢⍺)/11 c∊op[;1]:({ 2>≢⍵:'Missing operand'⎕SIGNAL 11 c='→':(≥/2↑⍵),2↓⍵ ((⍎c)/2↑⍵),2↓⍵ }⍺)∇rst } _←(nvar/0) eval order confs←⍉(nvar/2)⊤¯1+⍳2*nvar tab←'FT│'[1+(confs,2),{⍵ eval order}¨↓confs] tab←↑,/ ' ',¨tab hdr←((∊,/(' ',¨vars),' '),[0.5]'─'),⍪'│┼' hdr←hdr,(' ',⍵,' '),[0.5]'─' hdr⍪(,∘' '⍣(⊃⊃-/1↓¨⍴¨hdr tab))tab }
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
#D
D
import std.stdio, std.math, std.algorithm, std.array, std.range;   int cell(in int n, int x, int y, in int start=1) pure nothrow @safe @nogc { x = x - (n - 1) / 2; y = y - n / 2; immutable l = 2 * max(x.abs, y.abs); immutable d = (y > x) ? (l * 3 + x + y) : (l - x - y); return (l - 1) ^^ 2 + d + start - 1; }   void showSpiral(in int n, in string symbol="# ", in int start=1, string space=null) /*@safe*/ { if (space is null) space = " ".replicate(symbol.length);   immutable top = start + n ^^ 2 + 1; auto isPrime = [false, false, true] ~ [true, false].replicate(top / 2); foreach (immutable x; 3 .. 1 + cast(int)real(top).sqrt) { if (!isPrime[x]) continue; foreach (immutable i; iota(x ^^ 2, top, x * 2)) isPrime[i] = false; }   string cellStr(in int x) pure nothrow @safe @nogc { return isPrime[x] ? symbol : space; }   foreach (immutable y; 0 .. n) n.iota.map!(x => cell(n, x, y, start)).map!cellStr.joiner.writeln; }   void main() { 35.showSpiral; }
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Sidef
Sidef
var content = []; Dir.cwd.open.each { |file| file ~~ < . .. > && next; content.append(file); }   content.sort.each { |file| say file; }
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Smalltalk
Smalltalk
Stdout printCR: ( PipeStream outputFromCommand:'ls' )
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
#Wortel
Wortel
@let { dot &[a b] @sum @mapm ^* [a b] cross &[a b] [[ -*a.1 b.2 *a.2 b.1 -*a.2 b.0 *a.0 b.2 -*a.0 b.1 *a.1 b.0 ]] scalarTripleProduct &[a b c] !!dot a !!cross b c vectorTripleProduct &[a b c] !!cross a !!cross b c   a [3 4 5] b [4 3 5] c [5N 12N 13N]   [[  !!dot a b  !!cross a b @!scalarTripleProduct [a b c] @!vectorTripleProduct [a b c] ]] }
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#WDTE
WDTE
let プリント t => io.writeln io.stdout t;   プリント 'これは実験です。';
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#Wren
Wren
var w = "voilà" for (c in w) { System.write("%(c) ") // prints the 5 Unicode 'characters'. } System.print("\nThe length of %(w) is %(w.count)")     System.print("\nIts code-points are:") for (cp in w.codePoints) { System.write("%(cp) ") // prints the code-points as numbers }   System.print("\n\nIts bytes are: ") for (b in w.bytes) { System.write("%(b) ") // prints the bytes as numbers }   var zwe = "👨‍👩‍👧" System.print("\n\n%(zwe) has:") System.print("  %(zwe.bytes.count) bytes: %(zwe.bytes.toList.join(" "))") System.print("  %(zwe.codePoints.count) code-points: %(zwe.codePoints.toList.join(" "))") System.print("  %(Graphemes.clusterCount(zwe)) grapheme")
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.
#Phix
Phix
with javascript_semantics atom t0 = time() function twin_primes(integer maxp, bool both=true) integer n = 0, -- result pn = 2, -- next prime index p, -- a prime, <= maxp prev_p = 2 while true do p = get_prime(pn) if both and p>=maxp then exit end if n += (prev_p = p-2) if (not both) and p>=maxp then exit end if prev_p = p pn += 1 end while return n end function integer mp = 6 -- prompt_number("Enter limit:") printf(1,"Twin prime pairs less than %,d: %,d\n",{mp,twin_primes(mp)}) printf(1,"Twin prime pairs less than %,d: %,d\n",{mp,twin_primes(mp,false)}) for p=1 to 9 do integer p10 = power(10,p) printf(1,"Twin prime pairs less than %,d: %,d\n",{p10,twin_primes(p10)}) end for ?elapsed(time()-t0)
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)
#Python
Python
from itertools import count, islice   def primes(_cache=[2, 3]): yield from _cache for n in count(_cache[-1]+2, 2): if isprime(n): _cache.append(n) yield n   def isprime(n, _seen={0: False, 1: False}): def _isprime(n): for p in primes(): if p*p > n: return True if n%p == 0: return False   if n not in _seen: _seen[n] = _isprime(n) return _seen[n]   def unprime(): for a in count(1): d = 1 while d <= a: base = (a//(d*10))*(d*10) + (a%d) # remove current digit if any(isprime(y) for y in range(base, base + d*10, d)): break d *= 10 else: yield a     print('First 35:') print(' '.join(str(i) for i in islice(unprime(), 35)))   print('\nThe 600-th:') print(list(islice(unprime(), 599, 600))[0]) print()   first, need = [False]*10, 10 for p in unprime(): i = p%10 if first[i]: continue   first[i] = p need -= 1 if not need: break   for i,v in enumerate(first): print(f'{i} ending: {v}')
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.
#PicoLisp
PicoLisp
(de randN (N) (if (= 1 (rand 1 N)) 1 0) )   (de unbiased (N) (use (A B) (while (= (setq A (randN N)) (setq B (randN N)) ) ) A ) )
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.
#PL.2FI
PL/I
  test: procedure options (main); /* 20 Nov. 2012 */   randN: procedure(N) returns (bit (1)); declare N fixed (1); declare random builtin; declare r fixed (2) external initial (-1); if r >= 0 then do; r = r-1; return ('0'b); end; r = random()*2*N; return ('1'b); end randN;   random: procedure returns (bit(1)); declare (r1, r2) bit (1); do until (r1 ^= r2); r1 = randN(N); r2 = randN(N); end; return (r1); end random;   declare (biasedrn, unbiasedrn) (100) bit (1); declare N fixed (1);   put ('N Biased Unbiased (tally of 100 random numbers)'); do N = 3 to 6; biasedrn = randN(N); unbiasedrn = random; put skip edit (N, sum(biasedrn), sum(unbiasedrn)) (F(1), 2 F(10)); end;   end test;  
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.
#Fortran
Fortran
SUBROUTINE CROAK(GASP) !Something bad has happened. CHARACTER*(*) GASP !As noted. WRITE (6,*) "Oh dear. ",GASP !So, gasp away. STOP "++ungood." !Farewell, cruel world. END !No return from this.   SUBROUTINE FILEHACK(FNAME,NB) CHARACTER*(*) FNAME !Name for the file. INTEGER NB !Number of bytes to survive. INTEGER L !A counter for te length of the file. INTEGER F,T !Mnemonics for file unit numbers. PARAMETER (F=66,T=67) !These should do. LOGICAL EXIST !Same as the mnemonic so left/right can be forgotten. CHARACTER*1 B !The worker! IF (FNAME.EQ."") CALL CROAK("Blank file name!") IF (NB.LE.0) CALL CROAK("Chop must be positive!") INQUIRE(FILE = FNAME, EXIST = EXIST) !This mishap is frequent, so attend to it. IF (.NOT.EXIST) CALL CROAK("Can't find a file called "//FNAME) !Tough love. OPEN (F,FILE=FNAME,STATUS="OLD",ACTION="READWRITE", !Grab the source file. 1 FORM="UNFORMATTED",RECL=1,ACCESS="DIRECT") !Oh dear. OPEN (T,STATUS="SCRATCH",FORM="UNFORMATTED",RECL=1) !Request a temporary file.   Copy the desired "records" to the temporary file. 10 DO L = 1,NB !Only up to a point. READ (F,REC = L,ERR = 20) B !One whole byte! WRITE (T) B !And, write it too! END DO !Again. 20 IF (L.LE.NB) CALL CROAK("Short file!") !Should end the loop with L = NB + 1. Convert from input to output... REWIND T !Not CLOSE! That would discard the file! CLOSE(F) !The source file still exists. OPEN (F,FILE=FNAME,FORM="FORMATTED", !But, 1 ACTION="WRITE",STATUS="REPLACE") !This dooms it! Copy from the temporary file. DO L = 1,NB !A certain number only. READ (T) B !One at at timne. WRITE (F,"(A1,$)") B !The $, obviously, means no end-of-record appendage. END DO !And again. Completed. 30 CLOSE(T) !Abandon the temporary file. CLOSE(F) !Finished with the source file. END !Done.   PROGRAM CHOPPER CALL FILEHACK("foobar.txt",12) 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.
#11l
11l
T NNode String value [NNode] children   F (value) .value = value   F add(node) .children.append(node)   F.const to_str(depth) -> String V result = (‘ ’ * depth)‘’(.value)"\n" L(child) .children result ‘’= child.to_str(depth + 1) R result   F String() R .to_str(0)   T INode String value Int level F (value, level) .value = value .level = level   F to_indented(node) [INode] result F add_node(NNode node, Int level) -> N @result.append(INode(node.value, level)) L(child) node.children @add_node(child, level + 1) add_node(node, 0) R result   F to_nested(tree) [NNode] stack V nnode = NNode(tree[0].value) L(i) 1 .< tree.len V inode = tree[i] I inode.level > stack.len stack.append(nnode) E I inode.level == stack.len stack.last.children.append(nnode) E L inode.level < stack.len stack.last.children.append(nnode) nnode = stack.pop() stack.last.children.append(nnode) nnode = NNode(inode.value)   L stack.len > 0 stack.last.children.append(nnode) nnode = stack.pop()   R nnode   print(‘Displaying tree built using nested structure:’) V nestedTree = NNode(‘RosettaCode’) V rocks = NNode(‘rocks’) rocks.add(NNode(‘code’)) rocks.add(NNode(‘comparison’)) rocks.add(NNode(‘wiki’)) V mocks = NNode(‘mocks’) mocks.add(NNode(‘trolling’)) nestedTree.add(rocks) nestedTree.add(mocks) print(nestedTree)   print(‘Displaying tree converted to indented structure:’) V indentedTree = to_indented(nestedTree) L(node) indentedTree print((node.level)‘ ’(node.value)) print()   print(‘Displaying tree converted back to nested structure:’) print(to_nested(indentedTree))   print(‘Are they equal? ’(I String(nestedTree) == String(to_nested(indentedTree)) {‘yes’} E ‘no’))
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.
#AutoHotkey
AutoHotkey
; Note: the original puzzle provides 12 statements and starts with ; "Given the following twelve statements...", so the first statement ; should ignore the F1 flag and always be true (see "( N == 1 )").   S := 12 ; number of statements Output := "" Loop, % 2**S { ;;If !Mod(A_Index,100) ;; optional 'if' to show the loop progress ;; ToolTip, Index: %A_Index% SetFlags(A_Index-1), Current := "", Count := 0 Loop, %S% R := TestStatement(A_Index), Current .= " " R, Count += (R == F%A_Index%) If ( Count >= S-1 ) Output .= Count " ->" Current "`n" If ( Count = S ) Solution := "`nSolution = " Current } ToolTip MsgBox, % Output . Solution Return   ;-------------------------------------------------------------------------------------   SetFlags(D) { Local I Loop, %S% I := S-A_Index+1 , F%I% := (D >> (S-A_Index)) & 1 }   ;-------------------------------------------------------------------------------------   TestStatement(N) { Local I, C := 0 If ( N == 1 ) ; This is a numbered list of twelve statements. Return ( S == 12 ) ; should always be true If ( N == 2 ) { ; Exactly 3 of the last 6 statements are true. Loop, 6 I := S-A_Index+1 , C += F%I% Return ( C == 3 ) } If ( N == 3 ) { ; Exactly 2 of the even-numbered statements are true. Loop, %S% C += ( !Mod(A_Index,2) & F%A_Index% ) Return ( C == 2 ) } If ( N == 4 ) ; If statement 5 is true, then statements 6 and 7 are both true. Return ( F5 ? F6 & F7 : 1 ) If ( N == 5 ) { ; The 3 preceding statements are all false. Loop, 3 I := N-A_Index , C += F%I% Return ( C == 0 ) } If ( N == 6 ) { ; Exactly 4 of the odd-numbered statements are true. Loop, %S% C += ( !!Mod(A_Index,2) & F%A_Index% ) Return ( C == 4 ) } If ( N == 7 ) ; Either statement 2 or 3 is true, but not both. Return ( F2 ^ F3 ) If ( N == 8 ) ; If statement 7 is true, then 5 and 6 are both true. Return ( F7 ? F5 & F6 : 1 ) If ( N == 9 ) { ; Exactly 3 of the first 6 statements are true. Loop, 6 C += F%A_Index% Return ( C == 3 ) } If ( N == 10 ) ; The next two statements are both true. Return ( F11 & F12 ) If ( N == 11 ) ; Exactly 1 of statements 7, 8 and 9 are true Return ( F7+F8+F9 == 1 ) If ( N == 12 ) { ; Exactly 4 of the preceding statements are true Loop, % N-1 C += F%A_Index% Return ( C == 4 ) } }
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.
#BASIC
BASIC
10 DEFINT A-Z: DATA "~",4,"&",3,"|",2,"^",2,"=>",1 20 DIM V(26),E(255),S(255),C(5),C$(5) 30 FOR I=1 TO 5: READ C$(I),C(I): NEXT 40 PRINT "Boolean expression evaluator" 50 PRINT "----------------------------" 60 PRINT "Operators are: ~ (not), & (and), | (or), ^ (xor), => (implies)." 70 PRINT "Variables are A-Z. Constant False and True are 0 and 1." 100 FOR I=1 TO 26: V(I)=0: NEXT 110 PRINT: LINE INPUT "Enter an expression: ";A$ 120 E$="": E=0: S=0 130 FOR I=1 TO LEN(A$) 140 I$=MID$(A$,I,1) 150 IF I$<>" " THEN E$=E$+I$ 160 NEXT 170 IF E$="" THEN END ELSE Y$=E$ 180 IF E$="" THEN 330 190 A$=LEFT$(E$,1): A=ASC(A$) OR 32: B$=RIGHT$(E$,LEN(E$)-1) 200 IF A>=97 AND A<=122 THEN E(E)=A-33: E=E+1: E$=B$: GOTO 180 210 IF A$="0" OR A$="1" THEN E(E)=VAL(A$)+32: E=E+1: E$=B$: GOTO 180 220 IF A$="(" THEN S(S)=97: S=S+1: E$=B$: GOTO 180 225 IF A$=")" THEN E$=B$: GOTO 300 227 I=1 230 IF LEFT$(E$,LEN(C$(I)))=C$(I) THEN 250 ELSE I=I+1: IF I<6 THEN 230 240 PRINT "Parse error at: ";E$: PRINT: GOTO 100 250 A$=C$(I): E$=RIGHT$(E$,LEN(E$)-LEN(A$)) 260 IF I=1 THEN S(S)=1: S=S+1: GOTO 180 270 IF S=0 THEN 290 275 IF S(S-1)<>97 AND C(S(S-1) AND 31)>=C(I) THEN 280 ELSE 290 280 S=S-1: E(E)=S(S): E=E+1: GOTO 270 290 S(S)=I: S=S+1: GOTO 180 300 IF S=0 THEN PRINT "Error: missing (!": GOTO 100 310 IF S(S-1)<>97 THEN S=S-1: E(E)=S(S): E=E+1: GOTO 300 320 S=S-1: GOTO 180 330 IF S=0 THEN 350 ELSE S=S-1 335 IF S(S)=97 THEN PRINT "Error: missing )!": GOTO 100 340 E(E)=S(S): E=E+1: GOTO 330 350 V$="" 360 FOR I=0 TO E-1 370 IF (E(I) AND 224)<>64 THEN 390 380 A$=CHR$(E(I)+1): IF INSTR(V$,A$)=0 THEN V$=V$+A$ 390 NEXT 400 GOSUB 600 410 FOR I=1 TO LEN(V$): PRINT MID$(V$,I,1);" ";: NEXT 420 PRINT "| ";Y$ 430 PRINT STRING$(2+2*LEN(V$)+LEN(Y$),"-") 440 FOR J=1 TO 2^LEN(V$) 450 FOR I=1 TO LEN(V$) 460 IF V(I) THEN PRINT "T "; ELSE PRINT "F "; 470 NEXT 480 PRINT "| ";: GOSUB 600: IF S(0) THEN PRINT "T" ELSE PRINT "F" 490 I=1 500 IF V(I) THEN V(I)=0: I=I+1: GOTO 500 ELSE V(I)=1 510 NEXT 520 GOTO 100 600 S=0 610 FOR I=0 TO E-1: T=E(I) AND 224: V=E(I) AND 31 620 IF T=0 THEN ON V GOTO 700,710,720,730,740 630 IF T=32 THEN S(S)=-V: S=S+1: GOTO 650 640 IF T=64 THEN S(S)=V(INSTR(V$,CHR$(V+65))): S=S+1: GOTO 650 650 NEXT 660 IF S<>1 THEN PRINT "Missing operator": GOTO 100 670 RETURN 700 IF S<1 THEN 770 ELSE S(S-1)=1-S(S-1): GOTO 650 710 IF S<2 THEN 770 ELSE S=S-1:S(S-1)=S(S-1) AND S(S): GOTO 650 720 IF S<2 THEN 770 ELSE S=S-1:S(S-1)=S(S-1) OR S(S): GOTO 650 730 IF S<2 THEN 770 ELSE S=S-1:S(S-1)=S(S-1) XOR S(S): GOTO 650 740 IF S<2 THEN 770 ELSE S=S-1 750 IF S(S-1) THEN S(S-1)=S(S) ELSE S(S-1)=-1 760 GOTO 650 770 PRINT "Missing operand": GOTO 100
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
#EchoLisp
EchoLisp
  (lib 'plot)   (define *red* (rgb 1 0 0)) (define (ulam n nmax) (if ( prime? n) *red* (gray (// n nmax)))) (plot-spiral ulam 1000) ;; range [0...1000]  
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Standard_ML
Standard ML
OS.Process.system "ls -a"
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Stata
Stata
. dir *.dta 6.3k 6/12/17 14:26 auto.dta 2.3k 8/10/17 7:34 titanium.dta 6.0k 8/12/17 9:28 trend.dta
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Tcl
Tcl
puts [join [lsort [glob -nocomplain *]] "\n"]
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
#Wren
Wren
class Vector3D { construct new(x, y, z) { if (x.type != Num || y.type != Num || z.type != Num) Fiber.abort("Arguments must be numbers.") _x = x _y = y _z = z }   x { _x } y { _y } z { _z }   dot(v) { if (v.type != Vector3D) Fiber.abort("Argument must be a Vector3D.") return _x * v.x + _y * v.y + _z * v.z }   cross(v) { if (v.type != Vector3D) Fiber.abort("Argument must be a Vector3D.") return Vector3D.new(_y*v.z - _z*v.y, _z*v.x - _x*v.z, _x*v.y - _y*v.x) }   scalarTriple(v, w) { if ((v.type != Vector3D) || (w.type != Vector3D)) Fiber.abort("Arguments must be Vector3Ds.") return this.dot(v.cross(w)) }   vectorTriple(v, w) { if ((v.type != Vector3D) || (w.type != Vector3D)) Fiber.abort("Arguments must be Vector3Ds.") return this.cross(v.cross(w)) }   toString { [_x, _y, _z].toString } }   var a = Vector3D.new(3, 4, 5) var b = Vector3D.new(4, 3, 5) var c = Vector3D.new(-5, -12, -13) System.print("a = %(a)") System.print("b = %(b)") System.print("c = %(c)") System.print() System.print("a . b = %(a.dot(b))") System.print("a x b = %(a.cross(b))") System.print("a . b x c = %(a.scalarTriple(b, c))") System.print("a x b x c = %(a.vectorTriple(b, c))")
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.
#PureBasic
PureBasic
  Procedure isPrime(v.i) If v <= 1  : ProcedureReturn #False ElseIf v < 4  : ProcedureReturn #True ElseIf v % 2 = 0 : ProcedureReturn #False ElseIf v < 9  : ProcedureReturn #True ElseIf v % 3 = 0 : ProcedureReturn #False Else Protected r = Round(Sqr(v), #PB_Round_Down) Protected f = 5 While f <= r If v % f = 0 Or v % (f + 2) = 0 ProcedureReturn #False EndIf f + 6 Wend EndIf ProcedureReturn #True EndProcedure   Procedure paresDePrimos(limite.d) p1.i = 0 p2.i = 1 p3.i = 1 count.i = 0 For i.i = 5 To limite p3 = p2 p2 = p1 p1 = isPrime(i) If p3 And p1 count + 1 EndIf Next i ProcedureReturn count EndProcedure   OpenConsole() n.i = 1 For i.i = 1 To 6 n = n * 10 PrintN("pares de primos gemelos por debajo de < " + Str(n) + " : " + Str(paresDePrimos(n))) Next i PrintN(#CRLF$ + "--- terminado, pulsa RETURN---"): Input() CloseConsole() 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.
#Python
Python
primes = [2, 3, 5, 7, 11, 13, 17, 19]     def count_twin_primes(limit: int) -> int: global primes if limit > primes[-1]: ram_limit = primes[-1] + 90000000 - len(primes) reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) - 1   while reasonable_limit < limit: ram_limit = primes[-1] + 90000000 - len(primes) if ram_limit > primes[-1]: reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) else: reasonable_limit = min(limit, primes[-1] ** 2)   sieve = list({x for prime in primes for x in range(primes[-1] + prime - (primes[-1] % prime), reasonable_limit, prime)}) primes += [x - 1 for i, x in enumerate(sieve) if i and x - 1 != sieve[i - 1] and x - 1 < limit]   count = len([(x, y) for (x, y) in zip(primes, primes[1:]) if x + 2 == y])   return count     def test(limit: int): count = count_twin_primes(limit) print(f"Number of twin prime pairs less than {limit} is {count}\n")     test(10) test(100) test(1000) test(10000) test(100000) test(1000000) test(10000000) test(100000000)
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)
#Racket
Racket
#lang racket   (require math/number-theory)   (define cached-prime? (let ((hsh# (make-hash))) (λ (p) (hash-ref! hsh# p (λ () (prime? p))))))   (define (zero-digit n d) (define p (expt 10 d)) (+ (remainder n p) (* 10 p (quotient n (* p 10)))))   (define (primeable? n) (or (cached-prime? n) (for*/first ((d (in-range (add1 (order-of-magnitude n)))) (n0 (in-value (zero-digit n d))) (p (in-value (expt 10 d))) (r (in-range 10)) (n+ (in-value (+ n0 (* r p)))) #:when (cached-prime? n+)) n+)))   (define unprimeable? (negate primeable?))   (module+ main (printf "First 35 unprimeable numbers: ~a~%" (let recur ((i 0) (n 1) (acc null)) (cond [(= i 35) (reverse acc)] [(unprimeable? n) (recur (add1 i) (add1 n) (cons n acc))] [else (recur i (add1 n) acc)])))   (printf "600th unprimeable number: ~a~%" (let recur ((i 0) (n 1) (u #f)) (cond [(= i 600) u] [(unprimeable? n) (recur (add1 i) (add1 n) n)] [else (recur i (add1 n) u)])))   (for ((d 10)) (printf "Least unprimeable number ending in ~a = ~a~%" d (for/first ((i (in-range (+ 100 d) +Inf.0 10)) #:when (unprimeable? i)) i))))   (module+ test (require rackunit) (check-equal? (zero-digit 1234 2) 1034) (check-equal? (primeable? 10) 11) (check-true (unprimeable? 200)) (check-false (unprimeable? 201)))
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.]
#11l
11l
V MAX_PRIME = 1000000 V primes = [1B] * MAX_PRIME primes[0] = primes[1] = 0B   V i = 2 L i * i < MAX_PRIME L(j) (i * i .< MAX_PRIME).step(i) primes[j] = 0B i++ L i < MAX_PRIME & !primes[i] i++   F left_trunc(=n) V tens = 1 L tens < n tens *= 10   L n != 0 I !:primes[n] R 0B tens I/= 10 I n < tens R 0B n %= tens   R 1B   F right_trunc(=n) L n != 0 I !:primes[n] R 0B n I/= 10 R 1B   L(n) (MAX_PRIME - 1 .< 0).step(-2) I left_trunc(n) print(‘Left: ’n) L.break   L(n) (MAX_PRIME - 1 .< 0).step(-2) I right_trunc(n) print(‘Right: ’n) L.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.
#PowerShell
PowerShell
  function randN ( [int]$N ) { [int]( ( Get-Random -Maximum $N ) -eq 0 ) }   function unbiased ( [int]$N ) { do { $X = randN $N $Y = randN $N } While ( $X -eq $Y )   return $X }  
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.
#PureBasic
PureBasic
Procedure biased(n) If Random(n) <> 1 ProcedureReturn 0 EndIf ProcedureReturn 1 EndProcedure   Procedure unbiased(n) Protected a, b Repeat a = biased(n) b = biased(n) Until a <> b ProcedureReturn a EndProcedure   #count = 100000   Define n, m, output.s For n = 3 To 6 Dim b_count(1) Dim u_count(1) For m = 1 To #count x = biased(n) b_count(x) + 1 x = unbiased(n) u_count(x) + 1 Next output + "N = " + Str(n) + #LF$ output + " biased =>" + #tab$ + "#0=" + Str(b_count(0)) + #tab$ + "#1=" +Str(b_count(1)) output + #tab$ + " ratio=" + StrF(b_count(1) / #count * 100, 2) + "%" + #LF$ output + " unbiased =>" + #tab$ + "#0=" + Str(u_count(0)) + #tab$ + "#1=" + Str(u_count(1)) output + #tab$ + " ratio=" + StrF(u_count(1) / #count * 100, 2) + "%" + #LF$ Next MessageRequester("Biased and Unbiased random number results", output)
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.
#FreeBASIC
FreeBASIC
Sub truncateFile (archivo As String, longitud As Long) If Len(Dir(archivo)) Then Dim f As Long, c As String f = Freefile Open archivo For Binary As #f If longitud > Lof(f) Then Close #f Error 62 'Input past end of file Else c = Space(longitud) Get #f, 1, c Close f Open archivo For Output As #f Print #f, c; Close #f End If Else Error 53 'File not found End If End Sub
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#Go
Go
import ( "fmt" "os" )   if err := os.Truncate("filename", newSize); err != nil { fmt.Println(err) }
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.
#C.2B.2B
C++
#include <iomanip> #include <iostream> #include <list> #include <string> #include <vector> #include <utility> #include <vector>   class nest_tree;   bool operator==(const nest_tree&, const nest_tree&);   class nest_tree { public: explicit nest_tree(const std::string& name) : name_(name) {} nest_tree& add_child(const std::string& name) { children_.emplace_back(name); return children_.back(); } void print(std::ostream& out) const { print(out, 0); } const std::string& name() const { return name_; } const std::list<nest_tree>& children() const { return children_; } bool equals(const nest_tree& n) const { return name_ == n.name_ && children_ == n.children_; } private: void print(std::ostream& out, int level) const { std::string indent(level * 4, ' '); out << indent << name_ << '\n'; for (const nest_tree& child : children_) child.print(out, level + 1); } std::string name_; std::list<nest_tree> children_; };   bool operator==(const nest_tree& a, const nest_tree& b) { return a.equals(b); }   class indent_tree { public: explicit indent_tree(const nest_tree& n) { items_.emplace_back(0, n.name()); from_nest(n, 0); } void print(std::ostream& out) const { for (const auto& item : items_) std::cout << item.first << ' ' << item.second << '\n'; } nest_tree to_nest() const { nest_tree n(items_[0].second); to_nest_(n, 1, 0); return n; } private: void from_nest(const nest_tree& n, int level) { for (const nest_tree& child : n.children()) { items_.emplace_back(level + 1, child.name()); from_nest(child, level + 1); } } size_t to_nest_(nest_tree& n, size_t pos, int level) const { while (pos < items_.size() && items_[pos].first == level + 1) { nest_tree& child = n.add_child(items_[pos].second); pos = to_nest_(child, pos + 1, level + 1); } return pos; } std::vector<std::pair<int, std::string>> items_; };   int main() { nest_tree n("RosettaCode"); auto& child1 = n.add_child("rocks"); auto& child2 = n.add_child("mocks"); child1.add_child("code"); child1.add_child("comparison"); child1.add_child("wiki"); child2.add_child("trolling");   std::cout << "Initial nest format:\n"; n.print(std::cout);   indent_tree i(n); std::cout << "\nIndent format:\n"; i.print(std::cout);   nest_tree n2(i.to_nest()); std::cout << "\nFinal nest format:\n"; n2.print(std::cout);   std::cout << "\nAre initial and final nest formats equal? " << std::boolalpha << n.equals(n2) << '\n';   return 0; }
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.
#BBC_BASIC
BBC BASIC
nStatements% = 12 DIM Pass%(nStatements%), T%(nStatements%)   FOR try% = 0 TO 2^nStatements%-1   REM Postulate answer: FOR stmt% = 1 TO 12 T%(stmt%) = (try% AND 2^(stmt%-1)) <> 0 NEXT   REM 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) = ((T%(2) EOR 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)   CASE SUM(Pass%()) OF WHEN -11: PRINT "Near miss with statements "; FOR stmt% = 1 TO 12 IF T%(stmt%) PRINT ; stmt% " "; IF NOT Pass%(stmt%) miss% = stmt% NEXT PRINT "true (failed " ;miss% ")." WHEN -12: PRINT "Solution! with statements "; FOR stmt% = 1 TO 12 IF T%(stmt%) PRINT ; stmt% " "; NEXT PRINT "true." ENDCASE   NEXT try% END
http://rosettacode.org/wiki/Twelve_statements
Twelve statements
This puzzle is borrowed from   math-frolic.blogspot. Given the following twelve statements, which of them are true? 1. This is a numbered list of twelve statements. 2. Exactly 3 of the last 6 statements are true. 3. Exactly 2 of the even-numbered statements are true. 4. If statement 5 is true, then statements 6 and 7 are both true. 5. The 3 preceding statements are all false. 6. Exactly 4 of the odd-numbered statements are true. 7. Either statement 2 or 3 is true, but not both. 8. If statement 7 is true, then 5 and 6 are both true. 9. Exactly 3 of the first 6 statements are true. 10. The next two statements are both true. 11. Exactly 1 of statements 7, 8 and 9 are true. 12. Exactly 4 of the preceding statements are true. Task When you get tired of trying to figure it out in your head, write a program to solve it, and print the correct answer or answers. Extra credit Print out a table of near misses, that is, solutions that are contradicted by only a single statement.
#Bracmat
Bracmat
( ( number = n done ntest oldFT .  !arg:(?done.(=?ntest).?oldFT) & 0:?n & (  !done  :  ? ( !ntest . !oldFT&1+!n:?n&~ )  ? | !n ) ) & ( STATEMENTS = ( (1."This is a numbered list of twelve statements.") . 1 . ( = n nr done toDo .  !arg:(?done.?toDo) & 0:?n & whl ' ( !done:(?nr.?) ?done & 1+!n:!nr:?n ) & whl ' ( !toDo:((?nr.?).?) ?toDo & 1+!n:!nr:?n ) & (!n:12&true|false) ) ) ( (2."Exactly 3 of the last 6 statements are true.") . end . ( = done toDo lastSix .  !arg:(?done.?toDo) & !done:? [-7 ?lastSix & ( number$(!lastSix.(=?).true):3 & true | false ) ) ) ( (3."Exactly 2 of the even-numbered statements are true.") . end . ( = done toDo ii .  !arg:(?done.?toDo) & ( number $ ( !done . (=?ii&!ii*1/2:~/) . true )  : 2 & true | false ) ) ) ( (4."If statement 5 is true, then statements 6 and 7 are both true.") . 7 . ( = done toDo .  !arg:(?done.?toDo) & (  !done  : ( ? (5.false) ? |  ? (6.true) ?  : ? (7.true) ? ) & true | false ) ) ) ( (5."The 3 preceding statements are all false.") . 5 . ( = done toDo .  !arg:(?done.?toDo) & (  !done  :  ? (?.false) (?.false) (?.false) (?.?) & true | false ) ) ) ( (6."Exactly 4 of the odd-numbered statements are true.") . end . ( = done toDo i .  !arg:(?done.?toDo) & ( number $ ( !done . (=?i&!i*1/2:/) . true )  : 4 & true | false ) ) ) ( (7."Either statement 2 or 3 is true, but not both.") . 7 . ( = done toDo .  !arg:(?done.?toDo) & ( number $ (!done.(=2|3).true)  : 1 & true | false ) ) ) ( (8."If statement 7 is true, then 5 and 6 are both true.") . 8 . ( = done toDo .  !arg:(?done.?toDo) & (  !done  : ( ? (7.false) ? |  ? (5.true) ?  : ? (6.true) ? ) & true | false ) ) ) ( (9."Exactly 3 of the first 6 statements are true.") . 9 . ( = done toDo firstSix .  !arg:(?done.?toDo) & !done:?firstSix [6 ? & ( number$(!firstSix.(=?).true):3 & true | false ) ) ) ( (10."The next two statements are both true.") . 12 . ( = done toDo .  !arg:(?done.?toDo) & (  !done:? (?.true) (?.true) & true | false ) ) ) ( (11."Exactly 1 of statements 7, 8 and 9 are true.") . 11 . ( = done toDo .  !arg:(?done.?toDo) & ( number $ ( !done . (=7|8|9) . true )  : 1 & true | false ) ) ) ( (12."Exactly 4 of the preceding statements are true.") . 12 . ( = done toDo preceding .  !arg:(?done.?toDo) & !done:?preceding (?.?) & ( number$(!preceding.(=?).true):4 & true | false ) ) ) ) & ( TestTruth = done toDo postponedTests testToBePostponed , n when test FT oldFT A Z text , postponedTest testNow .  !arg:(?done.?toDo.?postponedTests) & (  !toDo: & "We have come to the end of the list of tests. Perform any tests that had to be postponed until now." & whl ' (  !postponedTests  : (?.?oldFT.(=?postponedTest)) ?A & postponedTest$(!done.):!oldFT & !A:?postponedTests ) & !postponedTests: & out$("Solution:" !done) & ~ |  !toDo  : ((?n.?text).?when.(=?test)) ?toDo & "'false' and 'true' are just two symbols, not 'boolean values'. You can choose other symbols if you like. The program first guesses the first symbol and assigns it to the variable FT. After backtracking, the second symbol is guessed and assigned to FT. This is done for each statement." & false true  :  ?  %@?FT ( ? & 1+!guesses:?guesses & (!n.!FT):?testNow & "Do all tests that had to be postponed until now, unless one of those tests fails. Remove the successful tests from the list of postponed tests." & whl ' (  !postponedTests  :  ?A (!n.?oldFT.(=?postponedTest))  ?Z & postponedTest$(!done !testNow.!toDo)  : !oldFT & !A !Z:?postponedTests ) & "Check that all tests that had to be postponed until now are removed from the list of postponed tests. Only then go on with looking at testing the current statement. Backtrack if a test failed." & !postponedTests:~(? (!n.?) ?) & (  !when:>!n & "The current statement cannot be tested right now. Postpone it to the earliest coming statement where the current statement can be tested. (The earliest statement, denoted by 'when', is computed manually.)" & (!when.!FT.'$test):?testToBePostponed | "No need to postpone. Test the current statement now." & :?testToBePostponed & "If the test fails, backtrack. If it succeeds, go on to the next statement." & test$(!done !testNow.!toDo):!FT ) & "So far so good. Test the next statements. (recursively)" & TestTruth $ ( !done !testNow . !toDo . !testToBePostponed !postponedTests ) ) ) ) & 0:?guesses & TestTruth$(.!STATEMENTS.) | out $ ( str $ ( "That's it. I made "  !guesses " true/false guesses in all. (A brute force method needs 2^12=" 2^12 " guesses." ) ) );
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
C
#include <stdio.h> #include <string.h> #include <stdlib.h>   #define TRUE 1 #define FALSE 0 #define STACK_SIZE 80 #define BUFFER_SIZE 100   typedef int bool;   typedef struct { char name; bool val; } var;   typedef struct { int top; bool els[STACK_SIZE]; } stack_of_bool;   char expr[BUFFER_SIZE]; int expr_len; var vars[24]; int vars_len;   /* stack manipulation functions */   bool is_full(stack_of_bool *sp) { return sp->top == STACK_SIZE - 1; }   bool is_empty(stack_of_bool *sp) { return sp->top == -1; }   bool peek(stack_of_bool *sp) { if (!is_empty(sp)) return sp->els[sp->top]; else { printf("Stack is empty.\n"); exit(1); } }   void push(stack_of_bool *sp, bool val) { if (!is_full(sp)) { sp->els[++(sp->top)] = val; } else { printf("Stack is full.\n"); exit(1); } }   bool pop(stack_of_bool *sp) { if (!is_empty(sp)) return sp->els[(sp->top)--]; else { printf("\nStack is empty.\n"); exit(1); } }   void make_empty(stack_of_bool *sp) { sp->top = -1; }   int elems_count(stack_of_bool *sp) { return (sp->top) + 1; }   bool is_operator(const char c) { return c == '&' || c == '|' || c == '!' || c == '^'; }   int vars_index(const char c) { int i; for (i = 0; i < vars_len; ++i) { if (vars[i].name == c) return i; } return -1; }   bool eval_expr() { int i, vi; char e; stack_of_bool s; stack_of_bool *sp = &s; make_empty(sp); for (i = 0; i < expr_len; ++i) { e = expr[i]; if (e == 'T') push(sp, TRUE); else if (e == 'F') push(sp, FALSE); else if((vi = vars_index(e)) >= 0) { push(sp, vars[vi].val); } else switch(e) { case '&': push(sp, pop(sp) & pop(sp)); break; case '|': push(sp, pop(sp) | pop(sp)); break; case '!': push(sp, !pop(sp)); break; case '^': push(sp, pop(sp) ^ pop(sp)); break; default: printf("\nNon-conformant character '%c' in expression.\n", e); exit(1); } } if (elems_count(sp) != 1) { printf("\nStack should contain exactly one element.\n"); exit(1); } return peek(sp); }   void set_vars(int pos) { int i; if (pos > vars_len) { printf("\nArgument to set_vars can't be greater than the number of variables.\n"); exit(1); } else if (pos == vars_len) { for (i = 0; i < vars_len; ++i) { printf((vars[i].val) ? "T " : "F "); } printf("%c\n", (eval_expr()) ? 'T' : 'F'); } else { vars[pos].val = FALSE; set_vars(pos + 1); vars[pos].val = TRUE; set_vars(pos + 1); } }   /* removes whitespace and converts to upper case */ void process_expr() { int i, count = 0; for (i = 0; expr[i]; ++i) { if (!isspace(expr[i])) expr[count++] = toupper(expr[i]); } expr[count] = '\0'; }   int main() { int i, h; char e; printf("Accepts single-character variables (except for 'T' and 'F',\n"); printf("which specify explicit true or false values), postfix, with\n"); printf("&|!^ for and, or, not, xor, respectively; optionally\n"); printf("seperated by whitespace. Just enter nothing to quit.\n");   while (TRUE) { printf("\nBoolean expression: "); fgets(expr, BUFFER_SIZE, stdin); fflush(stdin); process_expr(); expr_len = strlen(expr); if (expr_len == 0) break; vars_len = 0; for (i = 0; i < expr_len; ++i) { e = expr[i]; if (!is_operator(e) && e != 'T' && e != 'F' && vars_index(e) == -1) { vars[vars_len].name = e; vars[vars_len].val = FALSE; vars_len++; } } printf("\n"); if (vars_len == 0) { printf("No variables were entered.\n"); } else { for (i = 0; i < vars_len; ++i) printf("%c ", vars[i].name); printf("%s\n", expr); h = vars_len * 3 + expr_len; for (i = 0; i < h; ++i) printf("="); printf("\n"); set_vars(0); } } return 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
#Elixir
Elixir
defmodule Ulam do defp cell(n, x, y, start) do y = y - div(n, 2) x = x - div(n - 1, 2) l = 2 * max(abs(x), abs(y)) d = if y >= x, do: l*3 + x + y, else: l - x - y (l - 1)*(l - 1) + d + start - 1 end   def show_spiral(n, symbol\\nil, start\\1) do IO.puts "\nN : #{n}" if symbol==nil, do: format = "~#{length(to_char_list(start + n*n - 1))}s " prime = prime(n*n + start) Enum.each(0..n-1, fn y -> Enum.each(0..n-1, fn x -> i = cell(n, x, y, start) if symbol do IO.write if i in prime, do: Enum.at(symbol,0), else: Enum.at(symbol,1) else  :io.fwrite format, [if i in prime do to_char_list(i) else "" end] end end) IO.puts "" end) end   defp prime(num), do: prime(Enum.to_list(2..num), []) defp prime([], p), do: Enum.reverse(p) defp prime([h|t], p), do: prime((for i <- t, rem(i,h)>0, do: i), [h|p]) end   Ulam.show_spiral(9) Ulam.show_spiral(25) Ulam.show_spiral(25, ["#"," "])
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Ursa
Ursa
decl file f decl string<> fnames set fnames (sort (f.listdir "."))   for (decl int i) (< i (size fnames)) (inc i) out fnames<i> endl console end for
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Vlang
Vlang
import os   fn main() { contents := os.ls('.')? println(contents) }
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Wren
Wren
import "io" for Directory   var path = "./" // or whatever   // Note that output is automatically sorted using this method. Directory.list(path).each { |f| System.print(f) }
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
#XBS
XBS
#> Vector3 Class <# class Vector3 { construct=func(self,x,y,z){ self:x=x; self:y=y; self:z=z; }; ToString=func(self){ send self.x+", "+self.y+", "+self.z; }; Magnitude=func(self){ send math.sqrt((self.x^2)+(self.y^2)+(self.z^2)); }; Normalize=func(self){ set Mag = self::Magnitude(); send new Vector3 with [self.x/Mag,self.y/Mag,self.z/Mag]; }; Dot=func(self,v2){ send (self.x*v2.x)+(self.y*v2.y)+(self.z*v2.z); }; __add=func(self,x){ if (type(x)=="object"){ send new Vector3 with [self.x+x.x,self.y+x.y,self.z+x.z]; } else { send new Vector3 with [self.x+x,self.y+x,self.z+x]; } }; __sub=func(self,x){ if (type(x)=="object"){ send new Vector3 with [self.x-x.x,self.y-x.y,self.z-x.z]; } else { send new Vector3 with [self.x-x,self.y-x,self.z-x]; } }; __mul=func(self,x){ if (type(x)=="object"){ send new Vector3 with [self.x*x.x,self.y*x.y,self.z*x.z]; } else { send new Vector3 with [self.x*x,self.y*x,self.z*x]; } }; __div=func(self,x){ if (type(x)=="object"){ send new Vector3 with [self.x/x.x,self.y/x.y,self.z/x.z]; } else { send new Vector3 with [self.x/x,self.y/x,self.z/x]; } }; __pow=func(self,x){ if (type(x)=="object"){ send new Vector3 with [self.x^x.x,self.y^x.y,self.z^x.z]; } else { send new Vector3 with [self.x^x,self.y^x,self.z^x]; } }; __mod=func(self,x){ if (type(x)=="object"){ send new Vector3 with [self.x%x.x,self.y%x.y,self.z%x.z]; } else { send new Vector3 with [self.x%x,self.y%x,self.z%x]; } }; Reflect=func(self,v2){ set Normal = self::Normalize(); set Direction = v2::Normalize(); send (Normal*(2*Normal::Dot(Direction)))-Direction; }; Cross=func(self,v2){ send new Vector3 with [(self.y*v2.z)-(self.z*v2.y),(self.z*v2.x)-(self.x*v2.z),(self.x*v2.y)-(self.y*v2.x)]; }; }   math:deg=func(x){ send x*(180/math.PI); }   math:rad=func(x){ send x*(math.PI/180); }   set a = new Vector3 with [3,4,5]; set b = new Vector3 with [4,3,5]; set c = new Vector3 with [-5,-12,-13];   log("Dot: ",a::Dot(b)); log("Cross: ",a::Cross(b)::ToString()); log("Scalar Triple: ",a::Dot(b::Cross(c))); log("Vector Triple: ",a::Cross(b::Cross(c))::ToString());
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.
#Quackery
Quackery
[ dup dip [ eratosthenes 0 1 primes share ] bit 1 - & 1 >> [ dup while dup 5 & 5 = if [ rot 1+ unrot ] 2 >> dip [ 2 + ] again ] 2drop ] is twinprimes ( n --> [ )   5 times [ say "Number of twin primes below " 10 i^ 1+ ** dup echo say " is " twinprimes echo say "." cr ]
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.
#Raku
Raku
use Lingua::EN::Numbers;   use Math::Primesieve;   my $p = Math::Primesieve.new;   printf "Twin prime pairs less than %14s: %s\n", comma(10**$_), comma $p.count(10**$_, :twins) for 1 .. 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)
#Raku
Raku
use ntheory:from<Perl5> <is_prime>; use Lingua::EN::Numbers;   sub is-unprimeable (\n) { return False if n.&is_prime; my \chrs = n.chars; for ^chrs -> \place { my \pow = 10**(chrs - place - 1); my \this = n.substr(place, 1) × pow; ^10 .map: -> \dgt { next if this == dgt; return False if is_prime(n - this + dgt × pow) } } True }   my @ups = lazy ^∞ .grep: { .&is-unprimeable };   say "First 35 unprimeables:\n" ~ @ups[^35];   say "\n{ordinal-digit(600, :u)} unprimeable: " ~ comma( @ups[599] ) ~ "\n";   ^10 .map: -> \n { print "First unprimeable that ends with {n}: " ~ sprintf "%9s\n", comma (n, *+10 … *).race.first: { .&is-unprimeable } }
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.]
#Ada
Ada
  with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Ordered_Sets;   procedure Truncatable_Primes is package Natural_Set is new Ada.Containers.Ordered_Sets (Natural); use Natural_Set;   Primes : Set;   function Is_Prime (N : Natural) return Boolean is Position : Cursor := First (Primes); begin while Has_Element (Position) loop if N mod Element (Position) = 0 then return False; end if; Position := Next (Position); end loop; return True; end Is_Prime;   function Is_Left_Trucatable_Prime (N : Positive) return Boolean is M : Natural := 1; begin while Contains (Primes, N mod (M * 10)) and (N / M) mod 10 > 0 loop M := M * 10; if N <= M then return True; end if; end loop; return False; end Is_Left_Trucatable_Prime;   function Is_Right_Trucatable_Prime (N : Positive) return Boolean is M : Natural := N; begin while Contains (Primes, M) and M mod 10 > 0 loop M := M / 10; if M <= 1 then return True; end if; end loop; return False; end Is_Right_Trucatable_Prime;   Position : Cursor; begin for N in 2..1_000_000 loop if Is_Prime (N) then Insert (Primes, N); end if; end loop; Position := Last (Primes); while Has_Element (Position) loop if Is_Left_Trucatable_Prime (Element (Position)) then Put_Line ("Largest LTP from 1..1000000:" & Integer'Image (Element (Position))); exit; end if; Previous (Position); end loop; Position := Last (Primes); while Has_Element (Position) loop if Is_Right_Trucatable_Prime (Element (Position)) then Put_Line ("Largest RTP from 1..1000000:" & Integer'Image (Element (Position))); exit; end if; Previous (Position); end loop; end Truncatable_Primes;  
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.
#Python
Python
from __future__ import print_function import random   def randN(N): " 1,0 random generator factory with 1 appearing 1/N'th of the time" return lambda: random.randrange(N) == 0   def unbiased(biased): 'uses a biased() generator of 1 or 0, to create an unbiased one' this, that = biased(), biased() while this == that: # Loop until 10 or 01 this, that = biased(), biased() return this # return the first   if __name__ == '__main__': from collections import namedtuple   Stats = namedtuple('Stats', 'count1 count0 percent')   for N in range(3, 7): biased = randN(N) v = [biased() for x in range(1000000)] v1, v0 = v.count(1), v.count(0) print ( "Biased(%i) = %r" % (N, Stats(v1, v0, 100. * v1/(v1 + v0))) )   v = [unbiased(biased) for x in range(1000000)] v1, v0 = v.count(1), v.count(0) print ( " Unbiased = %r" % (Stats(v1, v0, 100. * v1/(v1 + v0)), ) )
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.
#Haskell
Haskell
setFileSize :: FilePath -> FileOffset -> IO () -- Truncates the file down to the specified length. -- If the file was larger than the given length -- before this operation was performed the extra is lost. -- Note: calls truncate.  
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.
#Icon_and_Unicon
Icon and Unicon
truncate(f := open(filename, "bu"), newsizeinbytes) & close(f)
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#J
J
require 'files' NB. needed for versions prior to J7 ftruncate=: ] fwrite~ ] fread@; 0 , [
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.
#Go
Go
package main   import ( "fmt" "io" "os" "strings" )   type nNode struct { name string children []nNode }   type iNode struct { level int name string }   func printNest(n nNode, level int, w io.Writer) { if level == 0 { fmt.Fprintln(w, "\n==Nest form==\n") } fmt.Fprintf(w, "%s%s\n", strings.Repeat(" ", level), n.name) for _, c := range n.children { fmt.Fprintf(w, "%s", strings.Repeat(" ", level+1)) printNest(c, level+1, w) } }   func toNest(iNodes []iNode, start, level int, n *nNode) { if level == 0 { n.name = iNodes[0].name } for i := start + 1; i < len(iNodes); i++ { if iNodes[i].level == level+1 { c := nNode{iNodes[i].name, nil} toNest(iNodes, i, level+1, &c) n.children = append(n.children, c) } else if iNodes[i].level <= level { return } } }   func printIndent(iNodes []iNode, w io.Writer) { fmt.Fprintln(w, "\n==Indent form==\n") for _, n := range iNodes { fmt.Fprintf(w, "%d %s\n", n.level, n.name) } }   func toIndent(n nNode, level int, iNodes *[]iNode) { *iNodes = append(*iNodes, iNode{level, n.name}) for _, c := range n.children { toIndent(c, level+1, iNodes) } }   func main() { n1 := nNode{"RosettaCode", nil} n2 := nNode{"rocks", []nNode{{"code", nil}, {"comparison", nil}, {"wiki", nil}}} n3 := nNode{"mocks", []nNode{{"trolling", nil}}} n1.children = append(n1.children, n2, n3)   var sb strings.Builder printNest(n1, 0, &sb) s1 := sb.String() fmt.Print(s1)   var iNodes []iNode toIndent(n1, 0, &iNodes) printIndent(iNodes, os.Stdout)   var n nNode toNest(iNodes, 0, 0, &n) sb.Reset() printNest(n, 0, &sb) s2 := sb.String() fmt.Print(s2)   fmt.Println("\nRound trip test satisfied? ", s1 == s2) }
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]
#AppleScript
AppleScript
on treeFromNestingLevels(input) set maxLevel to 0 repeat with thisLevel in input if (thisLevel > maxLevel) then set maxLevel to thisLevel end repeat if (maxLevel < 2) then return input   set emptyList to {} repeat with testLevel from maxLevel to 2 by -1 set output to {} set subnest to {} repeat with thisLevel in input set thisLevel to thisLevel's contents if ((thisLevel's class is integer) and (thisLevel < testLevel)) then if (subnest ≠ emptyList) then set subnest to {} set end of output to thisLevel else if (subnest = emptyList) then set end of output to subnest set end of subnest to thisLevel end if end repeat set input to output end repeat   return output end treeFromNestingLevels   -- Task code: local output, astid, input, part1, errMsg set output to {} set astid to AppleScript's text item delimiters repeat with input in {{}, {1, 2, 4}, {3, 1, 3, 1}, {1, 2, 3, 1}, {3, 2, 1, 3}, {3, 3, 3, 1, 1, 3, 3, 3}} set input to input's contents set AppleScript's text item delimiters to ", " set part1 to "{" & input & "} nests to: {" -- It's a pain having to parse nested lists to text, so throw a deliberate error and parse the error message instead. try || of treeFromNestingLevels(input) on error errMsg set AppleScript's text item delimiters to {"{", "}"} set end of output to part1 & ((text from text item 2 to text item -2 of errMsg) & "}") end try end repeat set AppleScript's text item delimiters to linefeed set output to output as text set AppleScript's text item delimiters to astid return output
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.23
C#
using System; using System.Collections.Generic; using System.Linq;   public static class TwelveStatements { public static void Main() { Func<Statements, bool>[] checks = { st => st[1], st => st[2] == (7.To(12).Count(i => st[i]) == 3), st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2), st => st[4] == st[5].Implies(st[6] && st[7]), st => st[5] == (!st[2] && !st[3] && !st[4]), st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4), st => st[7] == (st[2] != st[3]), st => st[8] == st[7].Implies(st[5] && st[6]), st => st[9] == (1.To(6).Count(i => st[i]) == 3), st => st[10] == (st[11] && st[12]), st => st[11] == (7.To(9).Count(i => st[i]) == 1), st => st[12] == (1.To(11).Count(i => st[i]) == 4) };   for (Statements statements = new Statements(0); statements.Value < 4096; statements++) { int count = 0; int falseIndex = 0; for (int i = 0; i < checks.Length; i++) { if (checks[i](statements)) count++; else falseIndex = i; } if (count == 0) Console.WriteLine($"{"All wrong:", -13}{statements}"); else if (count == 11) Console.WriteLine($"{$"Wrong at {falseIndex + 1}:", -13}{statements}"); else if (count == 12) Console.WriteLine($"{"All correct:", -13}{statements}"); } }   struct Statements { public Statements(int value) : this() { Value = value; }   public int Value { get; }   public bool this[int index] => (Value & (1 << index - 1)) != 0;   public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1);   public override string ToString() { Statements copy = this; //Cannot access 'this' in anonymous method... return string.Join(" ", from i in 1.To(12) select copy[i] ? "T" : "F"); }   }   //Extension methods static bool Implies(this bool x, bool y) => !x || y;   static IEnumerable<int> To(this int start, int end, int by = 1) { while (start <= end) { yield return start; start += by; } }   }
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.2B.2B
C++
#include <iostream> #include <stack> #include <string> #include <sstream> #include <vector>   struct var { char name; bool value; }; std::vector<var> vars;   template<typename T> T pop(std::stack<T> &s) { auto v = s.top(); s.pop(); return v; }   bool is_operator(char c) { return c == '&' || c == '|' || c == '!' || c == '^'; }   bool eval_expr(const std::string &expr) { std::stack<bool> sob; for (auto e : expr) { if (e == 'T') { sob.push(true); } else if (e == 'F') { sob.push(false); } else { auto it = std::find_if(vars.cbegin(), vars.cend(), [e](const var &v) { return v.name == e; }); if (it != vars.cend()) { sob.push(it->value); } else { int before = sob.size(); switch (e) { case '&': sob.push(pop(sob) & pop(sob)); break; case '|': sob.push(pop(sob) | pop(sob)); break; case '!': sob.push(!pop(sob)); break; case '^': sob.push(pop(sob) ^ pop(sob)); break; default: throw std::exception("Non-conformant character in expression."); } } } } if (sob.size() != 1) { throw std::exception("Stack should contain exactly one element."); } return sob.top(); }   void set_vars(int pos, const std::string &expr) { if (pos > vars.size()) { throw std::exception("Argument to set_vars can't be greater than the number of variables."); } if (pos == vars.size()) { for (auto &v : vars) { std::cout << (v.value ? "T " : "F "); } std::cout << (eval_expr(expr) ? 'T' : 'F') << '\n'; //todo implement evaluation } else { vars[pos].value = false; set_vars(pos + 1, expr); vars[pos].value = true; set_vars(pos + 1, expr); } }   /* removes whitespace and converts to upper case */ std::string process_expr(const std::string &src) { std::stringstream expr;   for (auto c : src) { if (!isspace(c)) { expr << (char)toupper(c); } }   return expr.str(); }   int main() { std::cout << "Accepts single-character variables (except for 'T' and 'F',\n"; std::cout << "which specify explicit true or false values), postfix, with\n"; std::cout << "&|!^ for and, or, not, xor, respectively; optionally\n"; std::cout << "seperated by whitespace. Just enter nothing to quit.\n";   while (true) { std::cout << "\nBoolean expression: ";   std::string input; std::getline(std::cin, input);   auto expr = process_expr(input); if (expr.length() == 0) { break; }   vars.clear(); for (auto e : expr) { if (!is_operator(e) && e != 'T' && e != 'F') { vars.push_back({ e, false }); } } std::cout << '\n'; if (vars.size() == 0) { std::cout << "No variables were entered.\n"; } else { for (auto &v : vars) { std::cout << v.name << " "; } std::cout << expr << '\n';   auto h = vars.size() * 3 + expr.length(); for (size_t i = 0; i < h; i++) { std::cout << '='; } std::cout << '\n';   set_vars(0, expr); } }   return 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
#ERRE
ERRE
PROGRAM SPIRAL   !$INTEGER   CONST RIGHT=1,UP=2,LEFT=3,DOWN=4   !$DYNAMIC DIM SPIRAL$[0,0]   PROCEDURE PRT_ULAM(N) FOR ROW=0 TO N DO FOR COL=0 TO N DO PRINT(SPIRAL$[ROW,COL];) END FOR PRINT END FOR PRINT GET(K$) FOR ROW=0 TO N DO FOR COL=0 TO N DO IF VAL(SPIRAL$[ROW,COL])<>0 THEN PRINT(" * ";) ELSE PRINT(SPIRAL$[ROW,COL];) END IF END FOR PRINT END FOR END PROCEDURE   PROCEDURE IS_PRIME(A->RES%) LOCAL N IF A=2 THEN RES%=TRUE EXIT PROCEDURE END IF IF A<=1 OR (A MOD 2=0) THEN RES%=FALSE EXIT PROCEDURE END IF MAX=SQR(A) FOR N=3 TO MAX STEP 2 DO IF (A MOD N=0) THEN RES%=FALSE EXIT PROCEDURE END IF END FOR RES%=TRUE END PROCEDURE   PROCEDURE GEN_ULAM(N,I) DIR=RIGHT J=I Y=INT(N/2) IF (N MOD 2=0) THEN X=Y-1 ELSE X=Y END IF ! shift left for even n's WHILE J<=(N*N)-1+I DO   IS_PRIME(J->RES%) IF RES% THEN SPIRAL$[Y,X]=RIGHT$(" "+STR$(J),4) ELSE SPIRAL$[Y,X]=" ---" END IF   CASE DIR OF RIGHT-> IF (X<=(N-1) AND SPIRAL$[Y-1,X]="" AND J>I) THEN DIR=UP END IF END -> UP-> IF SPIRAL$[Y,X-1]="" THEN DIR=LEFT END IF END -> LEFT-> IF (X=0) OR SPIRAL$[Y+1,X]="" THEN DIR=DOWN END IF END -> DOWN-> IF SPIRAL$[Y,X+1]="" THEN DIR=RIGHT END IF END -> END CASE   CASE DIR OF RIGHT-> X=X+1 END -> UP-> Y=Y-1 END -> LEFT-> X=X-1 END -> DOWN-> Y=Y+1 END -> END CASE J=J+1 END WHILE PRT_ULAM(N) END PROCEDURE   BEGIN N=9  !$DIM SPIRAL$[N,N] GEN_ULAM(N,1) END PROGRAM
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#XPL0
XPL0
string 0; char S; [S:= "ls"; asm { ldr r0, S bl system } ]
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#zkl
zkl
File.glob("*").sort()