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/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #BASIC256 | BASIC256 | function Sum (x, y)
Sum = x + y # using name of function
end function
function SumR (x, y)
return x + y # using Return keyword which always returns immediately
end function
print Sum (1, 2)
print SumR(2, 3) |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #Clojure | Clojure |
user=> 3
3
user=> (Math/pow *1 2)
9.0
user=> (Math/pow *2 0.5)
1.7320508075688772
|
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #Erlang | Erlang | 7> 1 + 2.
3
8> v(-1).
3
|
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #Forth | Forth | : myloop 11 1 do i . loop cr ; myloop |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #11l | 11l | F hanoi(ndisks, startPeg = 1, endPeg = 3) -> N
I ndisks
hanoi(ndisks - 1, startPeg, 6 - startPeg - endPeg)
print(‘Move disk #. from peg #. to peg #.’.format(ndisks, startPeg, endPeg))
hanoi(ndisks - 1, 6 - startPeg - endPeg, endPeg)
hanoi(ndisks' 3) |
http://rosettacode.org/wiki/Total_circles_area | Total circles area | Total circles area
You are encouraged to solve this task according to the task description, using any language you may know.
Example circles
Example circles filtered
Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal digits of precision. The area covered by two or more disks needs to be counted only once.
One point of this Task is also to compare and discuss the relative merits of various solution strategies, their performance, precision and simplicity. This means keeping both slower and faster solutions for a language (like C) is welcome.
To allow a better comparison of the different implementations, solve the problem with this standard dataset, each line contains the x and y coordinates of the centers of the disks and their radii (11 disks are fully contained inside other disks):
xc yc radius
1.6417233788 1.6121789534 0.0848270516
-1.4944608174 1.2077959613 1.1039549836
0.6110294452 -0.6907087527 0.9089162485
0.3844862411 0.2923344616 0.2375743054
-0.2495892950 -0.3832854473 1.0845181219
1.7813504266 1.6178237031 0.8162655711
-0.1985249206 -0.8343333301 0.0538864941
-1.7011985145 -0.1263820964 0.4776976918
-0.4319462812 1.4104420482 0.7886291537
0.2178372997 -0.9499557344 0.0357871187
-0.6294854565 -1.3078893852 0.7653357688
1.7952608455 0.6281269104 0.2727652452
1.4168575317 1.0683357171 1.1016025378
1.4637371396 0.9463877418 1.1846214562
-0.5263668798 1.7315156631 1.4428514068
-1.2197352481 0.9144146579 1.0727263474
-0.1389358881 0.1092805780 0.7350208828
1.5293954595 0.0030278255 1.2472867347
-0.5258728625 1.3782633069 1.3495508831
-0.1403562064 0.2437382535 1.3804956588
0.8055826339 -0.0482092025 0.3327165165
-0.6311979224 0.7184578971 0.2491045282
1.4685857879 -0.8347049536 1.3670667538
-0.6855727502 1.6465021616 1.0593087096
0.0152957411 0.0638919221 0.9771215985
The result is 21.56503660... .
Related task
Circles of given radius through two points.
See also
http://www.reddit.com/r/dailyprogrammer/comments/zff9o/9062012_challenge_96_difficult_water_droplets/
http://stackoverflow.com/a/1667789/10562
| #11l | 11l | T Circle
Float x, y, r
F (x, y, r)
.x = x
.y = y
.r = r
V circles = [
Circle(1.6417233788, 1.6121789534, 0.0848270516),
Circle(-1.4944608174, 1.2077959613, 1.1039549836),
Circle(0.6110294452, -0.6907087527, 0.9089162485),
Circle(0.3844862411, 0.2923344616, 0.2375743054),
Circle(-0.2495892950, -0.3832854473, 1.0845181219),
Circle(1.7813504266, 1.6178237031, 0.8162655711),
Circle(-0.1985249206, -0.8343333301, 0.0538864941),
Circle(-1.7011985145, -0.1263820964, 0.4776976918),
Circle(-0.4319462812, 1.4104420482, 0.7886291537),
Circle(0.2178372997, -0.9499557344, 0.0357871187),
Circle(-0.6294854565, -1.3078893852, 0.7653357688),
Circle(1.7952608455, 0.6281269104, 0.2727652452),
Circle(1.4168575317, 1.0683357171, 1.1016025378),
Circle(1.4637371396, 0.9463877418, 1.1846214562),
Circle(-0.5263668798, 1.7315156631, 1.4428514068),
Circle(-1.2197352481, 0.9144146579, 1.0727263474),
Circle(-0.1389358881, 0.1092805780, 0.7350208828),
Circle(1.5293954595, 0.0030278255, 1.2472867347),
Circle(-0.5258728625, 1.3782633069, 1.3495508831),
Circle(-0.1403562064, 0.2437382535, 1.3804956588),
Circle(0.8055826339, -0.0482092025, 0.3327165165),
Circle(-0.6311979224, 0.7184578971, 0.2491045282),
Circle(1.4685857879, -0.8347049536, 1.3670667538),
Circle(-0.6855727502, 1.6465021616, 1.0593087096),
Circle(0.0152957411, 0.0638919221, 0.9771215985)]
V x_min = min(circles.map(c -> c.x - c.r))
V x_max = max(circles.map(c -> c.x + c.r))
V y_min = min(circles.map(c -> c.y - c.r))
V y_max = max(circles.map(c -> c.y + c.r))
V box_side = 500
V dx = (x_max - x_min) / box_side
V dy = (y_max - y_min) / box_side
V count = 0
L(r) 0 .< box_side
V y = y_min + r * dy
L(c) 0 .< box_side
V x = x_min + c * dx
I any(circles.map(circle -> (@x - circle.x) ^ 2 + (@y - circle.y) ^ 2 <= (circle.r ^ 2)))
count++
print(‘Approximated area: ’(count * dx * dy)) |
http://rosettacode.org/wiki/Universal_Turing_machine | Universal Turing machine | One of the foundational mathematical constructs behind computer science
is the universal Turing Machine.
(Alan Turing introduced the idea of such a machine in 1936–1937.)
Indeed one way to definitively prove that a language
is turing-complete
is to implement a universal Turing machine in it.
Task
Simulate such a machine capable
of taking the definition of any other Turing machine and executing it.
Of course, you will not have an infinite tape,
but you should emulate this as much as is possible.
The three permissible actions on the tape are "left", "right" and "stay".
To test your universal Turing machine (and prove your programming language
is Turing complete!), you should execute the following two Turing machines
based on the following definitions.
Simple incrementer
States: q0, qf
Initial state: q0
Terminating states: qf
Permissible symbols: B, 1
Blank symbol: B
Rules:
(q0, 1, 1, right, q0)
(q0, B, 1, stay, qf)
The input for this machine should be a tape of 1 1 1
Three-state busy beaver
States: a, b, c, halt
Initial state: a
Terminating states: halt
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(a, 0, 1, right, b)
(a, 1, 1, left, c)
(b, 0, 1, left, a)
(b, 1, 1, right, b)
(c, 0, 1, left, b)
(c, 1, 1, stay, halt)
The input for this machine should be an empty tape.
Bonus:
5-state, 2-symbol probable Busy Beaver machine from Wikipedia
States: A, B, C, D, E, H
Initial state: A
Terminating states: H
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(A, 0, 1, right, B)
(A, 1, 1, left, C)
(B, 0, 1, right, C)
(B, 1, 1, right, B)
(C, 0, 1, right, D)
(C, 1, 0, left, E)
(D, 0, 1, left, A)
(D, 1, 1, left, D)
(E, 0, 1, stay, H)
(E, 1, 0, left, A)
The input for this machine should be an empty tape.
This machine runs for more than 47 millions steps.
| #CLU | CLU | % Bidirectional 'infinite' tape
tape = cluster [T: type] is make, left, right, get_cell, set_cell,
elements, get_size
rep = record[
blank: T,
loc: int,
data: array[T]
]
% Make a new tape with a given blank value and initial value
make = proc (blank: T, init: sequence[T]) returns (cvt)
data: array[T]
if sequence[T]$empty(init) then
data := array[T]$[blank]
else
data := sequence[T]$s2a(init)
end
return(rep${
blank: blank,
loc: 1,
data: data
})
end make
% Move the tape head left
left = proc (tap: cvt)
tap.loc := tap.loc - 1
if tap.loc < array[T]$low(tap.data) then
array[T]$addl(tap.data,tap.blank)
end
end left
% Move the tape head right
right = proc (tap: cvt)
tap.loc := tap.loc + 1
if tap.loc > array[T]$high(tap.data) then
array[T]$addh(tap.data,tap.blank)
end
end right
% Get the value of the current cell
get_cell = proc (tap: cvt) returns (T)
return(tap.data[tap.loc])
end get_cell
% Set the value of the current cell
set_cell = proc (tap: cvt, val: T)
tap.data[tap.loc] := val
end set_cell
% Retrieve all touched values, one by one, from left to right
elements = iter (tap: cvt) yields (T)
for v: T in array[T]$elements(tap.data) do
yield(v)
end
end elements
% Get the current size of the tape
get_size = proc (tap: cvt) returns (int)
return(array[T]$size(tap.data))
end get_size
end tape
% Turing machine state table
turing = cluster [T: type] is make, add_rule, run
where T has equal: proctype (T,T) returns (bool)
A_LEFT = 'L'
A_RIGHT = 'R'
A_STAY = 'S'
state = record[name: string, term: bool]
rule = struct[
cur_state: int,
read_sym, write_sym: T,
action: char,
next_state: int
]
rep = struct[
states: array[state],
rules: array[rule],
init_state: int
]
% Find the index of a state given its name
find_state = proc (states: array[state], name: string)
returns (int) signals (bad_state)
for i: int in array[state]$indexes(states) do
if states[i].name = name then return(i) end
end
signal bad_state
end find_state
% Make a new Turing machine given a list of states
make = proc (state_seq: sequence[string], init: string, term: sequence[string])
returns (cvt) signals (bad_state)
states: array[state] := array[state]$[]
for s: string in sequence[string]$elements(state_seq) do
array[state]$addh(states, state${name: s, term: false} )
end
init_n: int := find_state(states, init) resignal bad_state
for s: string in sequence[string]$elements(term) do
term_n: int := find_state(states, s) resignal bad_state
states[term_n].term := true
end
return(rep${states: states,
init_state: init_n,
rules: array[rule]$[]})
end make
% Add a rule to the Turing machine
add_rule = proc (tur: cvt,
in_state: string,
read_sym, write_sym: T,
action: string,
out_state: string)
signals (bad_state, bad_action)
cur_state: int := find_state(tur.states, in_state) resignal bad_state
next_state: int := find_state(tur.states, out_state) resignal bad_state
act: char
if action = "left" then act := A_LEFT
elseif action = "right" then act := A_RIGHT
elseif action = "stay" then act := A_STAY
else signal bad_action
end
array[rule]$addh(tur.rules,
rule${cur_state: cur_state,
read_sym: read_sym,
write_sym: write_sym,
action: act,
next_state: next_state})
end add_rule
% Find first matching rule
find_rule = proc (rules: array[rule], st: int, sym: T)
returns (rule) signals (no_rule)
for r: rule in array[rule]$elements(rules) do
if r.cur_state = st & r.read_sym = sym then
return(r)
end
end
signal no_rule
end find_rule
% Run the Turing machine on a given tape until it terminates
run = proc (tur: cvt, tap: tape[T]) signals (no_rule)
cur: int := tur.init_state
while ~tur.states[cur].term do
r: rule := find_rule(tur.rules, cur, tap.cell) resignal no_rule
tap.cell := r.write_sym
if r.action = A_LEFT then tape[T]$left(tap)
elseif r.action = A_RIGHT then tape[T]$right(tap)
end
cur := r.next_state
end
end run
end turing
% Simple incrementer
simple_incrementer = proc () returns (turing[char])
tc = turing[char]
t: tc := tc$make(
sequence[string]$["q0", "qf"],
"q0",
sequence[string]$["qf"]
)
tc$add_rule(t, "q0", '1', '1', "right", "q0")
tc$add_rule(t, "q0", 'B', '1', "stay", "qf")
return(t)
end simple_incrementer
% Three state beaver
three_state_beaver = proc () returns (turing[char])
tc = turing[char]
t: tc := tc$make(
sequence[string]$["a", "b", "c", "halt"],
"a",
sequence[string]$["halt"]
)
tc$add_rule(t, "a", '0', '1', "right", "b")
tc$add_rule(t, "a", '1', '1', "left", "c")
tc$add_rule(t, "b", '0', '1', "left", "a")
tc$add_rule(t, "b", '1', '1', "right", "b")
tc$add_rule(t, "c", '0', '1', "left", "b")
tc$add_rule(t, "c", '1', '1', "stay", "halt")
return(t)
end three_state_beaver
% Five state beaver
five_state_beaver = proc () returns (turing[char])
tc = turing[char]
t: tc := tc$make(
sequence[string]$["A", "B", "C", "D", "E", "H"],
"A",
sequence[string]$["H"]
)
tc$add_rule(t, "A", '0', '1', "right", "B")
tc$add_rule(t, "A", '1', '1', "left", "C")
tc$add_rule(t, "B", '0', '1', "right", "C")
tc$add_rule(t, "B", '1', '1', "right", "B")
tc$add_rule(t, "C", '0', '1', "right", "D")
tc$add_rule(t, "C", '1', '0', "left", "E")
tc$add_rule(t, "D", '0', '1', "left", "A")
tc$add_rule(t, "D", '1', '1', "left", "D")
tc$add_rule(t, "E", '0', '1', "stay", "H")
tc$add_rule(t, "E", '1', '0', "left", "A")
return(t)
end five_state_beaver
% Print the first 32 touched symbols on a tape
print_tape = proc (s: stream, t: tape[char])
n: int := 32
for c: char in tape[char]$elements(t) do
stream$putc(s, c)
n := n - 1
if n=0 then break end
end
if n=0 then
stream$puts(s, "... (length: " || int$unparse(t.size) || ")")
end
stream$putl(s, "")
end print_tape
% Run the three Turing machines and show the results
start_up = proc ()
turing_factory = proctype () returns (turing[char])
test = record[name: string, tf: turing_factory, tap: tape[char]]
stest = sequence[test]
sc = sequence[char]
tests: stest := stest$[
test${name: "Simple incrementer",
tf: simple_incrementer,
tap: tape[char]$make('B', sc$['1','1','1'])},
test${name: "Three-state busy beaver",
tf: three_state_beaver,
tap: tape[char]$make('0', sc$[])},
test${name: "Five-state probable busy beaver",
tf: five_state_beaver,
tap: tape[char]$make('0', sc$[])}]
po: stream := stream$primary_output()
for t: test in stest$elements(tests) do
stream$puts(po, t.name || ": ")
tm: turing[char] := t.tf()
turing[char]$run(tm, t.tap)
print_tape(po, t.tap)
end
end start_up |
http://rosettacode.org/wiki/Totient_function | Totient function | The totient function is also known as:
Euler's totient function
Euler's phi totient function
phi totient function
Φ function (uppercase Greek phi)
φ function (lowercase Greek phi)
Definitions (as per number theory)
The totient function:
counts the integers up to a given positive integer n that are relatively prime to n
counts the integers k in the range 1 ≤ k ≤ n for which the greatest common divisor gcd(n,k) is equal to 1
counts numbers ≤ n and prime to n
If the totient number (for N) is one less than N, then N is prime.
Task
Create a totient function and:
Find and display (1 per line) for the 1st 25 integers:
the integer (the index)
the totient number for that integer
indicate if that integer is prime
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000 (optional)
Show all output here.
Related task
Perfect totient numbers
Also see
Wikipedia: Euler's totient function.
MathWorld: totient function.
OEIS: Euler totient function phi(n).
| #APL | APL | task←{
totient ← 1+.=⍳∨⊢
prime ← totient=-∘1
⎕←'Index' 'Totient' 'Prime',(⊢⍪totient¨,[÷2]prime¨)⍳25
{⎕←'There are' (+/prime¨⍳⍵) 'primes below' ⍵}¨100 1000 10000
} |
http://rosettacode.org/wiki/Topswops | Topswops | Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is composed of reversing the first m cards where m is the value of the topmost card.
Rounds are repeated until the topmost card is the number 1 and the number of swaps is recorded.
For our example the swaps produce:
[2, 4, 1, 3] # Initial shuffle
[4, 2, 1, 3]
[3, 1, 2, 4]
[2, 1, 3, 4]
[1, 2, 3, 4]
For a total of four swaps from the initial ordering to produce the terminating case where 1 is on top.
For a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards.
Task
The task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive.
Note
Topswops is also known as Fannkuch from the German word Pfannkuchen meaning pancake.
Related tasks
Number reversal game
Sorting algorithms/Pancake sort
| #Eiffel | Eiffel |
class
TOPSWOPS
create
make
feature
make (n: INTEGER)
-- Topswop game.
local
perm, ar: ARRAY [INTEGER]
tcount, count: INTEGER
do
create perm_sol.make_empty
create solution.make_empty
across
1 |..| n as c
loop
create ar.make_filled (0, 1, c.item)
across
1 |..| c.item as d
loop
ar [d.item] := d.item
end
permute (ar, 1)
across
1 |..| perm_sol.count as e
loop
tcount := 0
from
until
perm_sol.at (e.item).at (1) = 1
loop
perm_sol.at (e.item) := reverse_array (perm_sol.at (e.item))
tcount := tcount + 1
end
if tcount > count then
count := tcount
end
end
solution.force (count, c.item)
end
end
solution: ARRAY [INTEGER]
feature {NONE}
perm_sol: ARRAY [ARRAY [INTEGER]]
reverse_array (ar: ARRAY [INTEGER]): ARRAY [INTEGER]
-- Array with 'ar[1]' elements reversed.
require
ar_not_void: ar /= Void
local
i, j: INTEGER
do
create Result.make_empty
Result.deep_copy (ar)
from
i := 1
j := ar [1]
until
i > j
loop
Result [i] := ar [j]
Result [j] := ar [i]
i := i + 1
j := j - 1
end
ensure
same_elements: across ar as a all Result.has (a.item) end
end
permute (a: ARRAY [INTEGER]; k: INTEGER)
-- All permutations of array 'a' stored in perm_sol.
require
ar_not_void: a.count >= 1
k_valid_index: k > 0
local
i, t: INTEGER
temp: ARRAY [INTEGER]
do
create temp.make_empty
if k = a.count then
across
a as ar
loop
temp.force (ar.item, temp.count + 1)
end
perm_sol.force (temp, perm_sol.count + 1)
else
from
i := k
until
i > a.count
loop
t := a [k]
a [k] := a [i]
a [i] := t
permute (a, k + 1)
t := a [k]
a [k] := a [i]
a [i] := t
i := i + 1
end
end
end
end
|
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #Autolisp | Autolisp |
(defun rad_to_deg (rad)(* 180.0 (/ rad PI)))
(defun deg_to_rad (deg)(* PI (/ deg 180.0)))
(defun asin (x)
(cond
((and(> x -1.0)(< x 1.0)) (atan (/ x (sqrt (- 1.0 (* x x))))))
((= x -1.0) (* -1.0 (/ pi 2)))
((= x 1) (/ pi 2))
)
)
(defun acos (x)
(cond
((and(>= x -1.0)(<= x 1.0)) (-(* pi 0.5) (asin x)))
)
)
(list
(list "cos PI/6" (cos (/ pi 6)) "cos 30 deg" (cos (deg_to_rad 30)))
(list "sin PI/4" (sin (/ pi 4)) "sin 45 deg" (sin (deg_to_rad 45)))
(list "tan PI/3" (tan (/ pi 3))"tan 60 deg" (tan (deg_to_rad 60)))
(list "asin 1 rad" (asin 1.0) "asin 1 rad (deg)" (rad_to_deg (asin 1.0)))
(list "acos 1/2 rad" (acos (/ 1 2.0)) "acos 1/2 rad (deg)" (rad_to_deg (acos (/ 1 2.0))))
(list "atan pi/12" (atan (/ pi 12)) "atan 15 deg" (rad_to_deg(atan(deg_to_rad 15))))
)
|
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.
From the wikipedia entry:
ask for 11 numbers to be read into a sequence S
reverse sequence S
for each item in sequence S
result := call a function to do an operation
if result overflows
alert user
else
print result
The task is to implement the algorithm:
Use the function:
f
(
x
)
=
|
x
|
0.5
+
5
x
3
{\displaystyle f(x)=|x|^{0.5}+5x^{3}}
The overflow condition is an answer of greater than 400.
The 'user alert' should not stop processing of other items of the sequence.
Print a prompt before accepting eleven, textual, numeric inputs.
You may optionally print the item as well as its associated result, but the results must be in reverse order of input.
The sequence S may be 'implied' and so not shown explicitly.
Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
| #BASIC256 | BASIC256 | dim s(11)
print 'enter 11 numbers'
for i = 0 to 10
input i + ">" , s[i]
next i
for i = 10 to 0 step -1
print "f(" + s[i] + ")=";
x = f(s[i])
if x > 400 then
print "-=< overflow >=-"
else
print x
endif
next i
end
function f(n)
return sqrt(abs(n))+5*n^3
end function |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.
From the wikipedia entry:
ask for 11 numbers to be read into a sequence S
reverse sequence S
for each item in sequence S
result := call a function to do an operation
if result overflows
alert user
else
print result
The task is to implement the algorithm:
Use the function:
f
(
x
)
=
|
x
|
0.5
+
5
x
3
{\displaystyle f(x)=|x|^{0.5}+5x^{3}}
The overflow condition is an answer of greater than 400.
The 'user alert' should not stop processing of other items of the sequence.
Print a prompt before accepting eleven, textual, numeric inputs.
You may optionally print the item as well as its associated result, but the results must be in reverse order of input.
The sequence S may be 'implied' and so not shown explicitly.
Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
| #C | C |
#include<math.h>
#include<stdio.h>
int
main ()
{
double inputs[11], check = 400, result;
int i;
printf ("\nPlease enter 11 numbers :");
for (i = 0; i < 11; i++)
{
scanf ("%lf", &inputs[i]);
}
printf ("\n\n\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :");
for (i = 10; i >= 0; i--)
{
result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);
printf ("\nf(%lf) = ");
if (result > check)
{
printf ("Overflow!");
}
else
{
printf ("%lf", result);
}
}
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.
| #Nim | Nim | import bitops, sequtils, strformat, strutils, sugar
type Bools = array[1..12, bool]
const Predicates = [1: (b: Bools) => b.len == 12,
2: (b: Bools) => b[7..12].count(true) == 3,
3: (b: Bools) => toSeq(countup(2, 12, 2)).mapIt(b[it]).count(true) == 2,
4: (b: Bools) => not b[5] or b[6] and b[7],
5: (b: Bools) => not b[2] and not b[3] and not b[4],
6: (b: Bools) => toSeq(countup(1, 12, 2)).mapIt(b[it]).count(true) == 4,
7: (b: Bools) => b[2] xor b[3],
8: (b: Bools) => not b[7] or b[5] and b[6],
9: (b: Bools) => b[1..6].count(true) == 3,
10: (b: Bools) => b[11] and b[12],
11: (b: Bools) => b[7..9].count(true) == 1,
12: (b: Bools) => b[1..11].count(true) == 4]
proc `$`(b: Bools): string =
toSeq(1..12).filterIt(b[it]).join(" ")
echo "Exacts hits:"
var bools: Bools
for n in 0..4095:
block check:
for i in 1..12: bools[i] = n.testBit(12 - i)
for i, predicate in Predicates:
if predicate(bools) != bools[i]:
break check
echo " ", bools
echo "\nNear misses:"
for n in 0..4095:
for i in 1..12: bools[i] = n.testBit(12 - i)
var count = 0
for i, predicate in Predicates:
if predicate(bools) == bools[i]: inc count
if count == 11:
for i, predicate in Predicates:
if predicate(bools) != bools[i]:
echo &" (Fails at statement {i:2}) {bools}"
break |
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.
| #Pascal | Pascal | PROGRAM TwelveStatements;
{
This program searches through the 4095 possible sets
of 12 statements for any which may be self-consistent.
}
CONST
max12b = 4095; { Largest 12 byte number. }
TYPE
statnum = 1..12; { statement numbers }
statset = set of statnum; { sets of statements }
VAR { global variables for use in main algorithm }
trialNumber: integer;
trialSet, testResults: statset;
function Convert(n: integer): statset;
{
Converts an integer into a set of statements.
For each "1" in the last 12 bits of
the integer's binary representation,
a statement number is put into the set.
}
var
i: statnum;
s: statset;
begin
s := []; { Empty set. }
for i := 12 downto 1 do begin
if (n mod 2) = 1 then s := s + [i];
n := n div 2
end;
Convert := s
end;
procedure Express(truths: statset);
{
Writes the statement number of each "truth",
with at least one space in front,
all on one line.
}
var n: statnum;
begin
for n := 1 to 12 do
if n in truths then write(n:3);
writeln
end;
function Count(truths: statset): integer;
{ Counts the statement numbers in the set. }
var
s: statnum;
i: integer;
begin
i := 0;
for s := 1 to 12 do if s in truths then i := i + 1;
Count := i
end;
function Test(truths: statset): statset;
{
Starts with a set of supposedly true statements
and checks which of the 12 statements can actually
be confirmed about the set itself.
}
var
evens, odds, confirmations: statset;
begin
evens := [2, 4, 6, 8, 10, 12];
odds := [1, 3, 5, 7, 9, 11];
{ Statement 1 is necessarily true. }
confirmations := [1];
{ Statement 2 }
if Count(truths * [7..12]) = 3
then confirmations := confirmations + [2];
{ Statement 3 }
if Count(truths * evens) = 2
then confirmations := confirmations + [3];
{ Statement 4 is true if 6 and 7 are true, or if 5 is false. }
if ([6, 7] <= truths) or not (5 in truths)
then confirmations := confirmations + [4];
{ Statement 5 }
if [2, 3, 4] <= truths
then confirmations := confirmations + [5];
{ Statement 6 }
if Count(truths * odds) = 4
then confirmations := confirmations + [6];
{ Statement 7 }
if (2 in truths) xor (3 in truths)
then confirmations := confirmations + [7];
{ Statement 8 is true if 5 and 6 are true, or if 7 is false. }
if ([5, 6] <= truths) or not (7 in truths)
then confirmations := confirmations + [8];
{ Statement 9 }
if Count(truths * [1..6]) = 3
then confirmations := confirmations + [9];
{ Statement 10 }
if [11, 12] <= truths
then confirmations := confirmations + [10];
{ Statement 11 }
if Count(truths * [7, 8, 9]) = 1
then confirmations := confirmations + [11];
{ Statement 12 }
if Count(truths - [12]) = 4
then confirmations := confirmations + [12];
Test := confirmations
end;
BEGIN { Main algorithm. }
for trialNumber := 1 to max12b do begin
trialSet := Convert(trialNumber);
testResults := Test(trialSet);
if testResults = trialSet then Express(trialSet)
end;
writeln('Done. Press ENTER.');
readln
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.
| #Liberty_BASIC | Liberty BASIC |
print
print " TRUTH TABLES"
print
print " Input a valid Boolean expression for creating the truth table "
print " Use lowercase 'and', 'or', 'xor', '(', 'not(' and ')'."
print
print " Take special care to precede closing bracket with a space."
print
print " You can use any alphanumeric variable names, but no spaces."
print " You can refer again to a variable used already."
print " Program assumes <8 variables will be used.."
print
print " eg 'A xor B and not( C or A )'"
print " or 'Too_High xor not( Fuel_Out )'"
print
[start]
input " "; expression$
if expression$ ="" then [start]
print
'used$ =""
numVariables =0 ' count of detected variable names
variableNames$ ="" ' filled with detected variable names
i =1 ' index to space-delimited word in the expression$
[parse]
m$ =word$( expression$, i, " ")
if m$ ="" then [analyse]
' is it a reserved word, or a variable name already met?
if m$ <>"and" and m$ <>"or" and m$ <>"not(" and m$ <>")" and m$ <>"xor"_
and not( instr( variableNames$, m$)) then
variableNames$ =variableNames$ +m$ +" ": numVariables =numVariables +1
end if
i =i +1
goto [parse]
[analyse]
for i =1 to numVariables
ex$ =FindReplace$( expression$, word$( variableNames$, i, " "), chr$( 64 +i), 1)
expression$ =ex$
next i
'print " "; numVariables; " variables, simplifying to "; expression$
print ,;
for j =1 to numVariables
print word$( variableNames$, j, " "),
next j
print "Result"
print
for i =0 to ( 2^numVariables) -1
print ,;
A =i mod 2: print A,
if numVariables >1 then B =int( i /2) mod 2: print B,
if numVariables >2 then C =int( i /4) mod 2: print C,
if numVariables >3 then D =int( i /4) mod 2: print D,
if numVariables >4 then E =int( i /4) mod 2: print E,
if numVariables >5 then F =int( i /4) mod 2: print F,
if numVariables >6 then G =int( i /4) mod 2: print G,
' .......................... etc
'e =eval( expression$)
if eval( expression$) <>0 then e$ ="1" else e$ ="0"
print "==> "; e$
next i
print
goto [start]
end
function FindReplace$( FindReplace$, find$, replace$, replaceAll)
if ( ( FindReplace$ <>"") and ( find$ <>"")) then
fLen = len( find$)
rLen = len( replace$)
do
fPos = instr( FindReplace$, find$, fPos)
if not( fPos) then exit function
pre$ = left$( FindReplace$, fPos -1)
post$ = mid$( FindReplace$, fPos +fLen)
FindReplace$ = pre$ +replace$ +post$
fPos = fPos +(rLen -fLen) +1
loop while ( replaceAll)
end if
end function
|
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[iCCWSpiralEast]
iCCWSpiralEast[n_Integer]:=Table[(1/2 (-1)^# ({1,-1} (Abs[#^2-t]-#)+#^2-t-Mod[#,2])&)[Round[Sqrt[t]]],{t,0,n-1}]
n=20
start=1;
pts=iCCWSpiralEast[n^2];
pts=Pick[pts,PrimeQ[start+Range[n^2]-1],True];
grid=Table[({i,j}/.(Alternatives@@pts)->"#")/.{_,_}->" ",{j,Round[n/2],-Round[n/2],-1},{i,-Round[n/2],Round[n/2],1}];
Grid[grid] |
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.]
| #Elixir | Elixir | defmodule Prime do
defp left_truncatable?(n, prime) do
func = fn i when i<=9 -> 0
i -> to_string(i) |> String.slice(1..-1) |> String.to_integer end
truncatable?(n, prime, func)
end
defp right_truncatable?(n, prime) do
truncatable?(n, prime, fn i -> div(i, 10) end)
end
defp truncatable?(n, prime, trunc_func) do
if to_string(n) |> String.match?(~r/0/),
do: false,
else: trunc_loop(trunc_func.(n), prime, trunc_func)
end
defp trunc_loop(0, _prime, _trunc_func), do: true
defp trunc_loop(n, prime, trunc_func) do
if elem(prime,n), do: trunc_loop(trunc_func.(n), prime, trunc_func), else: false
end
def eratosthenes(limit) do # descending order
Enum.to_list(2..limit) |> sieve(:math.sqrt(limit), [])
end
defp sieve([h|_]=list, max, sieved) when h>max, do: Enum.reverse(list, sieved)
defp sieve([h | t], max, sieved) do
list = for x <- t, rem(x,h)>0, do: x
sieve(list, max, [h | sieved])
end
defp prime_table(_, [], list), do: [false, false | list]
defp prime_table(n, [n|t], list), do: prime_table(n-1, t, [true|list])
defp prime_table(n, prime, list), do: prime_table(n-1, prime, [false|list])
def task(limit \\ 1000000) do
prime = eratosthenes(limit)
prime_tuple = prime_table(limit, prime, []) |> List.to_tuple
left = Enum.find(prime, fn n -> left_truncatable?(n, prime_tuple) end)
IO.puts "Largest left-truncatable prime : #{left}"
right = Enum.find(prime, fn n -> right_truncatable?(n, prime_tuple) end)
IO.puts "Largest right-truncatable prime: #{right}"
end
end
Prime.task |
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.
| #XPL0 | XPL0 | int I, Size, FD;
char C, FN(80), Array;
[I:= 0; \get file name from command line
loop [C:= ChIn(8);
if C = $20 \space\ then quit;
FN(I):= C;
I:= I+1;
];
FN(I):= 0;
Size:= IntIn(8); \get number of bytes from command line
if Size = 0 then [Text(0, "Length not found (or zero)"); exit 1];
Trap(false); \disable abort on errors
FD:= FOpen(FN, 0); \open specified file for input
FSet(FD, ^i);
OpenI(3);
if GetErr then [Text(0, "File not found"); exit 1];
Array:= Reserve(0); \64MB available if no procedures are called
for I:= 0 to Size-1 do \read specified number of bytes
[Array(I):= ChIn(3);
if GetErr then [Text(0, "File is too short"); exit 1];
]; \if end of file encountered, show error
FClose(FD);
FD:= FOpen(FN, 1); \open file by same name for output
FSet(FD, ^o);
OpenO(3);
if GetErr then [Text(0, "Output error"); exit 1];
for I:= 0 to Size-1 do ChOut(3, Array(I));
Close(3);
] |
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.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 CLEAR 29999
20 INPUT "Which file do you want to truncate?";f$
30 PRINT "Start tape to load file to truncate."
40 LOAD f$ CODE 30000
50 "Input how many bytes do you want to keep?";n
60 PRINT "Please rewind the tape and press record."
70 SAVE f$ CODE 30000,n
80 STOP |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
See also
Wikipedia article: Tree traversal.
| #ACL2 | ACL2 | (defun flatten-preorder (tree)
(if (endp tree)
nil
(append (list (first tree))
(flatten-preorder (second tree))
(flatten-preorder (third tree)))))
(defun flatten-inorder (tree)
(if (endp tree)
nil
(append (flatten-inorder (second tree))
(list (first tree))
(flatten-inorder (third tree)))))
(defun flatten-postorder (tree)
(if (endp tree)
nil
(append (flatten-postorder (second tree))
(flatten-postorder (third tree))
(list (first tree)))))
(defun flatten-level-r1 (tree level levels)
(if (endp tree)
levels
(let ((curr (cdr (assoc level levels))))
(flatten-level-r1
(second tree)
(1+ level)
(flatten-level-r1
(third tree)
(1+ level)
(put-assoc level
(append curr (list (first tree)))
levels))))))
(defun flatten-level-r2 (levels max-level)
(declare (xargs :measure (nfix (1+ max-level))))
(if (zp (1+ max-level))
nil
(append (flatten-level-r2 levels
(1- max-level))
(reverse (cdr (assoc max-level levels))))))
(defun flatten-level (tree)
(let ((levels (flatten-level-r1 tree 0 nil)))
(flatten-level-r2 levels (len levels)))) |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' Three different ways of returning a value from a function
Function Sum (x As Integer, y As Integer) As Integer
Sum = x + y '' using name of function
End Function
Function Sum2 (x As Integer, y As Integer) As Integer
Function = x + y '' using Function keyword
End Function
Function Sum3 (x As Integer, y As Integer) As Integer
Return x + y '' using Return keyword which always returns immediately
End Function
Print Sum (1, 2)
Print Sum2(2, 3)
Print Sum3(3, 4)
Sleep |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #Go | Go | package main
import (
"math"
"os"
"strconv"
"text/template"
)
func sqr(x string) string {
f, err := strconv.ParseFloat(x, 64)
if err != nil {
return "NA"
}
return strconv.FormatFloat(f*f, 'f', -1, 64)
}
func sqrt(x string) string {
f, err := strconv.ParseFloat(x, 64)
if err != nil {
return "NA"
}
return strconv.FormatFloat(math.Sqrt(f), 'f', -1, 64)
}
func main() {
f := template.FuncMap{"sqr": sqr, "sqrt": sqrt}
t := template.Must(template.New("").Funcs(f).Parse(`. = {{.}}
square: {{sqr .}}
square root: {{sqrt .}}
`))
t.Execute(os.Stdout, "3")
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #360_Assembly | 360 Assembly | * Towers of Hanoi 08/09/2015
HANOITOW CSECT
USING HANOITOW,R12 r12 : base register
LR R12,R15 establish base register
ST R14,SAVE14 save r14
BEGIN LH R2,=H'4' n <===
L R3,=C'123 ' stating position
BAL R14,MOVE r1=move(m,n)
RETURN L R14,SAVE14 restore r14
BR R14 return to caller
SAVE14 DS F static save r14
PG DC CL44'xxxxxxxxxxxx Move disc from pole X to pole Y'
NN DC F'0'
POLEX DS F current poles
POLEN DS F new poles
* .... recursive subroutine move(n, poles) [r2,r3]
MOVE LR R10,R11 save stackptr (r11) in r10 temp
LA R1,STACKLEN amount of storage required
GETMAIN RU,LV=(R1) allocate storage for stack
USING STACKDS,R11 make storage addressable
LR R11,R1 establish stack addressability
ST R14,SAVE14M save previous r14
ST R10,SAVE11M save previous r11
LR R1,R5 restore saved argument r5
BEGINM STM R2,R3,STACK push arguments to stack
ST R3,POLEX
CH R2,=H'1' if n<>1
BNE RECURSE then goto recurse
L R1,NN
LA R1,1(R1) nn=nn+1
ST R1,NN
XDECO R1,PG nn
MVC PG+33(1),POLEX+0 from
MVC PG+43(1),POLEX+1 to
XPRNT PG,44 print "move disk from to"
B RETURNM
RECURSE L R2,N n
BCTR R2,0 n=n-1
MVC POLEN+0(1),POLES+0 from
MVC POLEN+1(1),POLES+2 via
MVC POLEN+2(1),POLES+1 to
L R3,POLEN new poles
BAL R14,MOVE call move(n-1,from,via,to)
LA R2,1 n=1
MVC POLEN,POLES
L R3,POLEN new poles
BAL R14,MOVE call move(1,from,to,via)
L R2,N n
BCTR R2,0 n=n-1
MVC POLEN+0(1),POLES+2 via
MVC POLEN+1(1),POLES+1 to
MVC POLEN+2(1),POLES+0 from
L R3,POLEN new poles
BAL R14,MOVE call move(n-1,via,to,from)
RETURNM LM R2,R3,STACK pull arguments from stack
LR R1,R11 current stack
L R14,SAVE14M restore r14
L R11,SAVE11M restore r11
LA R0,STACKLEN amount of storage to free
FREEMAIN A=(R1),LV=(R0) free allocated storage
BR R14 return to caller
LTORG
DROP R12 base no longer needed
STACKDS DSECT dynamic area
SAVE14M DS F saved r14
SAVE11M DS F saved r11
STACK DS 0F stack
N DS F r2 n
POLES DS F r3 poles
STACKLEN EQU *-STACKDS
YREGS
END HANOITOW |
http://rosettacode.org/wiki/Total_circles_area | Total circles area | Total circles area
You are encouraged to solve this task according to the task description, using any language you may know.
Example circles
Example circles filtered
Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal digits of precision. The area covered by two or more disks needs to be counted only once.
One point of this Task is also to compare and discuss the relative merits of various solution strategies, their performance, precision and simplicity. This means keeping both slower and faster solutions for a language (like C) is welcome.
To allow a better comparison of the different implementations, solve the problem with this standard dataset, each line contains the x and y coordinates of the centers of the disks and their radii (11 disks are fully contained inside other disks):
xc yc radius
1.6417233788 1.6121789534 0.0848270516
-1.4944608174 1.2077959613 1.1039549836
0.6110294452 -0.6907087527 0.9089162485
0.3844862411 0.2923344616 0.2375743054
-0.2495892950 -0.3832854473 1.0845181219
1.7813504266 1.6178237031 0.8162655711
-0.1985249206 -0.8343333301 0.0538864941
-1.7011985145 -0.1263820964 0.4776976918
-0.4319462812 1.4104420482 0.7886291537
0.2178372997 -0.9499557344 0.0357871187
-0.6294854565 -1.3078893852 0.7653357688
1.7952608455 0.6281269104 0.2727652452
1.4168575317 1.0683357171 1.1016025378
1.4637371396 0.9463877418 1.1846214562
-0.5263668798 1.7315156631 1.4428514068
-1.2197352481 0.9144146579 1.0727263474
-0.1389358881 0.1092805780 0.7350208828
1.5293954595 0.0030278255 1.2472867347
-0.5258728625 1.3782633069 1.3495508831
-0.1403562064 0.2437382535 1.3804956588
0.8055826339 -0.0482092025 0.3327165165
-0.6311979224 0.7184578971 0.2491045282
1.4685857879 -0.8347049536 1.3670667538
-0.6855727502 1.6465021616 1.0593087096
0.0152957411 0.0638919221 0.9771215985
The result is 21.56503660... .
Related task
Circles of given radius through two points.
See also
http://www.reddit.com/r/dailyprogrammer/comments/zff9o/9062012_challenge_96_difficult_water_droplets/
http://stackoverflow.com/a/1667789/10562
| #Arturo | Arturo | circles: @[
@[ 1.6417233788 1.6121789534 0.0848270516]
@[neg 1.4944608174 1.2077959613 1.1039549836]
@[ 0.6110294452 neg 0.6907087527 0.9089162485]
@[ 0.3844862411 0.2923344616 0.2375743054]
@[neg 0.2495892950 neg 0.3832854473 1.0845181219]
@[ 1.7813504266 1.6178237031 0.8162655711]
@[neg 0.1985249206 neg 0.8343333301 0.0538864941]
@[neg 1.7011985145 neg 0.1263820964 0.4776976918]
@[neg 0.4319462812 1.4104420482 0.7886291537]
@[ 0.2178372997 neg 0.9499557344 0.0357871187]
@[neg 0.6294854565 neg 1.3078893852 0.7653357688]
@[ 1.7952608455 0.6281269104 0.2727652452]
@[ 1.4168575317 1.0683357171 1.1016025378]
@[ 1.4637371396 0.9463877418 1.1846214562]
@[neg 0.5263668798 1.7315156631 1.4428514068]
@[neg 1.2197352481 0.9144146579 1.0727263474]
@[neg 0.1389358881 0.1092805780 0.7350208828]
@[ 1.5293954595 0.0030278255 1.2472867347]
@[neg 0.5258728625 1.3782633069 1.3495508831]
@[neg 0.1403562064 0.2437382535 1.3804956588]
@[ 0.8055826339 neg 0.0482092025 0.3327165165]
@[neg 0.6311979224 0.7184578971 0.2491045282]
@[ 1.4685857879 neg 0.8347049536 1.3670667538]
@[neg 0.6855727502 1.6465021616 1.0593087096]
@[ 0.0152957411 0.0638919221 0.9771215985]
]
xMin: min map circles 'c -> c\0 - c\2
xMax: max map circles 'c -> c\0 + c\2
yMin: min map circles 'c -> c\1 - c\2
yMax: max map circles 'c -> c\1 + c\2
boxSide: 500
dx: (xMax - xMin) / boxSide
dy: (yMax - yMin) / boxSide
count: 0
loop 0..dec boxSide 'r [
y: yMin + r * dy
loop 0..dec boxSide 'c [
x: xMin + c * dx
loop circles 'circle [
if (add (x - first circle)*(x - first circle) (y - circle\1)*(y - circle\1)) =< (last circle)*(last circle) [
count: count + 1
break
]
]
]
]
print ["Approximated area: " count * dx * dy] |
http://rosettacode.org/wiki/Universal_Turing_machine | Universal Turing machine | One of the foundational mathematical constructs behind computer science
is the universal Turing Machine.
(Alan Turing introduced the idea of such a machine in 1936–1937.)
Indeed one way to definitively prove that a language
is turing-complete
is to implement a universal Turing machine in it.
Task
Simulate such a machine capable
of taking the definition of any other Turing machine and executing it.
Of course, you will not have an infinite tape,
but you should emulate this as much as is possible.
The three permissible actions on the tape are "left", "right" and "stay".
To test your universal Turing machine (and prove your programming language
is Turing complete!), you should execute the following two Turing machines
based on the following definitions.
Simple incrementer
States: q0, qf
Initial state: q0
Terminating states: qf
Permissible symbols: B, 1
Blank symbol: B
Rules:
(q0, 1, 1, right, q0)
(q0, B, 1, stay, qf)
The input for this machine should be a tape of 1 1 1
Three-state busy beaver
States: a, b, c, halt
Initial state: a
Terminating states: halt
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(a, 0, 1, right, b)
(a, 1, 1, left, c)
(b, 0, 1, left, a)
(b, 1, 1, right, b)
(c, 0, 1, left, b)
(c, 1, 1, stay, halt)
The input for this machine should be an empty tape.
Bonus:
5-state, 2-symbol probable Busy Beaver machine from Wikipedia
States: A, B, C, D, E, H
Initial state: A
Terminating states: H
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(A, 0, 1, right, B)
(A, 1, 1, left, C)
(B, 0, 1, right, C)
(B, 1, 1, right, B)
(C, 0, 1, right, D)
(C, 1, 0, left, E)
(D, 0, 1, left, A)
(D, 1, 1, left, D)
(E, 0, 1, stay, H)
(E, 1, 0, left, A)
The input for this machine should be an empty tape.
This machine runs for more than 47 millions steps.
| #Common_Lisp | Common Lisp | (defun turing (initial terminal blank rules tape &optional (verbose NIL))
(labels ((combine (front back)
(if front
(combine (cdr front) (cons (car front) back))
back))
(update-tape (old-front old-back new-content move)
(cond ((eq move 'right)
(list (cons new-content old-front)
(cdr old-back)))
((eq move 'left)
(list (cdr old-front)
(list* (car old-front) new-content (cdr old-back))))
(T (list old-front
(cons new-content (cdr old-back))))))
(show-tape (front back)
(format T "~{~a~}[~a]~{~a~}~%"
(nreverse (subseq front 0 (min 10 (length front))))
(or (car back) blank)
(subseq (cdr back) 0 (min 10 (length (cdr back)))))))
(loop for back = tape then new-back
for front = '() then new-front
for state = initial then new-state
for content = (or (car back) blank)
for (new-state new-content move) = (gethash (cons state content) rules)
for (new-front new-back) = (update-tape front back new-content move)
until (equal state terminal)
do (when verbose
(show-tape front back))
finally (progn
(when verbose
(show-tape front back))
(return (combine front back)))))) |
http://rosettacode.org/wiki/Totient_function | Totient function | The totient function is also known as:
Euler's totient function
Euler's phi totient function
phi totient function
Φ function (uppercase Greek phi)
φ function (lowercase Greek phi)
Definitions (as per number theory)
The totient function:
counts the integers up to a given positive integer n that are relatively prime to n
counts the integers k in the range 1 ≤ k ≤ n for which the greatest common divisor gcd(n,k) is equal to 1
counts numbers ≤ n and prime to n
If the totient number (for N) is one less than N, then N is prime.
Task
Create a totient function and:
Find and display (1 per line) for the 1st 25 integers:
the integer (the index)
the totient number for that integer
indicate if that integer is prime
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000 (optional)
Show all output here.
Related task
Perfect totient numbers
Also see
Wikipedia: Euler's totient function.
MathWorld: totient function.
OEIS: Euler totient function phi(n).
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI or android with termux */
/* program totient.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ MAXI, 25
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessNumber: .asciz " number @ totient @ @ \n"
szCarriageReturn: .asciz "\n"
szMessPrime: .asciz " is prime."
szMessSpace: .asciz " "
szMessCounterPrime: .asciz "Number of primes to @ : @ \n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main:
mov r4,#1 @ start number
1:
mov r0,r4
bl totient @ compute totient
mov r5,r0
mov r0,r4
bl isPrime @ control if number is prime
mov r6,r0
mov r0,r4 @ display result
ldr r1,iAdrsZoneConv
bl conversion10 @ call décimal conversion
ldr r0,iAdrszMessNumber
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
mov r7,r0
mov r0,r5
ldr r1,iAdrsZoneConv
bl conversion10 @ call décimal conversion
mov r0,r7
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
mov r7,r0
cmp r6,#1
ldreq r1,iAdrszMessPrime
ldrne r1,iAdrszMessSpace
mov r0,r7
bl strInsertAtCharInc
bl affichageMess @ display message
add r4,r4,#1 @ increment number
cmp r4,#MAXI @ maxi ?
ble 1b @ and loop
mov r4,#2 @ first number
mov r5,#0 @ prime counter
ldr r6,iCst1000 @ load constantes
ldr r7,iCst10000
ldr r8,iCst100000
2:
mov r0,r4
bl isPrime
cmp r0,#0
beq 3f
add r5,r5,#1
3:
add r4,r4,#1
cmp r4,#100
bne 4f
mov r0,#100
mov r1,r5
bl displayCounter
b 7f
4:
cmp r4,r6 @ 1000
bne 5f
mov r0,r6
mov r1,r5
bl displayCounter
b 7f
5:
cmp r4,r7 @ 10000
bne 6f
mov r0,r7
mov r1,r5
bl displayCounter
b 7f
6:
cmp r4,r8 @ 100000
bne 7f
mov r0,r8
mov r1,r5
bl displayCounter
7:
cmp r4,r8
ble 2b @ and loop
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsZoneConv: .int sZoneConv
iAdrszMessNumber: .int szMessNumber
iAdrszMessCounterPrime: .int szMessCounterPrime
iAdrszMessPrime: .int szMessPrime
iAdrszMessSpace: .int szMessSpace
iCst1000: .int 1000
iCst10000: .int 10000
iCst100000: .int 100000
/******************************************************************/
/* display counter */
/******************************************************************/
/* r0 contains limit */
/* r1 contains counter */
displayCounter:
push {r1-r3,lr} @ save registers
mov r2,r1
ldr r1,iAdrsZoneConv
bl conversion10 @ call décimal conversion
ldr r0,iAdrszMessCounterPrime
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
mov r3,r0
mov r0,r2
ldr r1,iAdrsZoneConv
bl conversion10 @ call décimal conversion
mov r0,r3
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
bl affichageMess
100:
pop {r1-r3,pc} @ restaur registers
/******************************************************************/
/* compute totient of number */
/******************************************************************/
/* r0 contains number */
totient:
push {r1-r5,lr} @ save registers
mov r4,r0 @ totient
mov r5,r0 @ save number
mov r1,#0 @ for first divisor
1: @ begin loop
mul r3,r1,r1 @ compute square
cmp r3,r5 @ compare number
bgt 4f @ end
add r1,r1,#2 @ next divisor
mov r0,r5
bl division
cmp r3,#0 @ remainder null ?
bne 3f
2: @ begin loop 2
mov r0,r5
bl division
cmp r3,#0
moveq r5,r2 @ new value = quotient
beq 2b
mov r0,r4 @ totient
bl division
sub r4,r4,r2 @ compute new totient
3:
cmp r1,#2 @ first divisor ?
moveq r1,#1 @ divisor = 1
b 1b @ and loop
4:
cmp r5,#1 @ final value > 1
ble 5f
mov r0,r4 @ totient
mov r1,r5 @ divide by value
bl division
sub r4,r4,r2 @ compute new totient
5:
mov r0,r4
100:
pop {r1-r5,pc} @ restaur registers
/***************************************************/
/* check if a number is prime */
/***************************************************/
/* r0 contains the number */
/* r0 return 1 if prime 0 else */
@2147483647
@4294967297
@131071
isPrime:
push {r1-r6,lr} @ save registers
cmp r0,#0
beq 90f
cmp r0,#17
bhi 1f
cmp r0,#3
bls 80f @ for 1,2,3 return prime
cmp r0,#5
beq 80f @ for 5 return prime
cmp r0,#7
beq 80f @ for 7 return prime
cmp r0,#11
beq 80f @ for 11 return prime
cmp r0,#13
beq 80f @ for 13 return prime
cmp r0,#17
beq 80f @ for 17 return prime
1:
tst r0,#1 @ even ?
beq 90f @ yes -> not prime
mov r2,r0 @ save number
sub r1,r0,#1 @ exposant n - 1
mov r0,#3 @ base
bl moduloPuR32 @ compute base power n - 1 modulo n
cmp r0,#1
bne 90f @ if <> 1 -> not prime
mov r0,#5
bl moduloPuR32
cmp r0,#1
bne 90f
mov r0,#7
bl moduloPuR32
cmp r0,#1
bne 90f
mov r0,#11
bl moduloPuR32
cmp r0,#1
bne 90f
mov r0,#13
bl moduloPuR32
cmp r0,#1
bne 90f
mov r0,#17
bl moduloPuR32
cmp r0,#1
bne 90f
80:
mov r0,#1 @ is prime
b 100f
90:
mov r0,#0 @ no prime
100: @ fin standard de la fonction
pop {r1-r6,lr} @ restaur des registres
bx lr @ retour de la fonction en utilisant lr
/********************************************************/
/* Calcul modulo de b puissance e modulo m */
/* Exemple 4 puissance 13 modulo 497 = 445 */
/* */
/********************************************************/
/* r0 nombre */
/* r1 exposant */
/* r2 modulo */
/* r0 return result */
moduloPuR32:
push {r1-r7,lr} @ save registers
cmp r0,#0 @ verif <> zero
beq 100f
cmp r2,#0 @ verif <> zero
beq 100f @ TODO: vérifier les cas erreur
1:
mov r4,r2 @ save modulo
mov r5,r1 @ save exposant
mov r6,r0 @ save base
mov r3,#1 @ start result
mov r1,#0 @ division de r0,r1 par r2
bl division32R
mov r6,r2 @ base <- remainder
2:
tst r5,#1 @ exposant even or odd
beq 3f
umull r0,r1,r6,r3
mov r2,r4
bl division32R
mov r3,r2 @ result <- remainder
3:
umull r0,r1,r6,r6
mov r2,r4
bl division32R
mov r6,r2 @ base <- remainder
lsr r5,#1 @ left shift 1 bit
cmp r5,#0 @ end ?
bne 2b
mov r0,r3
100: @ fin standard de la fonction
pop {r1-r7,lr} @ restaur des registres
bx lr @ retour de la fonction en utilisant lr
/***************************************************/
/* division number 64 bits in 2 registers by number 32 bits */
/***************************************************/
/* r0 contains lower part dividende */
/* r1 contains upper part dividende */
/* r2 contains divisor */
/* r0 return lower part quotient */
/* r1 return upper part quotient */
/* r2 return remainder */
division32R:
push {r3-r9,lr} @ save registers
mov r6,#0 @ init upper upper part remainder !!
mov r7,r1 @ init upper part remainder with upper part dividende
mov r8,r0 @ init lower part remainder with lower part dividende
mov r9,#0 @ upper part quotient
mov r4,#0 @ lower part quotient
mov r5,#32 @ bits number
1: @ begin loop
lsl r6,#1 @ shift upper upper part remainder
lsls r7,#1 @ shift upper part remainder
orrcs r6,#1
lsls r8,#1 @ shift lower part remainder
orrcs r7,#1
lsls r4,#1 @ shift lower part quotient
lsl r9,#1 @ shift upper part quotient
orrcs r9,#1
@ divisor sustract upper part remainder
subs r7,r2
sbcs r6,#0 @ and substract carry
bmi 2f @ négative ?
@ positive or equal
orr r4,#1 @ 1 -> right bit quotient
b 3f
2: @ negative
orr r4,#0 @ 0 -> right bit quotient
adds r7,r2 @ and restaur remainder
adc r6,#0
3:
subs r5,#1 @ decrement bit size
bgt 1b @ end ?
mov r0,r4 @ lower part quotient
mov r1,r9 @ upper part quotient
mov r2,r7 @ remainder
100: @ function end
pop {r3-r9,lr} @ restaur registers
bx lr
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
http://rosettacode.org/wiki/Topswops | Topswops | Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is composed of reversing the first m cards where m is the value of the topmost card.
Rounds are repeated until the topmost card is the number 1 and the number of swaps is recorded.
For our example the swaps produce:
[2, 4, 1, 3] # Initial shuffle
[4, 2, 1, 3]
[3, 1, 2, 4]
[2, 1, 3, 4]
[1, 2, 3, 4]
For a total of four swaps from the initial ordering to produce the terminating case where 1 is on top.
For a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards.
Task
The task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive.
Note
Topswops is also known as Fannkuch from the German word Pfannkuchen meaning pancake.
Related tasks
Number reversal game
Sorting algorithms/Pancake sort
| #Elixir | Elixir | defmodule Topswops do
def get_1_first( [1 | _t] ), do: 0
def get_1_first( list ), do: 1 + get_1_first( swap(list) )
defp swap( [n | _t]=list ) do
{swaps, remains} = Enum.split( list, n )
Enum.reverse( swaps, remains )
end
def task do
IO.puts "N\ttopswaps"
Enum.map(1..10, fn n -> {n, permute(Enum.to_list(1..n))} end)
|> Enum.map(fn {n, n_permutations} -> {n, get_1_first_many(n_permutations)} end)
|> Enum.map(fn {n, n_swops} -> {n, Enum.max(n_swops)} end)
|> Enum.each(fn {n, max} -> IO.puts "#{n}\t#{max}" end)
end
def get_1_first_many( n_permutations ), do: (for x <- n_permutations, do: get_1_first(x))
defp permute([]), do: [[]]
defp permute(list), do: for x <- list, y <- permute(list -- [x]), do: [x|y]
end
Topswops.task |
http://rosettacode.org/wiki/Topswops | Topswops | Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is composed of reversing the first m cards where m is the value of the topmost card.
Rounds are repeated until the topmost card is the number 1 and the number of swaps is recorded.
For our example the swaps produce:
[2, 4, 1, 3] # Initial shuffle
[4, 2, 1, 3]
[3, 1, 2, 4]
[2, 1, 3, 4]
[1, 2, 3, 4]
For a total of four swaps from the initial ordering to produce the terminating case where 1 is on top.
For a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards.
Task
The task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive.
Note
Topswops is also known as Fannkuch from the German word Pfannkuchen meaning pancake.
Related tasks
Number reversal game
Sorting algorithms/Pancake sort
| #Erlang | Erlang |
-module( topswops ).
-export( [get_1_first/1, swap/1, task/0] ).
get_1_first( [1 | _T] ) -> 0;
get_1_first( List ) -> 1 + get_1_first( swap(List) ).
swap( [N | _T]=List ) ->
{Swaps, Remains} = lists:split( N, List ),
lists:reverse( Swaps ) ++ Remains.
task() ->
Permutations = [{X, permute:permute(lists:seq(1, X))} || X <- lists:seq(1, 10)],
Swops = [{N, get_1_first_many(N_permutations)} || {N, N_permutations} <- Permutations],
Topswops = [{N, lists:max(N_swops)} || {N, N_swops} <- Swops],
io:fwrite( "N topswaps~n" ),
[io:fwrite("~p ~p~n", [N, Max]) || {N, Max} <- Topswops].
get_1_first_many( N_permutations ) -> [get_1_first(X) || X <- N_permutations].
|
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #AWK | AWK | # tan(x) = tangent of x
function tan(x) {
return sin(x) / cos(x)
}
# asin(y) = arcsine of y, domain [-1, 1], range [-pi/2, pi/2]
function asin(y) {
return atan2(y, sqrt(1 - y * y))
}
# acos(x) = arccosine of x, domain [-1, 1], range [0, pi]
function acos(x) {
return atan2(sqrt(1 - x * x), x)
}
# atan(y) = arctangent of y, range (-pi/2, pi/2)
function atan(y) {
return atan2(y, 1)
}
BEGIN {
pi = atan2(0, -1)
degrees = pi / 180
print "Using radians:"
print " sin(-pi / 6) =", sin(-pi / 6)
print " cos(3 * pi / 4) =", cos(3 * pi / 4)
print " tan(pi / 3) =", tan(pi / 3)
print " asin(-1 / 2) =", asin(-1 / 2)
print " acos(-sqrt(2) / 2) =", acos(-sqrt(2) / 2)
print " atan(sqrt(3)) =", atan(sqrt(3))
print "Using degrees:"
print " sin(-30) =", sin(-30 * degrees)
print " cos(135) =", cos(135 * degrees)
print " tan(60) =", tan(60 * degrees)
print " asin(-1 / 2) =", asin(-1 / 2) / degrees
print " acos(-sqrt(2) / 2) =", acos(-sqrt(2) / 2) / degrees
print " atan(sqrt(3)) =", atan(sqrt(3)) / degrees
} |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.
From the wikipedia entry:
ask for 11 numbers to be read into a sequence S
reverse sequence S
for each item in sequence S
result := call a function to do an operation
if result overflows
alert user
else
print result
The task is to implement the algorithm:
Use the function:
f
(
x
)
=
|
x
|
0.5
+
5
x
3
{\displaystyle f(x)=|x|^{0.5}+5x^{3}}
The overflow condition is an answer of greater than 400.
The 'user alert' should not stop processing of other items of the sequence.
Print a prompt before accepting eleven, textual, numeric inputs.
You may optionally print the item as well as its associated result, but the results must be in reverse order of input.
The sequence S may be 'implied' and so not shown explicitly.
Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
| #C.2B.2B | C++ |
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <iomanip>
int main( ) {
std::vector<double> input( 11 ) , results( 11 ) ;
std::cout << "Please enter 11 numbers!\n" ;
for ( int i = 0 ; i < input.size( ) ; i++ )
std::cin >> input[i];
std::transform( input.begin( ) , input.end( ) , results.begin( ) ,
[ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ;
for ( int i = 10 ; i > -1 ; i-- ) {
std::cout << "f( " << std::setw( 3 ) << input[ i ] << " ) : " ;
if ( results[ i ] > 400 )
std::cout << "too large!" ;
else
std::cout << results[ i ] << " !" ;
std::cout << std::endl ;
}
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.
| #Perl | Perl | use List::Util 'sum';
my @condition = (
sub { 0 }, # dummy sub for index 0
sub { 13==@_ },
sub { 3==sum @_[7..12] },
sub { 2==sum @_[2,4,6,8,10,12] },
sub { $_[5] ? ($_[6] and $_[7]) : 1 },
sub { !$_[2] and !$_[3] and !$_[4] },
sub { 4==sum @_[1,3,5,7,9,11] },
sub { $_[2]==1-$_[3] },
sub { $_[7] ? ($_[5] and $_[6]) : 1 },
sub { 3==sum @_[1..6] },
sub { 2==sum @_[11..12] },
sub { 1==sum @_[7,8,9] },
sub { 4==sum @_[1..11] },
);
sub miss {
return grep { $condition[$_]->(@_) != $_[$_] } 1..12;
}
for (0..2**12-1) {
my @truth = split //, sprintf "0%012b", $_;
my @no = miss @truth;
print "Solution: true statements are ", join( " ", grep { $truth[$_] } 1..12), "\n" if 0 == @no;
print "1 miss (",$no[0],"): true statements are ", join( " ", grep { $truth[$_] } 1..12), "\n" if 1 == @no;
}
|
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | VariableNames[data_] := Module[ {TokenRemoved},
TokenRemoved = StringSplit[data,{"~And~","~Or~","~Xor~","!","(",")"}];
Union[Select[Map[StringTrim,TokenRemoved] , Not[StringMatchQ[#,""]]&]]
]
TruthTable[BooleanEquation_] := Module[ {TestDataSet},
TestDataSet = MapThread[Rule,{ToExpression@VariableNames[BooleanEquation],#}]&/@
Tuples[{False,True}, Length[VariableNames[BooleanEquation]]];
Join[List[Flatten[{VariableNames[BooleanEquation],BooleanEquation}]],
Flatten[{#/.Rule[x_,y_] -> y,ReplaceAll[ToExpression[BooleanEquation],#]}]&/@TestDataSet]//Grid
] |
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
| #Nim | Nim | import strutils
const N = 51 # Grid width and height.
type
Vec2 = tuple[x, y: int]
Grid = array[N, array[N, string]]
const Deltas: array[4, Vec2] = [(0, 1), (-1, 0), (0, -1), (1, 0)]
proc `+`(v1, v2: Vec2): Vec2 =
## Vector addition.
(v1.x + v2.x, v1.y + v2.y)
proc isPrime(n: Positive): bool =
## Check if a number is prime.
if n == 1: return false
if (n and 1) == 0: return n == 2
if (n mod 3) == 0: return n == 3
var delta = 2
var d = 5
while d * d <= n:
if n mod d == 0: return false
inc d, delta
delta = 6 - delta
return true
proc fill(grid: var Grid; start: Positive = 1) =
## Fill the grid using Ulam algorithm.
template isEmpty(pos: Vec2): bool = grid[pos.x][pos.y].len == 0
# Fill the grid with successive numbers (as strings).
var pos: Vec2 = (N div 2, N div 2)
grid[pos.x][pos.y] = $start
var currIdx = 3
for n in (start + 1)..<(start + N * N):
let nextIdx = (currIdx + 1) and 3
var nextPos = pos + Deltas[nextIdx]
if nextPos.isEmpty():
# Direction change is OK.
currIdx = nextIdx
else:
# Continue in same direction.
nextPos = pos + Deltas[currIdx]
pos = move(nextPos)
grid[pos.x][pos.y] = $n
# Replace the values with a symbol (if prime) or a space (if composite).
for row in 0..<N:
for col in 0..<N:
grid[row][col] = if grid[row][col].parseInt().isPrime(): "• " else: " "
var grid: Grid
grid.fill()
for row in grid:
echo row.join() |
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.]
| #Factor | Factor | USING: formatting fry grouping.extras kernel literals math
math.parser math.primes sequences ;
IN: rosetta-code.truncatable-primes
CONSTANT: primes $[ 1,000,000 primes-upto reverse ]
: number>digits ( n -- B{} ) number>string string>digits ;
: no-zeros? ( seq -- ? ) [ zero? not ] all? ;
: all-prime? ( seq -- ? ) [ prime? ] all? ;
: truncate ( seq quot -- seq' ) call( seq -- seq' )
[ 10 digits>integer ] map ;
: truncate-right ( seq -- seq' ) [ head-clump ] truncate ;
: truncate-left ( seq -- seq' ) [ tail-clump ] truncate ;
: truncatable-prime? ( n quot -- ? ) [ number>digits ] dip
'[ @ all-prime? ] [ no-zeros? ] bi and ; inline
: right-truncatable-prime? ( n -- ? ) [ truncate-right ]
truncatable-prime? ;
: left-truncatable-prime? ( n -- ? ) [ truncate-left ]
truncatable-prime? ;
: find-truncatable-primes ( -- ltp rtp )
primes [ [ left-truncatable-prime? ] find nip ]
[ [ right-truncatable-prime? ] find nip ] bi ;
: main ( -- ) find-truncatable-primes
"Left: %d\nRight: %d\n" printf ;
MAIN: main |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
See also
Wikipedia article: Tree traversal.
| #Action.21 | Action! | SET EndProg=* |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #Haskell | Haskell |
Prelude> [1..10]
[1,2,3,4,5,6,7,8,9,10]
Prelude> map (^2) it
[1,4,9,16,25,36,49,64,81,100]
|
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #J | J | example=: *:, %: NB. *: is square, %: is square root
example 3
9 1.73205 |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #jq | jq | julia> 3
3
julia> ans * ans, ans - 1
(9, 2) |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #Julia | Julia | julia> 3
3
julia> ans * ans, ans - 1
(9, 2) |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #Kotlin | Kotlin | // version 1.1.2
fun main(args: Array<String>) {
3.let {
println(it)
println(it * it)
println(Math.sqrt(it.toDouble()))
}
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #8080_Assembly | 8080 Assembly | org 100h
lhld 6 ; Top of CP/M usable memory
sphl ; Put the stack there
lxi b,0401h ; Set up first arguments to move()
lxi d,0203h
call move ; move(4, 1, 2, 3)
rst 0 ; quit program
;;; Move B disks from C via D to E.
move: dcr b ; One fewer disk in next iteration
jz mvout ; If this was the last disk, print move and stop
push b ; Otherwise, save registers,
push d
mov a,d ; First recursive call
mov d,e
mov e,a
call move ; move(B-1, C, E, D)
pop d ; Restore registers
pop b
call mvout ; Print current move
mov a,c ; Second recursive call
mov c,d
mov d,a
jmp move ; move(B-1, D, C, E) - tail call optimization
;;; Print move, saving registers.
mvout: push b ; Save registers on stack
push d
mov a,c ; Store 'from' as ASCII digit in 'from' space
adi '0'
sta out1
mov a,e ; Store 'to' as ASCII digit in 'to' space
adi '0'
sta out2
lxi d,outstr
mvi c,9 ; CP/M call to print the string
call 5
pop d ; Restore register contents
pop b
ret
;;; Move output with placeholder for pole numbers
outstr: db 'Move disk from pole '
out1: db '* to pole '
out2: db '*',13,10,'$' |
http://rosettacode.org/wiki/Total_circles_area | Total circles area | Total circles area
You are encouraged to solve this task according to the task description, using any language you may know.
Example circles
Example circles filtered
Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal digits of precision. The area covered by two or more disks needs to be counted only once.
One point of this Task is also to compare and discuss the relative merits of various solution strategies, their performance, precision and simplicity. This means keeping both slower and faster solutions for a language (like C) is welcome.
To allow a better comparison of the different implementations, solve the problem with this standard dataset, each line contains the x and y coordinates of the centers of the disks and their radii (11 disks are fully contained inside other disks):
xc yc radius
1.6417233788 1.6121789534 0.0848270516
-1.4944608174 1.2077959613 1.1039549836
0.6110294452 -0.6907087527 0.9089162485
0.3844862411 0.2923344616 0.2375743054
-0.2495892950 -0.3832854473 1.0845181219
1.7813504266 1.6178237031 0.8162655711
-0.1985249206 -0.8343333301 0.0538864941
-1.7011985145 -0.1263820964 0.4776976918
-0.4319462812 1.4104420482 0.7886291537
0.2178372997 -0.9499557344 0.0357871187
-0.6294854565 -1.3078893852 0.7653357688
1.7952608455 0.6281269104 0.2727652452
1.4168575317 1.0683357171 1.1016025378
1.4637371396 0.9463877418 1.1846214562
-0.5263668798 1.7315156631 1.4428514068
-1.2197352481 0.9144146579 1.0727263474
-0.1389358881 0.1092805780 0.7350208828
1.5293954595 0.0030278255 1.2472867347
-0.5258728625 1.3782633069 1.3495508831
-0.1403562064 0.2437382535 1.3804956588
0.8055826339 -0.0482092025 0.3327165165
-0.6311979224 0.7184578971 0.2491045282
1.4685857879 -0.8347049536 1.3670667538
-0.6855727502 1.6465021616 1.0593087096
0.0152957411 0.0638919221 0.9771215985
The result is 21.56503660... .
Related task
Circles of given radius through two points.
See also
http://www.reddit.com/r/dailyprogrammer/comments/zff9o/9062012_challenge_96_difficult_water_droplets/
http://stackoverflow.com/a/1667789/10562
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <stdbool.h>
typedef double Fp;
typedef struct { Fp x, y, r; } Circle;
Circle circles[] = {
{ 1.6417233788, 1.6121789534, 0.0848270516},
{-1.4944608174, 1.2077959613, 1.1039549836},
{ 0.6110294452, -0.6907087527, 0.9089162485},
{ 0.3844862411, 0.2923344616, 0.2375743054},
{-0.2495892950, -0.3832854473, 1.0845181219},
{ 1.7813504266, 1.6178237031, 0.8162655711},
{-0.1985249206, -0.8343333301, 0.0538864941},
{-1.7011985145, -0.1263820964, 0.4776976918},
{-0.4319462812, 1.4104420482, 0.7886291537},
{ 0.2178372997, -0.9499557344, 0.0357871187},
{-0.6294854565, -1.3078893852, 0.7653357688},
{ 1.7952608455, 0.6281269104, 0.2727652452},
{ 1.4168575317, 1.0683357171, 1.1016025378},
{ 1.4637371396, 0.9463877418, 1.1846214562},
{-0.5263668798, 1.7315156631, 1.4428514068},
{-1.2197352481, 0.9144146579, 1.0727263474},
{-0.1389358881, 0.1092805780, 0.7350208828},
{ 1.5293954595, 0.0030278255, 1.2472867347},
{-0.5258728625, 1.3782633069, 1.3495508831},
{-0.1403562064, 0.2437382535, 1.3804956588},
{ 0.8055826339, -0.0482092025, 0.3327165165},
{-0.6311979224, 0.7184578971, 0.2491045282},
{ 1.4685857879, -0.8347049536, 1.3670667538},
{-0.6855727502, 1.6465021616, 1.0593087096},
{ 0.0152957411, 0.0638919221, 0.9771215985}};
const size_t n_circles = sizeof(circles) / sizeof(Circle);
static inline Fp min(const Fp a, const Fp b) { return a <= b ? a : b; }
static inline Fp max(const Fp a, const Fp b) { return a >= b ? a : b; }
static inline Fp sq(const Fp a) { return a * a; }
// Return an uniform random value in [a, b).
static inline double uniform(const double a, const double b) {
const double r01 = rand() / (double)RAND_MAX;
return a + (b - a) * r01;
}
static inline bool is_inside_circles(const Fp x, const Fp y) {
for (size_t i = 0; i < n_circles; i++)
if (sq(x - circles[i].x) + sq(y - circles[i].y) < circles[i].r)
return true;
return false;
}
int main() {
// Initialize the bounding box (bbox) of the circles.
Fp x_min = INFINITY, x_max = -INFINITY;
Fp y_min = x_min, y_max = x_max;
// Compute the bounding box of the circles.
for (size_t i = 0; i < n_circles; i++) {
Circle *c = &circles[i];
x_min = min(x_min, c->x - c->r);
x_max = max(x_max, c->x + c->r);
y_min = min(y_min, c->y - c->r);
y_max = max(y_max, c->y + c->r);
c->r *= c->r; // Square the radii to speed up testing.
}
const Fp bbox_area = (x_max - x_min) * (y_max - y_min);
// Montecarlo sampling.
srand(time(0));
size_t to_try = 1U << 16;
size_t n_tries = 0;
size_t n_hits = 0;
while (true) {
n_hits += is_inside_circles(uniform(x_min, x_max),
uniform(y_min, y_max));
n_tries++;
if (n_tries == to_try) {
const Fp area = bbox_area * n_hits / n_tries;
const Fp r = (Fp)n_hits / n_tries;
const Fp s = area * sqrt(r * (1 - r) / n_tries);
printf("%.4f +/- %.4f (%zd samples)\n", area, s, n_tries);
if (s * 3 <= 1e-3) // Stop at 3 sigmas.
break;
to_try *= 2;
}
}
return 0;
} |
http://rosettacode.org/wiki/Universal_Turing_machine | Universal Turing machine | One of the foundational mathematical constructs behind computer science
is the universal Turing Machine.
(Alan Turing introduced the idea of such a machine in 1936–1937.)
Indeed one way to definitively prove that a language
is turing-complete
is to implement a universal Turing machine in it.
Task
Simulate such a machine capable
of taking the definition of any other Turing machine and executing it.
Of course, you will not have an infinite tape,
but you should emulate this as much as is possible.
The three permissible actions on the tape are "left", "right" and "stay".
To test your universal Turing machine (and prove your programming language
is Turing complete!), you should execute the following two Turing machines
based on the following definitions.
Simple incrementer
States: q0, qf
Initial state: q0
Terminating states: qf
Permissible symbols: B, 1
Blank symbol: B
Rules:
(q0, 1, 1, right, q0)
(q0, B, 1, stay, qf)
The input for this machine should be a tape of 1 1 1
Three-state busy beaver
States: a, b, c, halt
Initial state: a
Terminating states: halt
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(a, 0, 1, right, b)
(a, 1, 1, left, c)
(b, 0, 1, left, a)
(b, 1, 1, right, b)
(c, 0, 1, left, b)
(c, 1, 1, stay, halt)
The input for this machine should be an empty tape.
Bonus:
5-state, 2-symbol probable Busy Beaver machine from Wikipedia
States: A, B, C, D, E, H
Initial state: A
Terminating states: H
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(A, 0, 1, right, B)
(A, 1, 1, left, C)
(B, 0, 1, right, C)
(B, 1, 1, right, B)
(C, 0, 1, right, D)
(C, 1, 0, left, E)
(D, 0, 1, left, A)
(D, 1, 1, left, D)
(E, 0, 1, stay, H)
(E, 1, 0, left, A)
The input for this machine should be an empty tape.
This machine runs for more than 47 millions steps.
| #Cowgol | Cowgol | include "cowgol.coh";
include "strings.coh";
include "malloc.coh";
###############################################################################
########################## Turing machine definition ##########################
###############################################################################
typedef Symbol is uint8; # 256 symbols ought to be enough for everyone
const LEFT := 1;
const RIGHT := 2;
const STAY := 3;
typedef Action is int(LEFT, STAY);
# Linked list
record Linked is
next: [Linked];
end record;
record DoublyLinked: Linked is
prev: [DoublyLinked];
end record;
sub FreeLinked(r: [Linked]) is
while r != 0 as [Linked] loop
var v := r.next;
Free(r as [uint8]);
r := v;
end loop;
end sub;
sub FreeDoublyLinked(r: [DoublyLinked]) is
FreeLinked(r.next);
while r != 0 as [DoublyLinked] loop
var v := r.prev;
Free(r as [uint8]);
r := v;
end loop;
end sub;
# Turing machine
typedef Turing is [TuringR];
record StateR: Linked is
tm: Turing; # turing machine this state belongs to
term: uint8; # whether state is terminating
end record;
typedef State is [StateR];
record Cell: DoublyLinked is
sym: Symbol;
end record;
record RuleR: Linked is
instate: State;
insym: Symbol;
outsym: Symbol;
action: Action;
outstate: State;
end record;
typedef Rule is [RuleR];
record TuringR is
states: State;
rules: Rule;
initial: State;
current: State;
blank: Symbol;
head: [Cell];
end record;
sub MakeCell(): (c: [Cell]) is
c := Alloc(@bytesof Cell) as [Cell];
MemZero(c as [uint8], @bytesof Cell);
end sub;
# Define a Turing machine
sub MakeTuring(blank: Symbol, init: [Symbol]): (t: Turing) is
t := Alloc(@bytesof TuringR) as Turing;
MemZero(t as [uint8], @bytesof TuringR);
t.blank := blank;
t.head := MakeCell();
t.head.sym := blank;
var c := t.head;
var d: [Cell];
while [init] != 0 loop
c.sym := [init];
init := @next init;
if [init] == 0 then break; end if;
d := Alloc(@bytesof Cell) as [Cell];
d.prev := c as [DoublyLinked];
d.next := 0 as [Linked];
c.next := d as [Linked];
c := d;
end loop;
end sub;
# Add a state to a Turing machine
const T_NONE := 0;
const T_INIT := 1;
const T_HALT := 2;
sub MakeState(t: Turing, type: uint8): (s: State) is
s := Alloc(@bytesof StateR) as State;
s.tm := t;
s.next := t.states as [Linked];
t.states := s;
if type & T_INIT != 0 then
t.initial := s;
t.current := s;
end if;
s.term := 0;
if type & T_HALT != 0 then
s.term := 1;
end if;
end sub;
# Add a rule to a Turing machine
sub MakeRule(t: Turing,
instate: State,
insym: Symbol,
outsym: Symbol,
action: Action,
outstate: State): (r: Rule) is
r := Alloc(@bytesof RuleR) as Rule;
r.instate := instate;
r.insym := insym;
r.outsym := outsym;
r.action := action;
r.outstate := outstate;
r.next := t.rules as [Linked];
t.rules := r;
end sub;
# Free a Turing machine
sub FreeTuring(t: Turing) is
FreeDoublyLinked(t.head as [DoublyLinked]);
FreeLinked(t.states as [Linked]);
FreeLinked(t.rules as [Linked]);
Free(t as [uint8]);
end sub;
# Move the head
sub MoveHead(t: Turing, a: Action) is
var c: [Cell];
case a is
when STAY: return;
when LEFT:
if t.head.prev == 0 as [DoublyLinked] then
c := Alloc(@bytesof Cell) as [Cell];
c.prev := 0 as [DoublyLinked];
c.next := t.head as [Linked];
c.sym := t.blank;
t.head.prev := c as [DoublyLinked];
end if;
t.head := t.head.prev as [Cell];
return;
when RIGHT:
if t.head.next == 0 as [Linked] then
c := Alloc(@bytesof Cell) as [Cell];
c.next := 0 as [Linked];
c.prev := t.head as [DoublyLinked];
c.sym := t.blank;
t.head.next := c as [Linked];
end if;
t.head := t.head.next as [Cell];
return;
when else:
print("Invalid action\n");
ExitWithError();
end case;
end sub;
# Step a Turing machine
sub Step(t: Turing): (halt: uint8) is
# If we're in a halt state, do nothing
if t.current.term != 0 then
halt := 1;
return;
end if;
var r := t.rules;
while r != 0 as Rule loop
# Check each rule to see if it matches the current configuration
if t.current == r.instate
and t.head.sym == r.insym then
# Found a match
t.head.sym := r.outsym;
MoveHead(t, r.action);
t.current := r.outstate;
halt := t.current.term;
return;
end if;
r := r.next as Rule;
end loop;
print("No valid rule!\n");
ExitWithError();
end sub;
# Run a Turing machine until it halts
sub Run(t: Turing) is
while Step(t) == 0 loop
end loop;
end sub;
# Print the touched part of the tape of a Turing machine
sub PrintTape(t: Turing, max: uint32) is
var c := t.head;
var len: uint32 := 0;
while c.prev != 0 as [DoublyLinked] loop
c := c.prev as [Cell];
end loop;
while c != 0 as [Cell] loop
if len < max then
print_char(c.sym as uint8);
end if;
c := c.next as [Cell];
len := len + 1;
end loop;
if len >= max then
print("... (total length: ");
print_i32(len);
print(")");
end if;
end sub;
###############################################################################
######################## Turing machines from the task ########################
###############################################################################
interface TuringFactory(): (t: Turing);
sub SimpleIncrementer implements TuringFactory is
var r: Rule;
t := MakeTuring('B', "111");
var q0 := MakeState(t, T_INIT);
var qf := MakeState(t, T_HALT);
r := MakeRule(t, q0, '1', '1', RIGHT, q0);
r := MakeRule(t, q0, 'B', '1', STAY, qf);
end sub;
sub ThreeStateBeaver implements TuringFactory is
var r: Rule;
t := MakeTuring('0', "");
var a := MakeState(t, T_INIT);
var b := MakeState(t, T_NONE);
var c := MakeState(t, T_NONE);
var halt := MakeState(t, T_HALT);
r := MakeRule(t, a, '0', '1', RIGHT, b);
r := MakeRule(t, a, '1', '1', LEFT, c);
r := MakeRule(t, b, '0', '1', LEFT, a);
r := MakeRule(t, b, '1', '1', RIGHT, b);
r := MakeRule(t, c, '0', '1', LEFT, b);
r := MakeRule(t, c, '1', '1', STAY, halt);
end sub;
sub FiveStateBeaver implements TuringFactory is
var r: Rule;
t := MakeTuring('0', "");
var A := MakeState(t, T_INIT);
var B := MakeState(t, T_NONE);
var C := MakeState(t, T_NONE);
var D := MakeState(t, T_NONE);
var E := MakeState(t, T_NONE);
var H := MakeState(t, T_HALT);
r := MakeRule(t, A, '0', '1', RIGHT, B);
r := MakeRule(t, A, '1', '1', LEFT, C);
r := MakeRule(t, B, '0', '1', RIGHT, C);
r := MakeRule(t, B, '1', '1', RIGHT, B);
r := MakeRule(t, C, '0', '1', RIGHT, D);
r := MakeRule(t, C, '1', '0', LEFT, E);
r := MakeRule(t, D, '0', '1', LEFT, A);
r := MakeRule(t, D, '1', '1', LEFT, D);
r := MakeRule(t, E, '0', '1', STAY, H);
r := MakeRule(t, E, '1', '0', LEFT, A);
end sub;
record TF is
name: [uint8];
tf: TuringFactory;
end record;
var machines: TF[] := {
{"Simple incrementer", SimpleIncrementer},
{"Three state beaver", ThreeStateBeaver},
{"Five state beaver", FiveStateBeaver}
};
var i: @indexof machines;
i := 0;
while i < @sizeof machines loop
print(machines[i].name);
print(": ");
var t := (machines[i].tf) ();
Run(t);
PrintTape(t, 32);
FreeTuring(t);
print_nl();
i := i + 1;
end loop; |
http://rosettacode.org/wiki/Totient_function | Totient function | The totient function is also known as:
Euler's totient function
Euler's phi totient function
phi totient function
Φ function (uppercase Greek phi)
φ function (lowercase Greek phi)
Definitions (as per number theory)
The totient function:
counts the integers up to a given positive integer n that are relatively prime to n
counts the integers k in the range 1 ≤ k ≤ n for which the greatest common divisor gcd(n,k) is equal to 1
counts numbers ≤ n and prime to n
If the totient number (for N) is one less than N, then N is prime.
Task
Create a totient function and:
Find and display (1 per line) for the 1st 25 integers:
the integer (the index)
the totient number for that integer
indicate if that integer is prime
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000 (optional)
Show all output here.
Related task
Perfect totient numbers
Also see
Wikipedia: Euler's totient function.
MathWorld: totient function.
OEIS: Euler totient function phi(n).
| #AWK | AWK |
# syntax: GAWK -f TOTIENT_FUNCTION.AWK
BEGIN {
print(" N Phi isPrime")
for (n=1; n<=1000000; n++) {
tot = totient(n)
if (n-1 == tot) {
count++
}
if (n <= 25) {
printf("%2d %3d %s\n",n,tot,(n-1==tot)?"true":"false")
if (n == 25) {
printf("\n Limit PrimeCount\n")
printf("%7d %10d\n",n,count)
}
}
else if (n ~ /^100+$/) {
printf("%7d %10d\n",n,count)
}
}
exit(0)
}
function totient(n, i,tot) {
tot = n
for (i=2; i*i<=n; i+=2) {
if (n % i == 0) {
while (n % i == 0) {
n /= i
}
tot -= tot / i
}
if (i == 2) {
i = 1
}
}
if (n > 1) {
tot -= tot / n
}
return(tot)
}
|
http://rosettacode.org/wiki/Topswops | Topswops | Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is composed of reversing the first m cards where m is the value of the topmost card.
Rounds are repeated until the topmost card is the number 1 and the number of swaps is recorded.
For our example the swaps produce:
[2, 4, 1, 3] # Initial shuffle
[4, 2, 1, 3]
[3, 1, 2, 4]
[2, 1, 3, 4]
[1, 2, 3, 4]
For a total of four swaps from the initial ordering to produce the terminating case where 1 is on top.
For a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards.
Task
The task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive.
Note
Topswops is also known as Fannkuch from the German word Pfannkuchen meaning pancake.
Related tasks
Number reversal game
Sorting algorithms/Pancake sort
| #Factor | Factor | USING: formatting kernel math math.combinatorics math.order
math.ranges sequences ;
FROM: sequences.private => exchange-unsafe ;
IN: rosetta-code.topswops
! Reverse a subsequence in-place from 0 to n.
: head-reverse! ( seq n -- seq' )
dupd [ 2/ ] [ ] bi rot
[ [ over - 1 - ] dip exchange-unsafe ] 2curry each-integer ;
! Reverse the elements in seq according to the first element.
: swop ( seq -- seq' ) dup first head-reverse! ;
! Determine the number of swops until 1 is the head.
: #swops ( seq -- n )
0 swap [ dup first 1 = ] [ [ 1 + ] [ swop ] bi* ] until
drop ;
! Determine the maximum number of swops for a given length.
: topswops ( n -- max )
[1,b] <permutations> [ #swops ] [ max ] map-reduce ;
: main ( -- )
10 [1,b] [ dup topswops "%2d: %2d\n" printf ] each ;
MAIN: main |
http://rosettacode.org/wiki/Topswops | Topswops | Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is composed of reversing the first m cards where m is the value of the topmost card.
Rounds are repeated until the topmost card is the number 1 and the number of swaps is recorded.
For our example the swaps produce:
[2, 4, 1, 3] # Initial shuffle
[4, 2, 1, 3]
[3, 1, 2, 4]
[2, 1, 3, 4]
[1, 2, 3, 4]
For a total of four swaps from the initial ordering to produce the terminating case where 1 is on top.
For a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards.
Task
The task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive.
Note
Topswops is also known as Fannkuch from the German word Pfannkuchen meaning pancake.
Related tasks
Number reversal game
Sorting algorithms/Pancake sort
| #Fortran | Fortran | module top
implicit none
contains
recursive function f(x) result(m)
integer :: n, m, x(:),y(size(x)), fst
fst = x(1)
if (fst == 1) then
m = 0
else
y(1:fst) = x(fst:1:-1)
y(fst+1:) = x(fst+1:)
m = 1 + f(y)
end if
end function
recursive function perms(x) result(p)
integer, pointer :: p(:,:), q(:,:)
integer :: x(:), n, k, i
n = size(x)
if (n == 1) then
allocate(p(1,1))
p(1,:) = x
else
q => perms(x(2:n))
k = ubound(q,1)
allocate(p(k*n,n))
p = 0
do i = 1,n
p(1+k*(i-1):k*i,1:i-1) = q(:,1:i-1)
p(1+k*(i-1):k*i,i) = x(1)
p(1+k*(i-1):k*i,i+1:) = q(:,i:)
end do
end if
end function
end module
program topswort
use top
implicit none
integer :: x(10)
integer, pointer :: p(:,:)
integer :: i, j, m
forall(i=1:10)
x(i) = i
end forall
do i = 1,10
p=>perms(x(1:i))
m = 0
do j = 1, ubound(p,1)
m = max(m, f(p(j,:)))
end do
print "(i3,a,i3)", i,": ",m
end do
end program
|
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #Axe | Axe | Disp sin(43)▶Dec,i
Disp cos(43)▶Dec,i
Disp tan⁻¹(10,10)▶Dec,i |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.
From the wikipedia entry:
ask for 11 numbers to be read into a sequence S
reverse sequence S
for each item in sequence S
result := call a function to do an operation
if result overflows
alert user
else
print result
The task is to implement the algorithm:
Use the function:
f
(
x
)
=
|
x
|
0.5
+
5
x
3
{\displaystyle f(x)=|x|^{0.5}+5x^{3}}
The overflow condition is an answer of greater than 400.
The 'user alert' should not stop processing of other items of the sequence.
Print a prompt before accepting eleven, textual, numeric inputs.
You may optionally print the item as well as its associated result, but the results must be in reverse order of input.
The sequence S may be 'implied' and so not shown explicitly.
Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
| #Commodore_BASIC | Commodore BASIC |
10 REM TRABB PARDO-KNUTH ALGORITHM
20 REM USED "MAGIC NUMBERS" BECAUSE OF STRICT SPECIFICATION OF THE ALGORITHM.
30 DEF FNF(N)=SQR(ABS(N))+5*N*N*N
40 DIM S(10)
50 PRINT "ENTER 11 NUMBERS."
60 FOR I=0 TO 10
70 PRINT STR$(I+1);
80 INPUT S(I)
90 NEXT I
100 PRINT
110 REM REVERSE
120 FOR I=0 TO 10/2
130 TMP=S(I)
140 S(I)=S(10-I)
150 S(10-I)=TMP
160 NEXT I
170 REM RESULTS
180 FOR I=0 TO 10
190 PRINT "F(";STR$(S(I));") =";
200 R=FNF(S(I))
210 IF R>400 THEN PRINT " OVERFLOW":ELSE PRINT R
220 NEXT I
230 END
|
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.
From the wikipedia entry:
ask for 11 numbers to be read into a sequence S
reverse sequence S
for each item in sequence S
result := call a function to do an operation
if result overflows
alert user
else
print result
The task is to implement the algorithm:
Use the function:
f
(
x
)
=
|
x
|
0.5
+
5
x
3
{\displaystyle f(x)=|x|^{0.5}+5x^{3}}
The overflow condition is an answer of greater than 400.
The 'user alert' should not stop processing of other items of the sequence.
Print a prompt before accepting eleven, textual, numeric inputs.
You may optionally print the item as well as its associated result, but the results must be in reverse order of input.
The sequence S may be 'implied' and so not shown explicitly.
Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
| #Common_Lisp | Common Lisp | (defun read-numbers ()
(princ "Enter 11 numbers (space-separated): ")
(let ((numbers '()))
(dotimes (i 11 numbers)
(push (read) numbers))))
(defun trabb-pardo-knuth (func overflowp)
(let ((S (read-numbers)))
(format T "~{~a~%~}"
(substitute-if "Overflow!" overflowp (mapcar func S)))))
(trabb-pardo-knuth (lambda (x) (+ (expt (abs x) 0.5) (* 5 (expt x 3))))
(lambda (x) (> x 400))) |
http://rosettacode.org/wiki/Twelve_statements | Twelve statements | This puzzle is borrowed from math-frolic.blogspot.
Given the following twelve statements, which of them are true?
1. This is a numbered list of twelve statements.
2. Exactly 3 of the last 6 statements are true.
3. Exactly 2 of the even-numbered statements are true.
4. If statement 5 is true, then statements 6 and 7 are both true.
5. The 3 preceding statements are all false.
6. Exactly 4 of the odd-numbered statements are true.
7. Either statement 2 or 3 is true, but not both.
8. If statement 7 is true, then 5 and 6 are both true.
9. Exactly 3 of the first 6 statements are true.
10. The next two statements are both true.
11. Exactly 1 of statements 7, 8 and 9 are true.
12. Exactly 4 of the preceding statements are true.
Task
When you get tired of trying to figure it out in your head,
write a program to solve it, and print the correct answer or answers.
Extra credit
Print out a table of near misses, that is, solutions that are contradicted by only a single statement.
| #Phix | Phix | function s1(string s) return length(s)=12 end function
function s2(string s) return sum(sq_eq(s[7..12],'1'))=3 end function
function s3(string s) return sum(sq_eq(extract(s,tagset(12,2,2)),'1'))=2 end function
function s4(string s) return s[5]='0' or s[6..7]="11" end function
function s5(string s) return s[2..4]="000" end function
function s6(string s) return sum(sq_eq(extract(s,tagset(12,1,2)),'1'))=4 end function
function s7(string s) return s[2]!=s[3] end function
function s8(string s) return s[7]='0' or s[5..6]="11" end function
function s9(string s) return sum(sq_eq(s[1..6],'1'))=3 end function
function s10(string s) return s[11..12]="11" end function
function s11(string s) return sum(sq_eq(s[7..9],'1'))=1 end function
function s12(string s) return sum(sq_eq(s[1..11],'1'))=4 end function
sequence rtn = {s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12}
string misses = "\n"
for i=0 to power(2,12)-1 do
string s = sprintf("%012b",i)
sequence res = find_all('1',s)
integer t = 0, pass, fail
for b=1 to 12 do
pass = call_func(rtn[b],{s})=(s[b]='1')
if not pass then fail = b end if
t += pass
if b=12 and t=12 then printf(1,"Solution: %v\n",{res}) end if
end for
if t=11 then
misses &= sprintf("Near miss: %v, fail on %d\n",{res,fail})
end if
end for
puts(1,misses)
|
http://rosettacode.org/wiki/Truth_table | Truth table | A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.
Task
Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function.
(One can assume that the user input is correct).
Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function.
Either reverse-polish or infix notation expressions are allowed.
Related tasks
Boolean values
Ternary logic
See also
Wolfram MathWorld entry on truth tables.
some "truth table" examples from Google.
| #Maxima | Maxima | /* Maxima already has the following logical operators
=, # (not equal), not, and, or
define some more and set 'binding power' (operator
precedence) for them
*/
infix("xor", 60)$
"xor"(A,B):= (A or B) and not(A and B)$
infix("=>", 59)$
"=>"(A,B):= not A or B$
/*
Substitute variables `r' in `e' with values taken from list `l' where
`e' is expression, `r' is a list of independent variables, `l' is a
list of the values
lsubst( '(A + B), ['A, 'B], [1, 2]);
1 + 2;
*/
lsubst(e, r, l):= ev(e, maplist( lambda([x, y], x=y), r, l), 'simp)$
/*
"Cartesian power" `n' of list `b'. Returns a list of lists of the form
[<x_1>, ..., <x_n>], were <x_1>, .. <x_n> are elements of list `b'
cartesian_power([true, false], 2);
[[true, true], [true, false], [false, true], [false, false]];
cartesian_power([true, false], 3);
[[true, true, true], [true, true, false], [true, false, true],
[true, false, false], [false, true, true], [false, true, false],
[false, false, true], [false, false, false]];
*/
cartesian_power(b, n) := block(
[aux_lst: makelist(setify(b), n)],
listify(apply(cartesian_product, aux_lst))
)$
gen_table(expr):= block(
[var_lst: listofvars(expr), st_lst, res_lst, m],
st_lst: cartesian_power([true, false], length(var_lst)),
res_lst: create_list(lsubst(expr, var_lst, val_lst), val_lst, st_lst),
m : apply('matrix, cons(var_lst, st_lst)),
addcol(m, cons(expr, res_lst))
);
/* examples */
gen_table('(not A));
gen_table('(A xor B));
gen_table('(Jim and (Spock xor Bones) or Scotty));
gen_table('(A => (B and A)));
gen_table('(V xor (B xor (K xor D ) ))); |
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
| #PARI.2FGP | PARI/GP |
\\ Ulam spiral (plotting/printing)
\\ 4/19/16 aev
plotulamspir(n,pflg=0)={
my(n=if(n%2==0,n++,n),M=matrix(n,n),x,y,xmx,ymx,cnt,dir,n2=n*n,pch,sz=#Str(n2),pch2=srepeat(" ",sz));
if(pflg<0||pflg>2,pflg=0);
print(" *** Ulam spiral: ",n,"x",n," matrix, p-flag=",pflg);
x=y=n\2+1; xmx=ymx=cnt=1; dir="R";
for(i=1,n2,
if(isprime(i), if(!insm(M,x,y), break); if(pflg==2, M[y,x]=i, M[y,x]=1));
if(dir=="R", if(xmx>0, x++;xmx--, dir="U";ymx=cnt;y--;ymx--); next);
if(dir=="U", if(ymx>0, y--;ymx--, dir="L";cnt++;xmx=cnt;x--;xmx--); next);
if(dir=="L", if(xmx>0, x--;xmx--, dir="D";ymx=cnt;y++;ymx--); next);
if(dir=="D", if(ymx>0, y++;ymx--, dir="R";cnt++;xmx=cnt;x++;xmx--); next);
);\\fend
\\Plot/Print according to the p-flag(0-real plot,1-"*",2-primes)
if(pflg==0, plotmat(M));
if(pflg==1, for(i=1,n,
for(j=1,n, if(M[i,j]==1, pch="*", pch=" ");
print1(" ",pch)); print(" ")));
if(pflg==2, for(i=1,n,
for(j=1,n, if(M[i,j]==0, pch=pch2, pch=spad(Str(M[i,j]),sz,,1));
print1(" ",pch)); print(" ")));
}
{\\ Executing:
plotulamspir(9,1); \\ (see output)
plotulamspir(9,2); \\ (see output)
plotulamspir(100); \\ ULAMspiral1.png
plotulamspir(200); \\ ULAMspiral2.png
}
|
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.]
| #Forth | Forth | : prime? ( n -- ? ) here + c@ 0= ;
: notprime! ( n -- ) here + 1 swap c! ;
: sieve ( n -- )
here over erase
0 notprime!
1 notprime!
2
begin
2dup dup * >
while
dup prime? if
2dup dup * do
i notprime!
dup +loop
then
1+
repeat
2drop ;
: left_truncatable_prime? ( n -- flag )
dup prime? invert if
drop false exit
then
dup >r
10
begin
2dup >
while
2dup mod
dup r> = if
2drop drop false exit
then
dup prime? invert if
2drop drop false exit
then
>r
10 *
repeat
2drop rdrop true ;
: right_truncatable_prime? ( n -- flag )
dup prime? invert if
drop false exit
then
begin
10 / dup 0 >
while
dup prime? invert if
drop false exit
then
repeat
drop true ;
: max_left_truncatable_prime ( n -- )
begin
dup 0 >
while
dup left_truncatable_prime? if . cr exit then
1-
repeat drop ;
: max_right_truncatable_prime ( n -- )
begin
dup 0 >
while
dup right_truncatable_prime? if . cr exit then
1-
repeat drop ;
1000000 constant limit
limit 1+ sieve
." Largest left truncatable prime: "
limit max_left_truncatable_prime
." Largest right truncatable prime: "
limit max_right_truncatable_prime
bye |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
See also
Wikipedia article: Tree traversal.
| #Ada | Ada | with Ada.Text_Io; use Ada.Text_Io;
with Ada.Unchecked_Deallocation;
with Ada.Containers.Doubly_Linked_Lists;
procedure Tree_Traversal is
type Node;
type Node_Access is access Node;
type Node is record
Left : Node_Access := null;
Right : Node_Access := null;
Data : Integer;
end record;
procedure Destroy_Tree(N : in out Node_Access) is
procedure free is new Ada.Unchecked_Deallocation(Node, Node_Access);
begin
if N.Left /= null then
Destroy_Tree(N.Left);
end if;
if N.Right /= null then
Destroy_Tree(N.Right);
end if;
Free(N);
end Destroy_Tree;
function Tree(Value : Integer; Left : Node_Access; Right : Node_Access) return Node_Access is
Temp : Node_Access := new Node;
begin
Temp.Data := Value;
Temp.Left := Left;
Temp.Right := Right;
return Temp;
end Tree;
procedure Preorder(N : Node_Access) is
begin
Put(Integer'Image(N.Data));
if N.Left /= null then
Preorder(N.Left);
end if;
if N.Right /= null then
Preorder(N.Right);
end if;
end Preorder;
procedure Inorder(N : Node_Access) is
begin
if N.Left /= null then
Inorder(N.Left);
end if;
Put(Integer'Image(N.Data));
if N.Right /= null then
Inorder(N.Right);
end if;
end Inorder;
procedure Postorder(N : Node_Access) is
begin
if N.Left /= null then
Postorder(N.Left);
end if;
if N.Right /= null then
Postorder(N.Right);
end if;
Put(Integer'Image(N.Data));
end Postorder;
procedure Levelorder(N : Node_Access) is
package Queues is new Ada.Containers.Doubly_Linked_Lists(Node_Access);
use Queues;
Node_Queue : List;
Next : Node_Access;
begin
Node_Queue.Append(N);
while not Is_Empty(Node_Queue) loop
Next := First_Element(Node_Queue);
Delete_First(Node_Queue);
Put(Integer'Image(Next.Data));
if Next.Left /= null then
Node_Queue.Append(Next.Left);
end if;
if Next.Right /= null then
Node_Queue.Append(Next.Right);
end if;
end loop;
end Levelorder;
N : Node_Access;
begin
N := Tree(1,
Tree(2,
Tree(4,
Tree(7, null, null),
null),
Tree(5, null, null)),
Tree(3,
Tree(6,
Tree(8, null, null),
Tree(9, null, null)),
null));
Put("preorder: ");
Preorder(N);
New_Line;
Put("inorder: ");
Inorder(N);
New_Line;
Put("postorder: ");
Postorder(N);
New_Line;
Put("level order: ");
Levelorder(N);
New_Line;
Destroy_Tree(N);
end Tree_traversal; |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | In[1]:= 3
Out[1]= 3
In[2]:= %1^2
Out[2]= 9
In[3]:= Sqrt[%%]
Out[3]= Sqrt[3]
In[4]:= N[Out[-1]] (* for floating point *)
Out[4]= 1.73205 |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #Nim | Nim | for _ in 1..10:
echo "Hello World!" |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #Oforth | Oforth | 3 dup sq swap sqrt |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #PARI.2FGP | PARI/GP | 3
[sqrt(%),%^2] |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #Perl | Perl | print sqrt . " " for (4, 16, 64) |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #Phix | Phix | with javascript_semantics
object _
_ = 3
?_
?_*_
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #8086_Assembly | 8086 Assembly | cpu 8086
bits 16
org 100h
section .text
mov bx,0402h ; Set up first arguments to move()
mov cx,0103h ; Registers chosen s.t. CX contains output
;;; Move BH disks from CH via BL to CL
move: dec bh ; One fewer disk in next iteration
jz .out ; If this was last disk, just print move
push bx ; Save the registers for a recursive call
push cx
xchg bl,cl ; Swap the 'to' and 'via' registers
call move ; move(BH, CH, CL, BL)
pop cx ; Restore the registers from the stack
pop bx
call .out ; Print the move
xchg ch,bl ; Swap the 'from' and 'via' registers
jmp move ; move(BH, BL, CH, CL)
;;; Print the move
.out: mov ax,'00' ; Add ASCII 0 to both 'from' and 'to'
add ax,cx ; in one 16-bit operation
mov [out1],ah ; Store 'from' field in output
mov [out2],al ; Store 'to' field in output
mov dx,outstr ; MS-DOS system call to print string
mov ah,9
int 21h
ret
section .data
outstr: db 'Move disk from pole '
out1: db '* to pole '
out2: db '*',13,10,'$' |
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping | Tokenize a string with escaping | Task[edit]
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
It should accept three input parameters:
The string
The separator character
The escape character
It should output a list of strings.
Details
Rules for splitting:
The fields that were separated by the separators, become the elements of the output list.
Empty fields should be preserved, even at the start and end.
Rules for escaping:
"Escaped" means preceded by an occurrence of the escape character that is not already escaped itself.
When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special).
Each occurrence of the escape character that was used to escape something, should not become part of the output.
Test case
Demonstrate that your function satisfies the following test-case:
Input
Output
string:
one^|uno||three^^^^|four^^^|^cuatro|
separator character:
|
escape character:
^
one|uno
three^^
four^|cuatro
(Print the output list in any format you like, as long as it is it easy to see what the fields are.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #11l | 11l | F token_with_escape(a, escape = ‘^’, separator = ‘|’)
[String] result
V token = ‘’
V state = 0
L(c) a
I state == 0
I c == escape
state = 1
E I c == separator
result.append(token)
token = ‘’
E
token ‘’= c
E I state == 1
token ‘’= c
state = 0
result.append(token)
R result
print(token_with_escape(‘one^|uno||three^^^^|four^^^|^cuatro|’).map(s -> ‘'’s‘'’).join(‘, ’)) |
http://rosettacode.org/wiki/Total_circles_area | Total circles area | Total circles area
You are encouraged to solve this task according to the task description, using any language you may know.
Example circles
Example circles filtered
Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal digits of precision. The area covered by two or more disks needs to be counted only once.
One point of this Task is also to compare and discuss the relative merits of various solution strategies, their performance, precision and simplicity. This means keeping both slower and faster solutions for a language (like C) is welcome.
To allow a better comparison of the different implementations, solve the problem with this standard dataset, each line contains the x and y coordinates of the centers of the disks and their radii (11 disks are fully contained inside other disks):
xc yc radius
1.6417233788 1.6121789534 0.0848270516
-1.4944608174 1.2077959613 1.1039549836
0.6110294452 -0.6907087527 0.9089162485
0.3844862411 0.2923344616 0.2375743054
-0.2495892950 -0.3832854473 1.0845181219
1.7813504266 1.6178237031 0.8162655711
-0.1985249206 -0.8343333301 0.0538864941
-1.7011985145 -0.1263820964 0.4776976918
-0.4319462812 1.4104420482 0.7886291537
0.2178372997 -0.9499557344 0.0357871187
-0.6294854565 -1.3078893852 0.7653357688
1.7952608455 0.6281269104 0.2727652452
1.4168575317 1.0683357171 1.1016025378
1.4637371396 0.9463877418 1.1846214562
-0.5263668798 1.7315156631 1.4428514068
-1.2197352481 0.9144146579 1.0727263474
-0.1389358881 0.1092805780 0.7350208828
1.5293954595 0.0030278255 1.2472867347
-0.5258728625 1.3782633069 1.3495508831
-0.1403562064 0.2437382535 1.3804956588
0.8055826339 -0.0482092025 0.3327165165
-0.6311979224 0.7184578971 0.2491045282
1.4685857879 -0.8347049536 1.3670667538
-0.6855727502 1.6465021616 1.0593087096
0.0152957411 0.0638919221 0.9771215985
The result is 21.56503660... .
Related task
Circles of given radius through two points.
See also
http://www.reddit.com/r/dailyprogrammer/comments/zff9o/9062012_challenge_96_difficult_water_droplets/
http://stackoverflow.com/a/1667789/10562
| #D | D | import std.stdio, std.math, std.algorithm, std.typecons, std.range;
alias Fp = real;
struct Circle { Fp x, y, r; }
void removeInternalDisks(ref Circle[] circles) pure nothrow @safe {
static bool isFullyInternal(in Circle c1, in Circle c2)
pure nothrow @safe @nogc {
if (c1.r > c2.r) // Quick exit.
return false;
return (c1.x - c2.x) ^^ 2 + (c1.y - c2.y) ^^ 2 <
(c2.r - c1.r) ^^ 2;
}
// Heuristics for performance: large radii first.
circles.sort!q{ a.r > b.r };
// Remove circles inside another circle.
for (auto i = circles.length; i-- > 0; )
for (auto j = circles.length; j-- > 0; )
if (i != j && isFullyInternal(circles[i], circles[j])) {
circles[i] = circles[$ - 1];
circles.length--;
break;
}
}
void main() {
Circle[] circles = [
{ 1.6417233788, 1.6121789534, 0.0848270516},
{-1.4944608174, 1.2077959613, 1.1039549836},
{ 0.6110294452, -0.6907087527, 0.9089162485},
{ 0.3844862411, 0.2923344616, 0.2375743054},
{-0.2495892950, -0.3832854473, 1.0845181219},
{ 1.7813504266, 1.6178237031, 0.8162655711},
{-0.1985249206, -0.8343333301, 0.0538864941},
{-1.7011985145, -0.1263820964, 0.4776976918},
{-0.4319462812, 1.4104420482, 0.7886291537},
{ 0.2178372997, -0.9499557344, 0.0357871187},
{-0.6294854565, -1.3078893852, 0.7653357688},
{ 1.7952608455, 0.6281269104, 0.2727652452},
{ 1.4168575317, 1.0683357171, 1.1016025378},
{ 1.4637371396, 0.9463877418, 1.1846214562},
{-0.5263668798, 1.7315156631, 1.4428514068},
{-1.2197352481, 0.9144146579, 1.0727263474},
{-0.1389358881, 0.1092805780, 0.7350208828},
{ 1.5293954595, 0.0030278255, 1.2472867347},
{-0.5258728625, 1.3782633069, 1.3495508831},
{-0.1403562064, 0.2437382535, 1.3804956588},
{ 0.8055826339, -0.0482092025, 0.3327165165},
{-0.6311979224, 0.7184578971, 0.2491045282},
{ 1.4685857879, -0.8347049536, 1.3670667538},
{-0.6855727502, 1.6465021616, 1.0593087096},
{ 0.0152957411, 0.0638919221, 0.9771215985}];
writeln("Input Circles: ", circles.length);
removeInternalDisks(circles);
writeln("Circles left: ", circles.length);
immutable Fp xMin = reduce!((acc, c) => min(acc, c.x - c.r))
(Fp.max, circles[]);
immutable Fp xMax = reduce!((acc, c) => max(acc, c.x + c.r))
(Fp(0), circles[]);
alias YRange = Tuple!(Fp,"y0", Fp,"y1");
auto yRanges = new YRange[circles.length];
Fp computeTotalArea(in Fp nSlicesX) nothrow @safe {
Fp total = 0;
// Adapted from an idea by Cosmologicon.
foreach (immutable p; cast(int)(xMin * nSlicesX) ..
cast(int)(xMax * nSlicesX) + 1) {
immutable Fp x = p / nSlicesX;
size_t nPairs = 0;
// Look for the circles intersecting the current
// vertical secant:
foreach (const ref c; circles) {
immutable Fp d = c.r ^^ 2 - (c.x - x) ^^ 2;
immutable Fp sd = d.sqrt;
if (d > 0)
// And keep only the intersection chords.
yRanges[nPairs++] = YRange(c.y - sd, c.y + sd);
}
// Merge the ranges, counting the overlaps only once.
yRanges[0 .. nPairs].sort();
Fp y = -Fp.max;
foreach (immutable r; yRanges[0 .. nPairs])
if (y < r.y1) {
total += r.y1 - max(y, r.y0);
y = r.y1;
}
}
return total / nSlicesX;
}
// Iterate to reach some precision.
enum Fp epsilon = 1e-9;
Fp nSlicesX = 1_000;
Fp oldArea = -1;
while (true) {
immutable Fp newArea = computeTotalArea(nSlicesX);
if (abs(oldArea - newArea) < epsilon) {
writeln("N. vertical slices: ", nSlicesX);
writefln("Approximate area: %.17f", newArea);
return;
}
oldArea = newArea;
nSlicesX *= 2;
}
} |
http://rosettacode.org/wiki/Universal_Turing_machine | Universal Turing machine | One of the foundational mathematical constructs behind computer science
is the universal Turing Machine.
(Alan Turing introduced the idea of such a machine in 1936–1937.)
Indeed one way to definitively prove that a language
is turing-complete
is to implement a universal Turing machine in it.
Task
Simulate such a machine capable
of taking the definition of any other Turing machine and executing it.
Of course, you will not have an infinite tape,
but you should emulate this as much as is possible.
The three permissible actions on the tape are "left", "right" and "stay".
To test your universal Turing machine (and prove your programming language
is Turing complete!), you should execute the following two Turing machines
based on the following definitions.
Simple incrementer
States: q0, qf
Initial state: q0
Terminating states: qf
Permissible symbols: B, 1
Blank symbol: B
Rules:
(q0, 1, 1, right, q0)
(q0, B, 1, stay, qf)
The input for this machine should be a tape of 1 1 1
Three-state busy beaver
States: a, b, c, halt
Initial state: a
Terminating states: halt
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(a, 0, 1, right, b)
(a, 1, 1, left, c)
(b, 0, 1, left, a)
(b, 1, 1, right, b)
(c, 0, 1, left, b)
(c, 1, 1, stay, halt)
The input for this machine should be an empty tape.
Bonus:
5-state, 2-symbol probable Busy Beaver machine from Wikipedia
States: A, B, C, D, E, H
Initial state: A
Terminating states: H
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(A, 0, 1, right, B)
(A, 1, 1, left, C)
(B, 0, 1, right, C)
(B, 1, 1, right, B)
(C, 0, 1, right, D)
(C, 1, 0, left, E)
(D, 0, 1, left, A)
(D, 1, 1, left, D)
(E, 0, 1, stay, H)
(E, 1, 0, left, A)
The input for this machine should be an empty tape.
This machine runs for more than 47 millions steps.
| #D | D | import std.stdio, std.algorithm, std.string, std.conv, std.array,
std.exception, std.traits, std.math, std.range;
struct UTM(State, Symbol, bool doShow=true)
if (is(State == enum) && is(Symbol == enum)) {
static assert(is(typeof({ size_t x = State.init; })),
"State must to be usable as array index.");
static assert([EnumMembers!State].equal(EnumMembers!State.length.iota),
"State must be a plain enum.");
static assert(is(typeof({ size_t x = Symbol.init; })),
"Symbol must to be usable as array index.");
static assert([EnumMembers!Symbol].equal(EnumMembers!Symbol.length.iota),
"Symbol must be a plain enum.");
enum Direction { right, left, stay }
private const TuringMachine tm;
private TapeHead head;
alias SymbolMap = string[EnumMembers!Symbol.length];
// The first index of this 'rules' matrix is a subtype of State
// because it can't contain H, but currently D can't enforce this,
// statically unlike Ada language.
Rule[EnumMembers!Symbol.length][EnumMembers!State.length - 1] mRules;
static struct Rule {
Symbol toWrite;
Direction direction;
State nextState;
this(in Symbol toWrite_, in Direction direction_, in State nextState_)
pure nothrow @safe @nogc {
this.toWrite = toWrite_;
this.direction = direction_;
this.nextState = nextState_;
}
}
// This is kept separated from the rest so it can be inialized
// one field at a time in the main function, yet it will become
// const.
static struct TuringMachine {
Symbol blank;
State initialState;
Rule[Symbol][State] rules;
Symbol[] input;
SymbolMap symbolMap;
}
static struct TapeHead {
immutable Symbol blank;
Symbol[] tapeLeft, tapeRight;
int position;
const SymbolMap sMap;
size_t nSteps;
this(in ref TuringMachine t) pure nothrow @safe {
this.blank = EnumMembers!Symbol[0];
//tapeRight = t.input.empty ? [this.blank] : t.input.dup;
if (t.input.empty)
this.tapeRight = [this.blank];
else
this.tapeRight = t.input.dup;
this.position = 0;
this.sMap = t.symbolMap;
}
pure nothrow @safe @nogc invariant {
assert(this.tapeRight.length > 0);
if (this.position >= 0)
assert(this.position < this.tapeRight.length);
else
assert(this.position.abs <= this.tapeLeft.length);
}
Symbol readSymb() const pure nothrow @safe @nogc {
if (this.position >= 0)
return this.tapeRight[this.position];
else
return this.tapeLeft[this.position.abs - 1];
}
void showSymb() const @safe {
this.write;
}
void writeSymb(in Symbol symbol) @safe {
static if (doShow)
showSymb;
if (this.position >= 0)
this.tapeRight[this.position] = symbol;
else
this.tapeLeft[this.position.abs - 1] = symbol;
}
void goRight() pure nothrow @safe {
this.position++;
if (position > 0 && position == tapeRight.length)
tapeRight ~= blank;
}
void goLeft() pure nothrow @safe {
this.position--;
if (position < 0 && (position.abs - 1) == tapeLeft.length)
tapeLeft ~= blank;
}
void move(in Direction dir) pure nothrow @safe {
nSteps++;
final switch (dir) with (Direction) {
case left: goLeft; break;
case right: goRight; break;
case stay: /*Do nothing*/ break;
}
}
string toString() const @safe {
immutable pos = tapeLeft.length.signed + this.position + 4;
return format("...%-(%)...", tapeLeft.retro.chain(tapeRight)
.map!(s => sMap[s])) ~
'\n' ~
format("%" ~ pos.text ~ "s", "^") ~
'\n';
}
}
void show() const @safe {
head.showSymb;
}
this(in ref TuringMachine tm_) @safe {
static assert(__traits(compiles, State.H), "State needs a 'H' (Halt).");
immutable errMsg = "Invalid input.";
auto runningStates = remove!(s => s == State.H)([EnumMembers!State]);
enforce(!runningStates.empty, errMsg);
enforce(tm_.rules.length == EnumMembers!State.length - 1, errMsg);
enforce(State.H !in tm_.rules, errMsg);
enforce(runningStates.canFind(tm_.initialState), errMsg);
// Create a matrix to reduce running time.
foreach (immutable State st, const rset; tm_.rules)
foreach (immutable Symbol sy, immutable rule; rset)
mRules[st][sy] = rule;
this.tm = tm_;
head = TapeHead(this.tm);
State state = tm.initialState;
while (state != State.H) {
immutable next = mRules[state][head.readSymb];
head.writeSymb(next.toWrite);
head.move(next.direction);
state = next.nextState;
}
static if (doShow)
show;
writeln("Performed ", head.nSteps, " steps.");
}
}
void main() @safe {
"Incrementer:".writeln;
enum States1 : ubyte { A, H }
enum Symbols1 : ubyte { s0, s1 }
alias M1 = UTM!(States1, Symbols1);
M1.TuringMachine tm1;
with (tm1) with (States1) with (Symbols1) with (M1.Direction) {
alias R = M1.Rule;
initialState = A;
rules = [A: [s0: R(s1, stay, H), s1: R(s1, right, A)]];
input = [s1, s1, s1];
symbolMap = ["0", "1"];
}
M1(tm1);
// http://en.wikipedia.org/wiki/Busy_beaver
"\nBusy Beaver machine (3-state, 2-symbol):".writeln;
enum States2 : ubyte { A, B, C, H }
alias Symbols2 = Symbols1;
alias M2 = UTM!(States2, Symbols2);
M2.TuringMachine tm2;
with (tm2) with (States2) with (Symbols2) with (M2.Direction) {
alias R = M2.Rule;
initialState = A;
rules = [A: [s0: R(s1, right, B), s1: R(s1, left, C)],
B: [s0: R(s1, left, A), s1: R(s1, right, B)],
C: [s0: R(s1, left, B), s1: R(s1, stay, H)]];
symbolMap = ["0", "1"];
}
M2(tm2);
"\nSorting stress test (12212212121212):".writeln;
enum States3 : ubyte { A, B, C, D, E, H }
enum Symbols3 : ubyte { s0, s1, s2, s3 }
alias M3 = UTM!(States3, Symbols3, false);
M3.TuringMachine tm3;
with (tm3) with (States3) with (Symbols3) with (M3.Direction) {
alias R = M3.Rule;
initialState = A;
rules = [A: [s1: R(s1, right, A),
s2: R(s3, right, B),
s0: R(s0, left, E)],
B: [s1: R(s1, right, B),
s2: R(s2, right, B),
s0: R(s0, left, C)],
C: [s1: R(s2, left, D),
s2: R(s2, left, C),
s3: R(s2, left, E)],
D: [s1: R(s1, left, D),
s2: R(s2, left, D),
s3: R(s1, right, A)],
E: [s1: R(s1, left, E),
s0: R(s0, stay, H)]];
input = [s1, s2, s2, s1, s2, s2, s1,
s2, s1, s2, s1, s2, s1, s2];
symbolMap = ["0", "1", "2", "3"];
}
M3(tm3).show;
"\nPossible best Busy Beaver machine (5-state, 2-symbol):".writeln;
alias States4 = States3;
alias Symbols4 = Symbols1;
alias M4 = UTM!(States4, Symbols4, false);
M4.TuringMachine tm4;
with (tm4) with (States4) with (Symbols4) with (M4.Direction) {
alias R = M4.Rule;
initialState = A;
rules = [A: [s0: R(s1, right, B), s1: R(s1, left, C)],
B: [s0: R(s1, right, C), s1: R(s1, right, B)],
C: [s0: R(s1, right, D), s1: R(s0, left, E)],
D: [s0: R(s1, left, A), s1: R(s1, left, D)],
E: [s0: R(s1, stay, H), s1: R(s0, left, A)]];
symbolMap = ["0", "1"];
}
M4(tm4);
} |
http://rosettacode.org/wiki/Totient_function | Totient function | The totient function is also known as:
Euler's totient function
Euler's phi totient function
phi totient function
Φ function (uppercase Greek phi)
φ function (lowercase Greek phi)
Definitions (as per number theory)
The totient function:
counts the integers up to a given positive integer n that are relatively prime to n
counts the integers k in the range 1 ≤ k ≤ n for which the greatest common divisor gcd(n,k) is equal to 1
counts numbers ≤ n and prime to n
If the totient number (for N) is one less than N, then N is prime.
Task
Create a totient function and:
Find and display (1 per line) for the 1st 25 integers:
the integer (the index)
the totient number for that integer
indicate if that integer is prime
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000 (optional)
Show all output here.
Related task
Perfect totient numbers
Also see
Wikipedia: Euler's totient function.
MathWorld: totient function.
OEIS: Euler totient function phi(n).
| #BQN | BQN | GCD ← {𝕨(|𝕊⍟(>⟜0)⊣)𝕩}
Totient ← +´1=⊢GCD¨1+↕ |
http://rosettacode.org/wiki/Topswops | Topswops | Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is composed of reversing the first m cards where m is the value of the topmost card.
Rounds are repeated until the topmost card is the number 1 and the number of swaps is recorded.
For our example the swaps produce:
[2, 4, 1, 3] # Initial shuffle
[4, 2, 1, 3]
[3, 1, 2, 4]
[2, 1, 3, 4]
[1, 2, 3, 4]
For a total of four swaps from the initial ordering to produce the terminating case where 1 is on top.
For a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards.
Task
The task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive.
Note
Topswops is also known as Fannkuch from the German word Pfannkuchen meaning pancake.
Related tasks
Number reversal game
Sorting algorithms/Pancake sort
| #Go | Go | // Adapted from http://www-cs-faculty.stanford.edu/~uno/programs/topswops.w
// at Donald Knuth's web site. Algorithm credited there to Pepperdine
// and referenced to Mathematical Gazette 73 (1989), 131-133.
package main
import "fmt"
const ( // array sizes
maxn = 10 // max number of cards
maxl = 50 // upper bound for number of steps
)
func main() {
for i := 1; i <= maxn; i++ {
fmt.Printf("%d: %d\n", i, steps(i))
}
}
func steps(n int) int {
var a, b [maxl][maxn + 1]int
var x [maxl]int
a[0][0] = 1
var m int
for l := 0; ; {
x[l]++
k := int(x[l])
if k >= n {
if l <= 0 {
break
}
l--
continue
}
if a[l][k] == 0 {
if b[l][k+1] != 0 {
continue
}
} else if a[l][k] != k+1 {
continue
}
a[l+1] = a[l]
for j := 1; j <= k; j++ {
a[l+1][j] = a[l][k-j]
}
b[l+1] = b[l]
a[l+1][0] = k + 1
b[l+1][k+1] = 1
if l > m-1 {
m = l + 1
}
l++
x[l] = 0
}
return m
} |
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #BaCon | BaCon | ' Trigonometric functions in BaCon use Radians for input values
' The RAD() function converts from degrees to radians
FOR v$ IN "0, 10, 45, 90, 190.5"
d = VAL(v$) * 1.0
r = RAD(d) * 1.0
PRINT "Sine: ", d, " degrees (or ", r, " radians) is ", SIN(r)
PRINT "Cosine: ", d, " degrees (or ", r, " radians) is ", COS(r)
PRINT "Tangent: ", d, " degrees (or ", r, " radians) is ", TAN(r)
PRINT
PRINT "Arc Sine: ", SIN(r), " is ", DEG(ASIN(SIN(r))), " degrees (or ", ASIN(SIN(r)), " radians)"
PRINT "Arc CoSine: ", COS(r), " is ", DEG(ACOS(COS(r))), " degrees (or ", ACOS(COS(r)), " radians)"
PRINT "Arc Tangent: ", TAN(r), " is ", DEG(ATN(TAN(r))), " degrees (or ", ATN(TAN(r)), " radians)"
PRINT
NEXT |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.
From the wikipedia entry:
ask for 11 numbers to be read into a sequence S
reverse sequence S
for each item in sequence S
result := call a function to do an operation
if result overflows
alert user
else
print result
The task is to implement the algorithm:
Use the function:
f
(
x
)
=
|
x
|
0.5
+
5
x
3
{\displaystyle f(x)=|x|^{0.5}+5x^{3}}
The overflow condition is an answer of greater than 400.
The 'user alert' should not stop processing of other items of the sequence.
Print a prompt before accepting eleven, textual, numeric inputs.
You may optionally print the item as well as its associated result, but the results must be in reverse order of input.
The sequence S may be 'implied' and so not shown explicitly.
Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
| #D | D | import std.stdio, std.math, std.conv, std.algorithm, std.array;
double f(in double x) pure nothrow {
return x.abs.sqrt + 5 * x ^^ 3;
}
void main() {
double[] data;
while (true) {
"Please enter eleven numbers on a line: ".write;
data = readln.split.map!(to!double).array;
if (data.length == 11)
break;
writeln("Those aren't eleven numbers.");
}
foreach_reverse (immutable x; data) {
immutable y = x.f;
writefln("f(%0.3f) = %s", x, y > 400 ? "Too large" : y.text);
}
} |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.
From the wikipedia entry:
ask for 11 numbers to be read into a sequence S
reverse sequence S
for each item in sequence S
result := call a function to do an operation
if result overflows
alert user
else
print result
The task is to implement the algorithm:
Use the function:
f
(
x
)
=
|
x
|
0.5
+
5
x
3
{\displaystyle f(x)=|x|^{0.5}+5x^{3}}
The overflow condition is an answer of greater than 400.
The 'user alert' should not stop processing of other items of the sequence.
Print a prompt before accepting eleven, textual, numeric inputs.
You may optionally print the item as well as its associated result, but the results must be in reverse order of input.
The sequence S may be 'implied' and so not shown explicitly.
Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
| #EchoLisp | EchoLisp |
(define (trabb-fun n)
(+ (* 5 n n n) (sqrt(abs n))))
(define (check-trabb n)
(if (number? n)
(if (<= (trabb-fun n) 400)
(printf "🌱 f(%d) = %d" n (trabb-fun n))
(printf "❌ f(%d) = %d" n (trabb-fun n)))
(error "not a number" n)))
(define (trabb (numlist null))
(while (< (length numlist) 11)
(set! numlist (append numlist
(or
(read default: (shuffle (iota 11))
prompt: (format "Please enter %d more numbers" (- 11 (length numlist))))
(error 'incomplete-list numlist))))) ;; users cancel
(for-each check-trabb (reverse (take numlist 11))))
|
http://rosettacode.org/wiki/Twelve_statements | Twelve statements | This puzzle is borrowed from math-frolic.blogspot.
Given the following twelve statements, which of them are true?
1. This is a numbered list of twelve statements.
2. Exactly 3 of the last 6 statements are true.
3. Exactly 2 of the even-numbered statements are true.
4. If statement 5 is true, then statements 6 and 7 are both true.
5. The 3 preceding statements are all false.
6. Exactly 4 of the odd-numbered statements are true.
7. Either statement 2 or 3 is true, but not both.
8. If statement 7 is true, then 5 and 6 are both true.
9. Exactly 3 of the first 6 statements are true.
10. The next two statements are both true.
11. Exactly 1 of statements 7, 8 and 9 are true.
12. Exactly 4 of the preceding statements are true.
Task
When you get tired of trying to figure it out in your head,
write a program to solve it, and print the correct answer or answers.
Extra credit
Print out a table of near misses, that is, solutions that are contradicted by only a single statement.
| #Picat | Picat | % {{trans|Prolog}}
go ?=>
puzzle,
fail, % check for more answers
nl.
go => true.
puzzle =>
% 1. This is a numbered list of twelve statements.
L = [A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12],
L :: 0..1,
element(1, L, 1),
% 2. Exactly 3 of the last 6 statements are true.
A2 #<=> sum(L[7..12]) #= 3,
% 3. Exactly 2 of the even-numbered statements are true.
A3 #<=> sum([L[I]:I in 1..12,I mod 2 == 0]) #= 2,
% 4. If statement 5 is true, then statements 6 and 7 are both true.
A4 #<=> (A5 #=> (A6 #/\ A7)),
% 5. The 3 preceding statements are all false.
A5 #<=> sum(L[2..4]) #= 0,
% 6. Exactly 4 of the odd-numbered statements are true.
A6 #<=> sum([L[I]:I in 1..12,I mod 2 == 1]) #= 4,
% 7. Either statement 2 or 3 is true, but not both.
A7 #<=> (A2 + A3 #= 1),
% 8. If statement 7 is true, then 5 and 6 are both true.
A8 #<=> (A7 #=> A5 #/\ A6),
% 9. Exactly 3 of the first 6 statements are true.
A9 #<=> sum(L[1..6]) #= 3,
% 10. The next two statements are both true.
A10 #<=> (A11 #/\ A12),
% 11. Exactly 1 of statements 7, 8 and 9 are true.
A11 #<=> (A7 + A8 + A9 #= 1),
% 12. Exactly 4 of the preceding statements are true.
A12 #<=> sum(L[1..11]) #= 4,
solve(L),
println('L'=L),
printf("Statements %w are true.\n", [I.to_string : I in 1..12, L[I] == 1].join(" ")),
nl. |
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.
| #Prolog | Prolog | puzzle :-
% 1. This is a numbered list of twelve statements.
L = [A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12],
L ins 0..1,
element(1, L, 1),
% 2. Exactly 3 of the last 6 statements are true.
A2 #<==> A7 + A8 + A9 + A10 + A11 + A12 #= 3,
% 3. Exactly 2 of the even-numbered statements are true.
A3 #<==> A2 + A4 + A6 + A8 + A10 + A12 #= 2,
% 4. If statement 5 is true, then statements 6 and 7 are both true.
A4 #<==> (A5 #==> (A6 #/\ A7)),
% 5. The 3 preceding statements are all false.
A5 #<==> A2 + A3 + A4 #= 0,
% 6. Exactly 4 of the odd-numbered statements are true.
A6 #==> A1 + A3 + A5 + A7 + A9 + A11 #= 4,
% 7. Either statement 2 or 3 is true, but not both.
A7 #<==> A2 + A3 #= 1,
% 8. If statement 7 is true, then 5 and 6 are both true.
A8 #<==> (A7 #==> A5 #/\ A6),
% 9. Exactly 3 of the first 6 statements are true.
A9 #<==> A1 + A2 + A3 + A4 + A5 + A6 #= 3,
% 10. The next two statements are both true.
A10 #<==> A11 #/\ A12,
% 11. Exactly 1 of statements 7, 8 and 9 are true.
A11 #<==> A7 + A8 + A9 #= 1,
% 12. Exactly 4 of the preceding statements are true.
A12 #<==> A1 + A2 + A3 + A4 + A5 + A6 + A7 +A8 + A9 + A10 + A11 #= 4,
label(L),
numlist(1, 12, NL),
write('Statements '),
maplist(my_write, NL, L),
writeln('are true').
my_write(N, 1) :-
format('~w ', [N]).
my_write(_N, 0).
|
http://rosettacode.org/wiki/Truth_table | Truth table | A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.
Task
Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function.
(One can assume that the user input is correct).
Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function.
Either reverse-polish or infix notation expressions are allowed.
Related tasks
Boolean values
Ternary logic
See also
Wolfram MathWorld entry on truth tables.
some "truth table" examples from Google.
| #Nim | Nim | import sequtils, strutils, sugar
# List of possible variables names.
const VarChars = {'A'..'E', 'G'..'S', 'U'..'Z'}
type
Expression = object
names: seq[char] # List of variables names.
values: seq[bool] # Associated values.
formula: string # Formula as a string.
proc initExpression(str: string): Expression =
## Build an expression from a string.
for ch in str:
if ch in VarChars and ch notin result.names:
result.names.add ch
result.values.setLen(result.names.len)
result.formula = str
template apply(stack: seq[bool]; op: (bool, bool) -> bool): bool =
## Apply an operator on the last two operands of an evaluation stack.
## Needed to make sure that pops are done (avoiding short-circuit optimization).
let op2 = stack.pop()
let op1 = stack.pop()
op(op1, op2)
proc evaluate(expr: Expression): bool =
## Evaluate the current expression.
var stack: seq[bool] # Evaluation stack.
for e in expr.formula:
stack.add case e
of 'T': true
of 'F': false
of '!': not stack.pop()
of '&': stack.apply(`and`)
of '|': stack.apply(`or`)
of '^': stack.apply(`xor`)
else:
if e in VarChars: expr.values[expr.names.find(e)]
else:
raise newException(
ValueError, "Non-conformant character in expression: '$#'.".format(e))
if stack.len != 1:
raise newException(ValueError, "Ill-formed expression.")
result = stack[0]
proc setVariables(expr: var Expression; pos: Natural) =
## Recursively set the variables.
## When all the variables are set, launch the evaluation of the expression
## and print the result.
assert pos <= expr.values.len
if pos == expr.values.len:
# Evaluate and display.
let vs = expr.values.mapIt(if it: 'T' else: 'F').join(" ")
let es = if expr.evaluate(): 'T' else: 'F'
echo vs, " ", es
else:
# Set values.
expr.values[pos] = false
expr.setVariables(pos + 1)
expr.values[pos] = true
expr.setVariables(pos + 1)
echo "Accepts single-character variables (except for 'T' and 'F',"
echo "which specify explicit true or false values), postfix, with"
echo "&|!^ for and, or, not, xor, respectively; optionally"
echo "seperated by spaces or tabs. Just enter nothing to quit."
while true:
# Read formula and create expression.
stdout.write "\nBoolean expression: "
let line = stdin.readLine.toUpperAscii.multiReplace((" ", ""), ("\t", ""))
if line.len == 0: break
var expr = initExpression(line)
if expr.names.len == 0: break
# Display the result.
let vs = expr.names.join(" ")
echo '\n', vs, " ", expr.formula
let h = vs.len + expr.formula.len + 2
echo repeat('=', h)
expr.setVariables(0) |
http://rosettacode.org/wiki/Ulam_spiral_(for_primes) | Ulam spiral (for primes) | An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1), constructed on a square grid, starting at the "center".
An Ulam spiral is also known as a prime spiral.
The first grid (green) is shown with sequential integers, starting at 1.
In an Ulam spiral of primes, only the primes are shown (usually indicated by some glyph such as a dot or asterisk), and all non-primes as shown as a blank (or some other whitespace).
Of course, the grid and border are not to be displayed (but they are displayed here when using these Wiki HTML tables).
Normally, the spiral starts in the "center", and the 2nd number is to the viewer's right and the number spiral starts from there in a counter-clockwise direction.
There are other geometric shapes that are used as well, including clock-wise spirals.
Also, some spirals (for the 2nd number) is viewed upwards from the 1st number instead of to the right, but that is just a matter of orientation.
Sometimes, the starting number can be specified to show more visual striking patterns (of prime densities).
[A larger than necessary grid (numbers wise) is shown here to illustrate the pattern of numbers on the diagonals (which may be used by the method to orientate the direction of spiral-construction algorithm within the example computer programs)].
Then, in the next phase in the transformation of the Ulam prime spiral, the non-primes are translated to blanks.
In the orange grid below, the primes are left intact, and all non-primes are changed to blanks.
Then, in the final transformation of the Ulam spiral (the yellow grid), translate the primes to a glyph such as a • or some other suitable glyph.
65
64
63
62
61
60
59
58
57
66
37
36
35
34
33
32
31
56
67
38
17
16
15
14
13
30
55
68
39
18
5
4
3
12
29
54
69
40
19
6
1
2
11
28
53
70
41
20
7
8
9
10
27
52
71
42
21
22
23
24
25
26
51
72
43
44
45
46
47
48
49
50
73
74
75
76
77
78
79
80
81
61
59
37
31
67
17
13
5
3
29
19
2
11
53
41
7
71
23
43
47
73
79
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
The Ulam spiral becomes more visually obvious as the grid increases in size.
Task
For any sized N × N grid, construct and show an Ulam spiral (counter-clockwise) of primes starting at some specified initial number (the default would be 1), with some suitably dotty (glyph) representation to indicate primes, and the absence of dots to indicate non-primes.
You should demonstrate the generator by showing at Ulam prime spiral large enough to (almost) fill your terminal screen.
Related tasks
Spiral matrix
Zig-zag matrix
Identity matrix
Sequence of primes by Trial Division
See also
Wikipedia entry: Ulam spiral
MathWorld™ entry: Prime Spiral
| #Pascal | Pascal |
Program Ulam; Uses crt;
{Concocted by R.N.McLean (whom God preserve), ex Victoria university, NZ.}
{$B- evaluate boolean expressions only so far as necessary.}
{$R+ range checking...}
FUNCTION Trim(S : string) : string;
var L1,L2 : integer;
BEGIN
L1 := 1;
WHILE (L1 <= LENGTH(S)) AND (S[L1] = ' ') DO INC(L1);
L2 := LENGTH(S);
WHILE (S[L2] = ' ') AND (L2 > L1) DO DEC(L2);
IF L2 >= L1 THEN Trim := COPY(S,L1,L2 - L1 + 1) ELSE Trim := '';
END; {Of Trim.}
FUNCTION Ifmt(Digits : integer) : string;
var S : string[255];
BEGIN
STR(Digits,S);
Ifmt := Trim(S);
END; { Ifmt }
Function min(i,j: integer): integer;
begin
if i <= j then min:=i else min:=j;
end;
Procedure Croak(Gasp: string); {A lethal word.}
Begin
WriteLn;
WriteLn(Gasp);
HALT; {This way to the egress...}
End;
var ScreenLine,ScreenColumn: byte; {Line and column position.}
{=========================enough support===================}
const Mstyle = 6; {Display different results.}
const StyleName: array[1..Mstyle] of string = ('IsPrime','First Prime Factor Index',
'First Prime Factor','Number of Prime Factors',
'Sum of Prime Factors','Sum of Proper Factors');
const OrderLimit = 49; Limit2 = OrderLimit*OrderLimit; {A 50-line screen has room for a heading.}
var Tile: array[1..OrderLimit,1..OrderLimit] of integer; {Alas, can't put [Order,Order], only constants.}
var FirstPrimeFactorIndex,FirstPrimeFactor,NumPFactor,SumPFactor,SumFactor: array[1..Limit2] of integer;
const enuffP = 17; {Given the value of Limit2.}
const Prime: array[1..enuffP] of integer = (1,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53);
Procedure Prepare; {Various arrays are to be filled for the different styles.}
var i,j,p: integer;
Begin
for i:=1 to limit2 do {Alas, can't just put A:=0;}
begin {Nor clear A;}
FirstPrimeFactorIndex[i]:=1; {Prime[1] = 1, so this means no other divisor.}
FirstPrimeFactor[i]:=0;
NumPFactor[i]:=0;
SumPFactor[i]:=0;
SumFactor[i]:=1; {1 is counted as a proper factor.}
end;
FirstPrimeFactorIndex[1]:=0; {Fiddle, as 1 is not a prime number.}
SumFactor[1]:=0; {N is not a proper factor of N, so 1 has no proper factors...}
for i:=2 to enuffP do {Prime[1] = 1, Prime[2] = 2, so start with i = 2.}
begin
p:=Prime[i];
j:=p + p;
while j <= Limit2 do
begin
if FirstPrimeFactorIndex[j] = 1 then FirstPrimeFactorIndex[j]:=i;
if FirstPrimeFactor[j] = 0 then FirstPrimeFactor[j]:=p;
SumPFactor[j]:=SumPFactor[j] + p;
inc(NumPFactor[j]);
j:=j + p;
end;
end;
for i:=2 to Limit2 div 2 do {Step through all possible proper factors.}
begin {N is not a proper factor of N, so start at 2N,}
j:=2*i; {for which N is a proper factor of 2N.}
while j <= Limit2 do {Sigh. for j:=2*i:Limit2:i do ... Next i;}
begin
SumFactor[j]:=SumFactor[j] + i;
j:=j + i;
end;
end;
End; {Enough preparation.}
const enuffC = 11; {Perhaps the colours will highlight interesting patterns.}
const colour:array[0..enuffC] of byte = (black,white,LightRed,
LightMagenta,Yellow,LightGreen,LightCyan,LightBlue,LightGray,
Red,Green,DarkGray); {Colours on the screen don't always match their name!}
Procedure UlamSpiral(Order,Start,Style: integer); {Generate the numbers, then display.}
Function Encode(N: integer): integer; {Acording to Style, choose a result to show.}
Begin
if N <= 1 then Encode:=0
else
case style of
1:if FirstPrimeFactorIndex[N] = 1 then Encode:=1 else Encode:=0; {1 = Prime.}
2:Encode:=FirstPrimeFactorIndex[N];
3:Encode:=FirstPrimeFactor[N];
4:Encode:=NumPFactor[N];
5:Encode:=SumPFactor[N];
6:Encode:=SumFactor[N];
end;
End; {So much for encoding.}
var Place,Way: array[1..2] of integer; {Complex numbers.}
var m, {Middle.}
N, {Counter.}
length, {length of a side.}
lunge, {two lunges for each length.}
step {steps to make up a lunge of some length.}
: integer;
var i,j: integer; {Steppers.}
var code,it: integer; {Mess with the results.}
label XX; {Escape the second lunge.}
var OutF: text; {Utter drivel. It is a disc file.}
Begin
Write('Ulam Spiral, order ',Order,', start ',Start,', style ',style); {Start the heading.}
if style <= 0 then Croak('Must be a positive style');
if style > Mstyle then croak('Last known style is '+ifmt(Mstyle));
if Order > OrderLimit then Croak('Array OrderLimit is order '+IFmt(OrderLimit));
if Order mod 2 <>1 then Croak('The order must be an odd number!');
writeln(': ',StyleName[Style]); {Finish the heading. The pattern starts with line two.}
Assign(OutF,'Ulam.txt'); Rewrite(OutF); Writeln(OutF,'Ulam spiral: the codes for ',StyleName[style]);
m:=order div 2 + 1; {This is why Order must be odd.}
Place[1]:=m; Place[2]:=m; {Start at the middle.}
way[1]:=1; way[2]:=0; {Initial direction is along the x-axis.}
n:=Start;
for length:=1 to Order do {Advance through the lengths.}
for lunge:=1 to 2 do {Two lunges for each length.}
begin
for step:=1 to length do {Make the steps.}
begin
Tile[Place[1],Place[2]]:=N;
for i:=1 to 2 do Place[i]:=Place[i] + Way[i]; {Place:=Place + Way;}
N:=N + 1;
end;
if N >= Order*Order then goto XX; {Each corner piece is part of two lunges.}
i:=Way[1]; Way[1]:=-Way[2]; Way[2]:=i; {Way:=Way*(0,1) in complex numbers: (x,y)*(0,1) = (-y,x).}
end;
XX:for i:=order downto 1 do {Output: Lines count downwards, y runs upwards.}
begin {The first line is the topmost y.}
for j:=1 to order do {(line,column) = (y,x).}
begin {Work along the line.}
it:=Tile[j,i]; {Grab the number.}
code:=Encode(it); {Presentation scheme.}
Write(OutF,'(',it:4,':',code:2,')'); {Debugging...}
if FirstPrimeFactorIndex[it] > 1 then TextBackGround(Black) {Not a prime.}
else if it = 1 then TextBackGround(Black) {Darkness for one, also.}
else TextBackGround(White); {A prime number!}
TextColor(Colour[min(code,enuffC)]); {A lot of fuss for this!}
{Write(code:2);}
{Write(it:3);}
if it <= 9 then write(it) else Write('*'); {Thus mark the centre.}
end; {Next position along the line.}
if i > 1 then WriteLn; {Ending the last line would scroll the heading up.}
WriteLn(OutF); {But this is good for the text file.}
end; {On to the next line.}
Close(OutF); {Finished with the trace.}
{Some revelations to help in choosing a colour sequence.}
ScreenLine:=WhereY; ScreenColumn:=WhereX; {Gibberish to find the location.}
if Style > 1 then {Only the fancier styles go beyond 0 and 1.}
begin {So explain only for them.}
GoToXY(ScreenColumn + 1,ScreenLine - 4); {Unused space is to the right.}
TextColor(White); write('Colour sequence'); {Given 80-column displays.}
GoToXY(ScreenColumn + 1,ScreenLine - 3); {And no more than 50 lines.}
for i:=1 to enuffC do begin TextColor(Colour[i]); write(i); end; {My sequence.}
GoToXY(ScreenColumn + 1,ScreenLine - 2);
TextColor(White); write('From options');
GoToXY(ScreenColumn + 1,ScreenLine - 1);
for i:=1 to 15 do begin TextColor(i);write(i); end; {The options.}
end;
End; {of UlamSpiral.}
var start,wot,order: integer; {A selector.}
BEGIN {After all that.}
TextMode(Lo(LastMode) + Font8x8); {Gibberish sets 43 lines on EGA and 50 on VGA.}
ClrScr; TextColor(White); {This also gives character blocks that are almost square...}
WriteLn('Presents consecutive integers in a spiral, as per Stanislaw Ulam.');
WriteLn('Starting with 1, runs up to Order*Order.');
Write('What value for Order? (Limit ' + Ifmt(OrderLimit),'): ');
ReadLn(Order); {ReadKey needs no "enter", but requires decoding.}
if (order < 1) or (order > OrderLimit) then Croak('Out of range!'); {Oh dear.}
Prepare;
wot:=1; {The original task.}
Repeat {Until bored?}
ClrScr; {Scrub any previous stuff.}
UlamSpiral(Order,1,wot); {The deed!}
GoToXY(ScreenColumn + 1,ScreenLine); {Note that the last WriteLn was skipped.}
TextColor(White); Write('Enter 0, or 1 to '+Ifmt(Mstyle),': '); {Wot now?}
ReadLn(wot); {Receive.}
Until (wot <= 0) or (wot > Mstyle); {Alas, "Enter" must be pressed.}
END.
|
http://rosettacode.org/wiki/Truncatable_primes | Truncatable primes | A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.
Examples
The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.
The number 7393 is a right-truncatable prime as the numbers 7393, 739, 73, and 7 formed by removing digits from its right are also prime.
No zeroes are allowed in truncatable primes.
Task
The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied).
Related tasks
Find largest left truncatable prime in a given base
Sieve of Eratosthenes
See also
Truncatable Prime from MathWorld.]
| #Fortran | Fortran | module primes_mod
implicit none
logical, allocatable :: primes(:)
contains
subroutine Genprimes(parr)
logical, intent(in out) :: parr(:)
integer :: i
! Prime sieve
parr = .true.
parr (1) = .false.
parr (4 : size(parr) : 2) = .false.
do i = 3, int (sqrt (real (size(parr)))), 2
if (parr(i)) parr(i * i : size(parr) : i) = .false.
end do
end subroutine
function is_rtp(candidate)
logical :: is_rtp
integer, intent(in) :: candidate
integer :: n
is_rtp = .true.
n = candidate / 10
do while(n > 0)
if(.not. primes(n)) then
is_rtp = .false.
return
end if
n = n / 10
end do
end function
function is_ltp(candidate)
logical :: is_ltp
integer, intent(in) :: candidate
integer :: i, n
character(10) :: nstr
write(nstr, "(i10)") candidate
is_ltp = .true.
do i = len_trim(nstr)-1, 1, -1
n = mod(candidate, 10**i)
if(.not. primes(n)) then
is_ltp = .false.
return
end if
end do
end function
end module primes_mod
program Truncatable_Primes
use primes_mod
implicit none
integer, parameter :: limit = 999999
integer :: i
character(10) :: nstr
! Generate an array of prime flags up to limit of search
allocate(primes(limit))
call Genprimes(primes)
! Find left truncatable prime
do i = limit, 1, -1
write(nstr, "(i10)") i
if(index(trim(nstr), "0") /= 0) cycle ! check for 0 in number
if(is_ltp(i)) then
write(*, "(a, i0)") "Largest left truncatable prime below 1000000 is ", i
exit
end if
end do
! Find right truncatable prime
do i = limit, 1, -1
write(nstr, "(i10)") i
if(index(trim(nstr), "0") /= 0) cycle ! check for 0 in number
if(is_rtp(i)) then
write(*, "(a, i0)") "Largest right truncatable prime below 1000000 is ", i
exit
end if
end do
end program |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
See also
Wikipedia article: Tree traversal.
| #Agda | Agda | open import Data.List using (List; _∷_; []; concat)
open import Data.Nat using (ℕ; suc; zero)
open import Level using (Level)
open import Relation.Binary.PropositionalEquality using (_≡_; refl)
data Tree {a} (A : Set a) : Set a where
leaf : Tree A
node : A → Tree A → Tree A → Tree A
variable
a : Level
A : Set a
preorder : Tree A → List A
preorder tr = go tr []
where
go : Tree A → List A → List A
go leaf ys = ys
go (node x ls rs) ys = x ∷ go ls (go rs ys)
inorder : Tree A → List A
inorder tr = go tr []
where
go : Tree A → List A → List A
go leaf ys = ys
go (node x ls rs) ys = go ls (x ∷ go rs ys)
postorder : Tree A → List A
postorder tr = go tr []
where
go : Tree A → List A → List A
go leaf ys = ys
go (node x ls rs) ys = go ls (go rs (x ∷ ys))
level-order : Tree A → List A
level-order tr = concat (go tr [])
where
go : Tree A → List (List A) → List (List A)
go leaf qs = qs
go (node x ls rs) [] = (x ∷ []) ∷ go ls (go rs [])
go (node x ls rs) (q ∷ qs) = (x ∷ q ) ∷ go ls (go rs qs)
example-tree : Tree ℕ
example-tree =
node 1
(node 2
(node 4
(node 7
leaf
leaf)
leaf)
(node 5
leaf
leaf))
(node 3
(node 6
(node 8
leaf
leaf)
(node 9
leaf
leaf))
leaf)
_ : preorder example-tree ≡ 1 ∷ 2 ∷ 4 ∷ 7 ∷ 5 ∷ 3 ∷ 6 ∷ 8 ∷ 9 ∷ []
_ = refl
_ : inorder example-tree ≡ 7 ∷ 4 ∷ 2 ∷ 5 ∷ 1 ∷ 8 ∷ 6 ∷ 9 ∷ 3 ∷ []
_ = refl
_ : postorder example-tree ≡ 7 ∷ 4 ∷ 5 ∷ 2 ∷ 8 ∷ 9 ∷ 6 ∷ 3 ∷ 1 ∷ []
_ = refl
_ : level-order example-tree ≡ 1 ∷ 2 ∷ 3 ∷ 4 ∷ 5 ∷ 6 ∷ 7 ∷ 8 ∷ 9 ∷ []
_ = refl |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #PicoLisp | PicoLisp | PicoLisp sets the value of the variable (symbol) '@' to the result of
conditional and controlling expressions in flow- and logic-functions (cond, if,
and, when, while, etc.).
Within a function or method '@' behaves like a local variable, i.e. its value is
automatically saved upon function entry and restored at exit.
For example, to read the current input channel until EOF, and print the square
of every item which is a number: |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #PowerShell | PowerShell |
65..67 | ForEach-Object {$_ * 2} # Multiply the numbers by 2
65..67 | ForEach-Object {[char]$_ } # ASCII values of the numbers
|
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #Python | Python | >>> 3
3
>>> _*_, _**0.5
(9, 1.7320508075688772)
>>> |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #Racket | Racket |
#lang racket
(module topic1 racket
;; define $ as a "parameter", but make it look like a plain identifier
(provide $ (rename-out [$if if] [$#%app #%app]))
(define current-value (make-parameter #f))
(define-syntax $
(syntax-id-rules (set!)
[(_ x ...) ((current-value) x ...)]
[(set! _ val) (current-value val)]
[_ (current-value)]))
;; make an `if' form that binds it to the condition result
(define-syntax-rule ($if C T E)
(parameterize ([current-value C])
(if $ T E)))
;; function application with []s uses the topic variable for the first arg
(define-syntax ($#%app stx)
(syntax-case stx ()
[(_ f x y ...) (equal? #\[ (syntax-property stx 'paren-shape))
#'(parameterize ([current-value x]) (f y ...))]
[(_ f x ...) #'(f x ...)])))
(module topic2 racket
;; better variant: define `$' as a syntax parameter, which is adjusted to an
;; actual local binding; make it work in `if', and have a function definition
;; form that binds it to the actual arguments
(provide $ (rename-out [$if if]) defun)
(require racket/stxparam)
(define-syntax-parameter $ (λ(stx) (raise-syntax-error '$ "not in scope")))
(define-syntax-rule ($if C T E)
(let ([c C]) (syntax-parameterize ([$ (make-rename-transformer #'c)])
(if c T E))))
(define-syntax-rule (defun name body ...)
(define (name arg)
(syntax-parameterize ([$ (make-rename-transformer #'arg)])
body ...)))
)
(module sample1 racket
(require (submod ".." topic1))
(if (memq 2 '(1 2 3)) (cadr $) 'missing)
;; => 3
(define (foo) (list (sqrt $) (* $ $)))
[foo 9]
;; => '(3 81)
)
(require 'sample1)
(module sample2 racket
(require (submod ".." topic2))
(if (memq 2 '(1 2 3)) (cadr $) 'missing)
;; => 3
(defun foo (list (sqrt $) (* $ $)))
(foo 9)
;; => '(3 81)
)
(require 'sample2)
|
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #Raku | Raku | $_ = 'Outside';
for <3 5 7 10> {
print $_;
.³.map: { say join "\t", '', $_, .², .sqrt, .log(2), OUTER::<$_>, UNIT::<$_> }
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #8th | 8th |
5 var, disks
var sa
var sb
var sc
: save sc ! sb ! sa ! disks ! ;
: get sa @ sb @ sc @ ;
: get2 get swap ;
: hanoi
save disks @ not if ;; then
disks @ get
disks @ n:1- get2 hanoi save
cr
" move a ring from " . sa @ . " to " . sb @ .
disks @ n:1- get2 rot hanoi
;
" Tower of Hanoi, with " . disks @ . " rings: " .
disks @ 1 2 3 hanoi cr bye
|
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping | Tokenize a string with escaping | Task[edit]
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
It should accept three input parameters:
The string
The separator character
The escape character
It should output a list of strings.
Details
Rules for splitting:
The fields that were separated by the separators, become the elements of the output list.
Empty fields should be preserved, even at the start and end.
Rules for escaping:
"Escaped" means preceded by an occurrence of the escape character that is not already escaped itself.
When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special).
Each occurrence of the escape character that was used to escape something, should not become part of the output.
Test case
Demonstrate that your function satisfies the following test-case:
Input
Output
string:
one^|uno||three^^^^|four^^^|^cuatro|
separator character:
|
escape character:
^
one|uno
three^^
four^|cuatro
(Print the output list in any format you like, as long as it is it easy to see what the fields are.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #8080_Assembly | 8080 Assembly | org 100h
jmp demo
;;; Routine to split a 0-terminated string
;;; Input: B=separator, C=escape, HL=string pointer.
;;; Output: DE=end of list of strings
;;; The split strings are stored in place.
split: mov d,h ; Set DE = output pointer
mov e,l
snext: mov a,m ; Get current input character
inx h ; Advance input pointer
stax d ; Write character at output pointer
ana a ; If zero, we are done
rz
cmp c ; Is it the escape character?
jz sesc
cmp b ; Is it the separator character?
jz ssep
inx d ; Otherwise, advance output pointer,
jmp snext ; and get the next character
sesc: mov a,m ; Store the escaped character without
inx h ; checking for anything except zero.
stax d
inx d
ana a ; Zero is still end of string
rz
jmp snext
ssep: xra a ; End of string, write zero terminator
stax d
inx d
jmp snext
;;; Use the routine to split the test-case string
demo: mvi b,'|' ; Separator character
mvi c,'^' ; Escape character
lxi h,test ; Pointer to test string
call split
;;; Print each string on its own line
lxi h,test
str: call puts ; Print string
call cmp16 ; Are we there yet?
jnc str ; If not, print the next string
ret
;;; 16-bit compare
cmp16: mov a,d
cmp h
rnz
mov a,e
cmp l
ret
;;; Print zero-terminated string with newline
puts: push d ; Keep DE registers
push h ; Keep pointer
lxi d,pfx ; Print prefix
mvi c,9
call 5
pop h ; Restore pointer
ploop: mov e,m ; Get current character
push h ; Keep pointer
mvi c,2 ; CP/M print character
call 5
pop h ; Restore pointer
mov a,m ; Is character zero?
ora a
inx h ; Increment pointer
jnz ploop ; If not, there are more characters
push h ; Keep pointer
lxi d,nl ; Write newline
mvi c,9 ; CP/M print string
call 5
pop h
pop d ; Restore DE registers
ret
pfx: db '> $' ; Prefix to make the output more obvious
nl: db 13,10,'$'
test: db 'one^|uno||three^^^^|four^^^|^cuatro|',0 |
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping | Tokenize a string with escaping | Task[edit]
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
It should accept three input parameters:
The string
The separator character
The escape character
It should output a list of strings.
Details
Rules for splitting:
The fields that were separated by the separators, become the elements of the output list.
Empty fields should be preserved, even at the start and end.
Rules for escaping:
"Escaped" means preceded by an occurrence of the escape character that is not already escaped itself.
When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special).
Each occurrence of the escape character that was used to escape something, should not become part of the output.
Test case
Demonstrate that your function satisfies the following test-case:
Input
Output
string:
one^|uno||three^^^^|four^^^|^cuatro|
separator character:
|
escape character:
^
one|uno
three^^
four^|cuatro
(Print the output list in any format you like, as long as it is it easy to see what the fields are.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Action.21 | Action! | DEFINE PTR="CARD"
TYPE Tokens=[
PTR buf ;BYTE ARRAY
PTR arr ;CARD ARRAY
PTR endPtr
BYTE count]
PROC Init(Tokens POINTER t BYTE ARRAY b PTR ARRAY a)
t.buf=b
t.arr=a
t.endPtr=b
t.count=0
RETURN
PROC AddToken(Tokens POINTER t CHAR ARRAY s)
PTR ARRAY a
CHAR ARRAY tmp
a=t.arr
tmp=t.endPtr
SCopy(tmp,s)
a(t.count)=tmp
t.count==+1
t.endPtr=t.endPtr+s(0)+1
RETURN
PROC PrintTokens(Tokens POINTER t)
BYTE i
PTR ARRAY a
a=t.arr
FOR i=0 TO t.count-1
DO
PrintF("""%S""%E",a(i))
OD
RETURN
PROC Append(CHAR ARRAY s CHAR c)
s(0)==+1
s(s(0))=c
RETURN
PROC Tokenize(CHAR ARRAY s CHAR sep,esc Tokens POINTER res)
BYTE ARRAY b(200)
PTR ARRAY a(20)
CHAR ARRAY tmp(255)
BYTE i,isEsc
CHAR c
Init(res,b,a)
isEsc=0
tmp(0)=0
FOR i=1 TO s(0)
DO
c=s(i)
IF isEsc THEN
isEsc=0
Append(tmp,c)
ELSE
IF c=esc THEN
isEsc=1
ELSEIF c=sep THEN
AddToken(res,tmp)
tmp(0)=0
ELSE
Append(tmp,c)
FI
FI
OD
AddToken(res,tmp)
RETURN
PROC Main()
Tokens t
Tokenize("one^|uno||three^^^^|four^^^|^cuatro|",'|,'^,t)
PrintTokens(t)
RETURN |
http://rosettacode.org/wiki/Total_circles_area | Total circles area | Total circles area
You are encouraged to solve this task according to the task description, using any language you may know.
Example circles
Example circles filtered
Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal digits of precision. The area covered by two or more disks needs to be counted only once.
One point of this Task is also to compare and discuss the relative merits of various solution strategies, their performance, precision and simplicity. This means keeping both slower and faster solutions for a language (like C) is welcome.
To allow a better comparison of the different implementations, solve the problem with this standard dataset, each line contains the x and y coordinates of the centers of the disks and their radii (11 disks are fully contained inside other disks):
xc yc radius
1.6417233788 1.6121789534 0.0848270516
-1.4944608174 1.2077959613 1.1039549836
0.6110294452 -0.6907087527 0.9089162485
0.3844862411 0.2923344616 0.2375743054
-0.2495892950 -0.3832854473 1.0845181219
1.7813504266 1.6178237031 0.8162655711
-0.1985249206 -0.8343333301 0.0538864941
-1.7011985145 -0.1263820964 0.4776976918
-0.4319462812 1.4104420482 0.7886291537
0.2178372997 -0.9499557344 0.0357871187
-0.6294854565 -1.3078893852 0.7653357688
1.7952608455 0.6281269104 0.2727652452
1.4168575317 1.0683357171 1.1016025378
1.4637371396 0.9463877418 1.1846214562
-0.5263668798 1.7315156631 1.4428514068
-1.2197352481 0.9144146579 1.0727263474
-0.1389358881 0.1092805780 0.7350208828
1.5293954595 0.0030278255 1.2472867347
-0.5258728625 1.3782633069 1.3495508831
-0.1403562064 0.2437382535 1.3804956588
0.8055826339 -0.0482092025 0.3327165165
-0.6311979224 0.7184578971 0.2491045282
1.4685857879 -0.8347049536 1.3670667538
-0.6855727502 1.6465021616 1.0593087096
0.0152957411 0.0638919221 0.9771215985
The result is 21.56503660... .
Related task
Circles of given radius through two points.
See also
http://www.reddit.com/r/dailyprogrammer/comments/zff9o/9062012_challenge_96_difficult_water_droplets/
http://stackoverflow.com/a/1667789/10562
| #EchoLisp | EchoLisp |
(lib 'math)
(define (make-circle x0 y0 r)
(vector x0 y0 r ))
(define-syntax-id _.radius (_ 2))
(define-syntax-id _.x0 (_ 0))
(define-syntax-id _.y0 (_ 1))
;; to sort circles
(define (cmp-circles a b) (> a.radius b.radius))
(define (included? circle: a circles)
(for/or ((b circles))
#:continue (equal? a b)
(disk-in-disk? a b)))
;; eliminates, and sort
(define (sort-circles circles)
(list-sort cmp-circles
(filter (lambda(c) (not (included? c circles))) circles)))
(define circles (sort-circles
(list (make-circle 1.6417233788 1.6121789534 0.0848270516)
(make-circle -1.4944608174 1.2077959613 1.1039549836)
(make-circle 0.6110294452 -0.6907087527 0.9089162485)
(make-circle 0.3844862411 0.2923344616 0.2375743054)
(make-circle -0.2495892950 -0.3832854473 1.0845181219)
(make-circle 1.7813504266 1.6178237031 0.8162655711)
(make-circle -0.1985249206 -0.8343333301 0.0538864941)
(make-circle -1.7011985145 -0.1263820964 0.4776976918)
(make-circle -0.4319462812 1.4104420482 0.7886291537)
(make-circle 0.2178372997 -0.9499557344 0.0357871187)
(make-circle -0.6294854565 -1.3078893852 0.7653357688)
(make-circle 1.7952608455 0.6281269104 0.2727652452)
(make-circle 1.4168575317 1.0683357171 1.1016025378)
(make-circle 1.4637371396 0.9463877418 1.1846214562)
(make-circle -0.5263668798 1.7315156631 1.4428514068)
(make-circle -1.2197352481 0.9144146579 1.0727263474)
(make-circle -0.1389358881 0.1092805780 0.7350208828)
(make-circle 1.5293954595 0.0030278255 1.2472867347)
(make-circle -0.5258728625 1.3782633069 1.3495508831)
(make-circle -0.1403562064 0.2437382535 1.3804956588)
(make-circle 0.8055826339 -0.0482092025 0.3327165165)
(make-circle -0.6311979224 0.7184578971 0.2491045282)
(make-circle 1.4685857879 -0.8347049536 1.3670667538)
(make-circle -0.6855727502 1.6465021616 1.0593087096)
(make-circle 0.0152957411 0.0638919221 0.9771215985))))
;; bounding box
(define (enclosing-rect circles)
(define xmin (for/min ((c circles)) (- c.x0 c.radius)))
(define xmax (for/max ((c circles)) (+ c.x0 c.radius)))
(define ymin (for/min ((c circles)) (- c.y0 c.radius)))
(define ymax (for/max ((c circles)) (+ c.y0 c.radius)))
(vector xmin ymin (- xmax xmin) (- ymax ymin)))
;; Compute surface of entirely overlapped tiles
;; and assign candidates circles to other tiles.
;; cands is a vector nsteps x nsteps of circles lists indexed by (i,j)
(define (S0 circles rect steps into: cands)
(define dx (// (rect 2) steps)) ;; width / steps
(define dy (// (rect 3) steps)) ;; height / steps
(define ds (* dx dy)) ;; tile surface
(define dr (vector (- rect.x0 dx) (- rect.y0 dy) dx dy))
(define ijdx 0)
(for/sum ((i steps))
(vector+= dr 0 dx)
(vector-set! dr 1 (- rect.y0 dy))
(for/sum ((j steps))
(vector+= dr 1 dy)
(set! ijdx (+ i (* j steps)))
(for/sum ((c circles))
#:break (rect-in-disk? dr c) ;; enclosed ? add ds
=> (begin (vector-set! cands ijdx null) ds)
#:continue (not (rect-disk-intersect? dr c))
;; intersects ? add circle to candidates for this tile
(vector-set! cands ijdx (cons c (cands ijdx )))
0)
)))
(define ct 0)
;; return sum of surfaces of tiles which are not entirely overlapped
(define (S circles rect steps cands)
(++ ct)
(define dx (// (rect 2) steps))
(define dy (// (rect 3) steps))
(define ds (* dx dy))
(define dr (vector (- rect.x0 dx) (- rect.y0 dy) dx dy))
(define ijdx 0)
(for/sum ((i steps))
(vector+= dr 0 dx)
(vector-set! dr 1 (- (rect 1) dy))
(for/sum ((j steps))
(vector+= dr 1 dy)
(when (!null? cands) (set! circles (cands (+ i (* j steps)))))
#:continue (null? circles)
;; add surface
(or
(for/or ((c circles)) ;; enclosed ? add ds
#:break (rect-in-disk? dr c) => ds
#f )
(if ;; not intersecting? add 0
(for/or ((c circles))
(rect-disk-intersect? dr c)) #f 0)
;; intersecting ? recurse until precision
(when (> dx s-precision) (S circles dr 2 null))
;; no hope - add ds/2
(// ds 2))
)))
|
http://rosettacode.org/wiki/Topological_sort | Topological sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon.
The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on.
A tool exists that extracts library dependencies.
Task
Write a function that will return a valid compile order of VHDL libraries from their dependencies.
Assume library names are single words.
Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given.
Any self dependencies should be ignored.
Any un-orderable dependencies should be flagged.
Use the following data as an example:
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys
Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01.
C.f.
Topological sort/Extracted top item.
There are two popular algorithms for topological sorting:
Kahn's 1962 topological sort [1]
depth-first search [2] [3]
| #11l | 11l | V data = [
‘des_system_lib’ = Set(‘std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee’.split(‘ ’)),
‘dw01’ = Set(‘ieee dw01 dware gtech’.split(‘ ’)),
‘dw02’ = Set(‘ieee dw02 dware’.split(‘ ’)),
‘dw03’ = Set(‘std synopsys dware dw03 dw02 dw01 ieee gtech’.split(‘ ’)),
‘dw04’ = Set(‘dw04 ieee dw01 dware gtech’.split(‘ ’)),
‘dw05’ = Set(‘dw05 ieee dware’.split(‘ ’)),
‘dw06’ = Set(‘dw06 ieee dware’.split(‘ ’)),
‘dw07’ = Set(‘ieee dware’.split(‘ ’)),
‘dware’ = Set(‘ieee dware’.split(‘ ’)),
‘gtech’ = Set(‘ieee gtech’.split(‘ ’)),
‘ramlib’ = Set(‘std ieee’.split(‘ ’)),
‘std_cell_lib’ = Set(‘ieee std_cell_lib’.split(‘ ’)),
‘synopsys’ = Set[String]()
]
F toposort2(&data)
L(k, v) data
v.discard(k)
Set[String] extra_items_in_deps
L(v) data.values()
extra_items_in_deps.update(v)
extra_items_in_deps = extra_items_in_deps - Set(data.keys())
L(item) extra_items_in_deps
data[item] = Set[String]()
[String] r
L
Set[String] ordered
L(item, dep) data
I dep.empty
ordered.add(item)
I ordered.empty
L.break
r.append(sorted(Array(ordered)).join(‘ ’))
[String = Set[String]] new_data
L(item, dep) data
I item !C ordered
new_data[item] = dep - ordered
data = move(new_data)
assert(data.empty, ‘A cyclic dependency exists’)
R r
print(toposort2(&data).join("\n")) |
http://rosettacode.org/wiki/Universal_Turing_machine | Universal Turing machine | One of the foundational mathematical constructs behind computer science
is the universal Turing Machine.
(Alan Turing introduced the idea of such a machine in 1936–1937.)
Indeed one way to definitively prove that a language
is turing-complete
is to implement a universal Turing machine in it.
Task
Simulate such a machine capable
of taking the definition of any other Turing machine and executing it.
Of course, you will not have an infinite tape,
but you should emulate this as much as is possible.
The three permissible actions on the tape are "left", "right" and "stay".
To test your universal Turing machine (and prove your programming language
is Turing complete!), you should execute the following two Turing machines
based on the following definitions.
Simple incrementer
States: q0, qf
Initial state: q0
Terminating states: qf
Permissible symbols: B, 1
Blank symbol: B
Rules:
(q0, 1, 1, right, q0)
(q0, B, 1, stay, qf)
The input for this machine should be a tape of 1 1 1
Three-state busy beaver
States: a, b, c, halt
Initial state: a
Terminating states: halt
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(a, 0, 1, right, b)
(a, 1, 1, left, c)
(b, 0, 1, left, a)
(b, 1, 1, right, b)
(c, 0, 1, left, b)
(c, 1, 1, stay, halt)
The input for this machine should be an empty tape.
Bonus:
5-state, 2-symbol probable Busy Beaver machine from Wikipedia
States: A, B, C, D, E, H
Initial state: A
Terminating states: H
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(A, 0, 1, right, B)
(A, 1, 1, left, C)
(B, 0, 1, right, C)
(B, 1, 1, right, B)
(C, 0, 1, right, D)
(C, 1, 0, left, E)
(D, 0, 1, left, A)
(D, 1, 1, left, D)
(E, 0, 1, stay, H)
(E, 1, 0, left, A)
The input for this machine should be an empty tape.
This machine runs for more than 47 millions steps.
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | transitions(:
local :t {}
while /= ) dup:
set-to t swap & rot & rot rot &
t drop
take-from tape:
if tape:
pop-from tape
else:
:B
paste-together a h b:
push-to b h
while a:
push-to b pop-from a
b
universal-turing-machine transitions initial final tape:
local :tape-left []
local :state initial
local :head take-from tape
local :move { :stay @pass }
move!left:
push-to tape head
set :head take-from tape-left
move!right:
push-to tape-left head
set :head take-from tape
while /= state final:
if opt-get transitions & state head:
set :state &<>
set :head &<>
move!
else:
return paste-together tape-left head tape
paste-together tape-left head tape |
http://rosettacode.org/wiki/Totient_function | Totient function | The totient function is also known as:
Euler's totient function
Euler's phi totient function
phi totient function
Φ function (uppercase Greek phi)
φ function (lowercase Greek phi)
Definitions (as per number theory)
The totient function:
counts the integers up to a given positive integer n that are relatively prime to n
counts the integers k in the range 1 ≤ k ≤ n for which the greatest common divisor gcd(n,k) is equal to 1
counts numbers ≤ n and prime to n
If the totient number (for N) is one less than N, then N is prime.
Task
Create a totient function and:
Find and display (1 per line) for the 1st 25 integers:
the integer (the index)
the totient number for that integer
indicate if that integer is prime
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000 (optional)
Show all output here.
Related task
Perfect totient numbers
Also see
Wikipedia: Euler's totient function.
MathWorld: totient function.
OEIS: Euler totient function phi(n).
| #C | C |
/*Abhishek Ghosh, 7th December 2018*/
#include<stdio.h>
int totient(int n){
int tot = n,i;
for(i=2;i*i<=n;i+=2){
if(n%i==0){
while(n%i==0)
n/=i;
tot-=tot/i;
}
if(i==2)
i=1;
}
if(n>1)
tot-=tot/n;
return tot;
}
int main()
{
int count = 0,n,tot;
printf(" n %c prime",237);
printf("\n---------------\n");
for(n=1;n<=25;n++){
tot = totient(n);
if(n-1 == tot)
count++;
printf("%2d %2d %s\n", n, tot, n-1 == tot?"True":"False");
}
printf("\nNumber of primes up to %6d =%4d\n", 25,count);
for(n = 26; n <= 100000; n++){
tot = totient(n);
if(tot == n-1)
count++;
if(n == 100 || n == 1000 || n%10000 == 0){
printf("\nNumber of primes up to %6d = %4d\n", n, count);
}
}
return 0;
}
|
http://rosettacode.org/wiki/Topswops | Topswops | Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is composed of reversing the first m cards where m is the value of the topmost card.
Rounds are repeated until the topmost card is the number 1 and the number of swaps is recorded.
For our example the swaps produce:
[2, 4, 1, 3] # Initial shuffle
[4, 2, 1, 3]
[3, 1, 2, 4]
[2, 1, 3, 4]
[1, 2, 3, 4]
For a total of four swaps from the initial ordering to produce the terminating case where 1 is on top.
For a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards.
Task
The task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive.
Note
Topswops is also known as Fannkuch from the German word Pfannkuchen meaning pancake.
Related tasks
Number reversal game
Sorting algorithms/Pancake sort
| #Haskell | Haskell | import Data.List (permutations)
topswops :: Int -> Int
topswops n = maximum $ map tops $ permutations [1 .. n]
where
tops (1:_) = 0
tops xa@(x:_) = 1 + tops reordered
where
reordered = reverse (take x xa) ++ drop x xa
main =
mapM_ (putStrLn . ((++) <$> show <*> (":\t" ++) . show . topswops)) [1 .. 10] |
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #BASIC | BASIC | pi = 3.141592653589793#
radians = pi / 4 'a.k.a. 45 degrees
degrees = 45 * pi / 180 'convert 45 degrees to radians once
PRINT SIN(radians) + " " + SIN(degrees) 'sine
PRINT COS(radians) + " " + COS(degrees) 'cosine
PRINT TAN(radians) + " " + TAN (degrees) 'tangent
'arcsin
thesin = SIN(radians)
arcsin = ATN(thesin / SQR(1 - thesin ^ 2))
PRINT arcsin + " " + arcsin * 180 / pi
'arccos
thecos = COS(radians)
arccos = 2 * ATN(SQR(1 - thecos ^ 2) / (1 + thecos))
PRINT arccos + " " + arccos * 180 / pi
PRINT ATN(TAN(radians)) + " " + ATN(TAN(radians)) * 180 / pi 'arctan |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.
From the wikipedia entry:
ask for 11 numbers to be read into a sequence S
reverse sequence S
for each item in sequence S
result := call a function to do an operation
if result overflows
alert user
else
print result
The task is to implement the algorithm:
Use the function:
f
(
x
)
=
|
x
|
0.5
+
5
x
3
{\displaystyle f(x)=|x|^{0.5}+5x^{3}}
The overflow condition is an answer of greater than 400.
The 'user alert' should not stop processing of other items of the sequence.
Print a prompt before accepting eleven, textual, numeric inputs.
You may optionally print the item as well as its associated result, but the results must be in reverse order of input.
The sequence S may be 'implied' and so not shown explicitly.
Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
| #Ela | Ela | open monad io number string
:::IO
take_numbers 0 xs = do
return $ iter xs
where f x = sqrt (toSingle x) + 5.0 * (x ** 3.0)
p x = x < 400.0
iter [] = return ()
iter (x::xs)
| p res = do
putStrLn (format "f({0}) = {1}" x res)
iter xs
| else = do
putStrLn (format "f({0}) :: Overflow" x)
iter xs
where res = f x
take_numbers n xs = do
x <- readAny
take_numbers (n - 1) (x::xs)
do
putStrLn "Please enter 11 numbers:"
take_numbers 11 [] |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.
From the wikipedia entry:
ask for 11 numbers to be read into a sequence S
reverse sequence S
for each item in sequence S
result := call a function to do an operation
if result overflows
alert user
else
print result
The task is to implement the algorithm:
Use the function:
f
(
x
)
=
|
x
|
0.5
+
5
x
3
{\displaystyle f(x)=|x|^{0.5}+5x^{3}}
The overflow condition is an answer of greater than 400.
The 'user alert' should not stop processing of other items of the sequence.
Print a prompt before accepting eleven, textual, numeric inputs.
You may optionally print the item as well as its associated result, but the results must be in reverse order of input.
The sequence S may be 'implied' and so not shown explicitly.
Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
| #Elena | Elena | import extensions;
import extensions'math;
public program()
{
real[] inputs := new real[](11);
console.printLine("Please enter 11 numbers :");
for(int i := 0, i < 11, i += 1)
{
inputs[i] := console.readLine().toReal()
};
console.printLine("Evaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :");
for(int i := 10, i >= 0, i -= 1)
{
real result := sqrt(abs(inputs[i])) + 5 * power(inputs[i], 3);
console.print("f(", inputs[i], ")=");
if (result > 400)
{
console.printLine("Overflow!")
}
else
{
console.printLine(result)
}
}
} |
http://rosettacode.org/wiki/Twelve_statements | Twelve statements | This puzzle is borrowed from math-frolic.blogspot.
Given the following twelve statements, which of them are true?
1. This is a numbered list of twelve statements.
2. Exactly 3 of the last 6 statements are true.
3. Exactly 2 of the even-numbered statements are true.
4. If statement 5 is true, then statements 6 and 7 are both true.
5. The 3 preceding statements are all false.
6. Exactly 4 of the odd-numbered statements are true.
7. Either statement 2 or 3 is true, but not both.
8. If statement 7 is true, then 5 and 6 are both true.
9. Exactly 3 of the first 6 statements are true.
10. The next two statements are both true.
11. Exactly 1 of statements 7, 8 and 9 are true.
12. Exactly 4 of the preceding statements are true.
Task
When you get tired of trying to figure it out in your head,
write a program to solve it, and print the correct answer or answers.
Extra credit
Print out a table of near misses, that is, solutions that are contradicted by only a single statement.
| #Python | Python |
from itertools import product
#from pprint import pprint as pp
constraintinfo = (
(lambda st: len(st) == 12 ,(1, 'This is a numbered list of twelve statements')),
(lambda st: sum(st[-6:]) == 3 ,(2, 'Exactly 3 of the last 6 statements are true')),
(lambda st: sum(st[1::2]) == 2 ,(3, 'Exactly 2 of the even-numbered statements are true')),
(lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')),
(lambda st: sum(st[1:4]) == 0 ,(5, 'The 3 preceding statements are all false')),
(lambda st: sum(st[0::2]) == 4 ,(6, 'Exactly 4 of the odd-numbered statements are true')),
(lambda st: sum(st[1:3]) == 1 ,(7, 'Either statement 2 or 3 is true, but not both')),
(lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')),
(lambda st: sum(st[:6]) == 3 ,(9, 'Exactly 3 of the first 6 statements are true')),
(lambda st: (st[10]&st[11]) ,(10, 'The next two statements are both true')),
(lambda st: sum(st[6:9]) == 1 ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')),
(lambda st: sum(st[0:11]) == 4 ,(12, 'Exactly 4 of the preceding statements are true')),
)
def printer(st, matches):
if False in matches:
print('Missed by one statement: %i, %s' % docs[matches.index(False)])
else:
print('Full match:')
print(' ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1)))
funcs, docs = zip(*constraintinfo)
full, partial = [], []
for st in product( *([(False, True)] * 12) ):
truths = [bool(func(st)) for func in funcs]
matches = [s == t for s,t in zip(st, truths)]
mcount = sum(matches)
if mcount == 12:
full.append((st, matches))
elif mcount == 11:
partial.append((st, matches))
for stm in full + partial:
printer(*stm) |
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.
| #PARI.2FGP | PARI/GP | vars(P)={
my(v=List(),x);
while(type(P)=="t_POL",
x=variable(P);
listput(v,x);
P=subst(P,x,1)
);
Vec(v)
};
truthTable(P)={
my(var=vars(P),t,b);
for(i=0,2^#var-1,
t=eval(P);
for(j=1,#var,
b=bittest(i,j-1);
t=subst(t,var[j],b);
print1(b)
);
print(!!t)
);
};
truthTable("x+y") \\ OR
truthTable("x*y") \\ AND |
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
| #Perl | Perl | use ntheory qw/is_prime/;
use Imager;
my $n = shift || 512;
my $start = shift || 1;
my $file = "ulam.png";
sub cell {
my($n, $x, $y, $start) = @_;
$y -= $n>>1;
$x -= ($n-1)>>1;
my $l = 2*(abs($x) > abs($y) ? abs($x) : abs($y));
my $d = ($y > $x) ? $l*3 + $x + $y : $l-$x-$y;
($l-1)**2 + $d + $start - 1;
}
my $black = Imager::Color->new('#000000');
my $white = Imager::Color->new('#FFFFFF');
my $img = Imager->new(xsize => $n, ysize => $n, channels => 1);
$img->box(filled=>1, color=>$white);
for my $y (0 .. $n-1) {
for my $x (0 .. $n-1) {
my $v = cell($n, $x, $y, $start);
$img->setpixel(x => $x, y => $y, color => $black) if is_prime($v);
}
}
$img->write(file => $file) or die "Cannot write $file: ", $img->errstr, "\n"; |
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.]
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function isPrime(n As Integer) As Boolean
If n Mod 2 = 0 Then Return n = 2
If n Mod 3 = 0 Then Return n = 3
Dim d As Integer = 5
While d * d <= n
If n Mod d = 0 Then Return False
d += 2
If n Mod d = 0 Then Return False
d += 4
Wend
Return True
End Function
Dim As UInteger i, j, p, pow, lMax = 2, rMax = 2
Dim s As String
' largest left truncatable prime less than 1000000
' It can't end with 1, 4, 6, 8 or 9 as these numbers are not prime
' Nor can it end in 2 if it has more than one digit as such a number would divide by 2
For i = 3 To 999997 Step 2
s = Str(i)
If Instr(s, "0") > 1 Then Continue For '' cannot contain 0
j = s[Len(s) - 1] - 48
If j = 1 OrElse j = 9 Then Continue For
p = i
pow = 10 ^ (Len(s) - 1)
While pow > 1
If Not isPrime(p) Then Continue For
p Mod= pow
pow \= 10
Wend
lMax = i
Next
' largest right truncatable prime less than 1000000
' It can't begin with 1, 4, 6, 8 or 9 as these numbers are not prime
For i = 3 To 799999 Step 2
s = Str(i)
If Instr(s, "0") > 1 Then Continue For '' cannot contain 0
j = s[0] - 48
If j = 1 OrElse j = 4 OrElse j = 6 Then Continue For
p = i
While p > 0
If Not isPrime(p) Then Continue For
p \= 10
Wend
rMax = i
Next
Print "Largest left truncatable prime : "; lMax
Print "Largest right truncatable prime : "; rMax
Print
Print "Press any key to quit"
Sleep |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
See also
Wikipedia article: Tree traversal.
| #ALGOL_68 | ALGOL 68 | MODE VALUE = INT;
PROC value repr = (VALUE value)STRING: whole(value, 0);
MODE NODES = STRUCT ( VALUE value, REF NODES left, right);
MODE NODE = REF NODES;
PROC tree = (VALUE value, NODE left, right)NODE:
HEAP NODES := (value, left, right);
PROC preorder = (NODE node, PROC (VALUE)VOID action)VOID:
IF node ISNT NODE(NIL) THEN
action(value OF node);
preorder(left OF node, action);
preorder(right OF node, action)
FI;
PROC inorder = (NODE node, PROC (VALUE)VOID action)VOID:
IF node ISNT NODE(NIL) THEN
inorder(left OF node, action);
action(value OF node);
inorder(right OF node, action)
FI;
PROC postorder = (NODE node, PROC (VALUE)VOID action)VOID:
IF node ISNT NODE(NIL) THEN
postorder(left OF node, action);
postorder(right OF node, action);
action(value OF node)
FI;
PROC destroy tree = (NODE node)VOID:
postorder(node, (VALUE skip)VOID:
# free(node) - PR garbage collect hint PR #
node := (SKIP, NIL, NIL)
);
# helper queue for level order #
MODE QNODES = STRUCT (REF QNODES next, NODE value);
MODE QNODE = REF QNODES;
MODE QUEUES = STRUCT (QNODE begin, end);
MODE QUEUE = REF QUEUES;
PROC enqueue = (QUEUE queue, NODE node)VOID:
(
HEAP QNODES qnode := (NIL, node);
IF end OF queue ISNT QNODE(NIL) THEN
next OF end OF queue
ELSE
begin OF queue
FI := end OF queue := qnode
);
PROC queue empty = (QUEUE queue)BOOL:
begin OF queue IS QNODE(NIL);
PROC dequeue = (QUEUE queue)NODE:
(
NODE out := value OF begin OF queue;
QNODE second := next OF begin OF queue;
# free(begin OF queue); PR garbage collect hint PR #
QNODE(begin OF queue) := (NIL, NIL);
begin OF queue := second;
IF queue empty(queue) THEN
end OF queue := begin OF queue
FI;
out
);
PROC level order = (NODE node, PROC (VALUE)VOID action)VOID:
(
HEAP QUEUES queue := (QNODE(NIL), QNODE(NIL));
enqueue(queue, node);
WHILE NOT queue empty(queue)
DO
NODE next := dequeue(queue);
IF next ISNT NODE(NIL) THEN
action(value OF next);
enqueue(queue, left OF next);
enqueue(queue, right OF next)
FI
OD
);
PROC print node = (VALUE value)VOID:
print((" ",value repr(value)));
main: (
NODE node := tree(1,
tree(2,
tree(4,
tree(7, NIL, NIL),
NIL),
tree(5, NIL, NIL)),
tree(3,
tree(6,
tree(8, NIL, NIL),
tree(9, NIL, NIL)),
NIL));
MODE TEST = STRUCT(
STRING name,
PROC(NODE,PROC(VALUE)VOID)VOID order
);
PROC test = (TEST test)VOID:(
STRING pad=" "*(12-UPB name OF test);
print((name OF test,pad,": "));
(order OF test)(node, print node);
print(new line)
);
[]TEST test list = (
("preorder",preorder),
("inorder",inorder),
("postorder",postorder),
("level order",level order)
);
FOR i TO UPB test list DO test(test list[i]) OD;
destroy tree(node)
) |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #REXX | REXX | /*REXX program shows something close to a "topic variable" (for functions/subroutines).*/
parse arg N /*obtain a variable from the cmd line. */
call squareIt N /*invoke a function to square da number*/
say result ' ◄───' /*display returned value from the func.*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
squareIt: return arg(1) ** 2 /*return the square of passed argument.*/ |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #Ring | Ring |
see "sum1 = " + sum1(1,2) + nl
see "sum2 = " + sum2(2,3) + nl
func sum1 (x, y)
sum = x + y
return sum
func sum2 (x, y)
return x + y
|
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #Ruby | Ruby | while DATA.gets # assigns to $_ (local scope)
print # If no arguments are given, prints $_
end
__END__
This is line one
This is line two
This is line three |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number
3
{\displaystyle 3}
to it and then computing its square and square root.
| #Scala | Scala | object TopicVar extends App {
class SuperString(val org: String){
def it(): Unit = println(org)
}
new SuperString("FvdB"){it()}
new SuperString("FvdB"){println(org)}
Seq(1).foreach {println}
Seq(2).foreach {println(_)}
Seq(4).foreach { it => println(it)}
Seq(8).foreach { it => println(it + it)}
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.