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/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #360_Assembly | 360 Assembly | * Tokenize a string - 08/06/2018
TOKSTR CSECT
USING TOKSTR,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
MVC N,=A(1) n=1
LA R7,1 i1=1
LA R6,1 i=1
DO WHILE=(C,R6,LE,LENS) do i=1 to length(s);
LA R4,S-1 @s-1
AR R4,R6 +i
MVC C,0(R4) c=substr(s,i,1)
IF CLI,C,EQ,C',' THEN if c=',' then do
BAL R14,TOK call tok
LR R2,R8 i2
SR R2,R7 i2-i1
LA R2,1(R2) i2-i1+1
L R1,N n
SLA R1,1 *2
STH R2,TALEN-2(R1) talen(n)=i2-i1+1
L R2,N n
LA R2,1(R2) n+1
ST R2,N n=n+1
LA R7,1(R6) i1=i+1
ENDIF , endif
LA R6,1(R6) i++
ENDDO , enddo i
BAL R14,TOK call tok
LR R2,R8 i2
SR R2,R7 i2-i1
LA R2,1(R2) i2-i1+1
L R1,N n
SLA R1,1 *2
STH R2,TALEN-2(R1) talen(n)=i2-i1+1
LA R11,PG pgi=@pg
LA R6,1 i=1
DO WHILE=(C,R6,LE,N) do i=1 to n
LR R1,R6 i
SLA R1,1 *2
LH R10,TALEN-2(R1) l=talen(i)
LR R1,R6 i
SLA R1,3 *8
LA R4,TABLE-8(R1) @table(i)
LR R2,R10 l
BCTR R2,0 ~
EX R2,MVCX output table(i) length(l)
AR R11,R10 pgi=pgi+l
IF C,R6,NE,N THEN if i^=n then
MVC 0(1,R11),=C'.' output '.'
LA R11,1(R11) pgi=pgi+1
ENDIF , endif
LA R6,1(R6) i++
ENDDO , enddo i
XPRNT PG,L'PG print
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling sav
TOK LR R5,R6 i <--
BCTR R5,0 i-1 |
LR R8,R5 i2=i-1
SR R5,R7 i2-i1
LA R5,1(R5) l=i2-i1+1 source length
L R1,N n
SLA R1,3 *8
LA R2,TABLE-8(R1) @table(n)
LA R4,S-1 @s-1
AR R4,R7 @s+i1-1
LA R3,8 target length
MVCL R2,R4 table(n)=substr(s,i1,i2-i1+1) |
BR R14 End TOK subroutine <--
MVCX MVC 0(0,R11),0(R4) output table(i)
S DC CL80'Hello,How,Are,You,Today' <== input string ==
LENS DC F'23' length(s) <==
TABLE DC 8CL8' ' table(8)
TALEN DC 8H'0' talen(8)
C DS CL1 char
N DS F number of tokens
PG DC CL80' ' buffer
YREGS
END TOKSTR |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #8080_Assembly | 8080 Assembly | puts: equ 9
org 100h
jmp demo
;;; Split the string at DE by the character in C.
;;; Store pointers to the beginning of the elements starting at HL
;;; The amount of elements is returned in B.
split: mvi b,0 ; Amount of elements
sloop: mov m,e ; Store pointer at [HL]
inx h
mov m,d
inx h
inr b ; Increment counter
sscan: ldax d ; Get current character
inx d
cpi '$' ; Done?
rz ; Then stop
cmp c ; Place to split?
jnz sscan ; If not, keep going
dcx d
mvi a,'$' ; End the string here
stax d
inx d
jmp sloop ; Next part
;;; Test on the string given in the task
demo: lxi h,parts ; Parts array
lxi d,hello ; String
mvi c,','
call split ; Split the string
lxi h,parts ; Print each part
loop: mov e,m ; Load pointer into DE
inx h
mov d,m
inx h
push h ; Keep the array pointer
push b ; And the counter
mvi c,puts ; Print the string
call 5
lxi d,period ; And a period
mvi c,puts
call 5
pop b ; Restore the counter
pop h ; Restore the array pointer
dcr b ; One fewer string left
jnz loop
ret
period: db '. $'
hello: db 'Hello,How,Are,You,Today$'
parts: equ $ |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
Find the top N salaries in each department, where N is provided as a parameter.
Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:
Employee Name,Employee ID,Salary,Department
Tyler Bennett,E10297,32000,D101
John Rappl,E21437,47000,D050
George Woltman,E00127,53500,D101
Adam Smith,E63535,18000,D202
Claire Buckman,E39876,27800,D202
David McClellan,E04242,41500,D101
Rich Holcomb,E01234,49500,D202
Nathan Adams,E41298,21900,D050
Richard Potter,E43128,15900,D101
David Motsinger,E27002,19250,D202
Tim Sampair,E03033,27000,D101
Kim Arlich,E10001,57000,D190
Timothy Grove,E16398,29900,D190
| #Aime | Aime | Add_Employee(record employees, text name, id, integer salary, text department)
{
employees[name] = list(name, id, salary, department);
}
collect(record top, employees)
{
for (, list l in employees) {
top.v_index(l[3]).v_list(l[2]).link(-1, l);
}
for (text department, index x in top) {
list t;
x.ucall(l_ucall, 0, l_append, 1, t);
if (N < ~t.reverse) {
t.erase(N, -1);
}
top[department] = t;
}
}
print_department(text department, list employees)
{
o_("Department ", department, "\n");
for (, list l in employees) {
o_form(" ~ | ~ | ~\n", l[0], l[1], l[2]);
}
}
main(void)
{
record employees, top;
Add_Employee(employees, "Tyler Bennett ", "E10297", 32000, "D101");
Add_Employee(employees, "John Rappl ", "E21437", 47000, "D050");
Add_Employee(employees, "George Woltman ", "E00127", 53500, "D101");
Add_Employee(employees, "Adam Smith ", "E63535", 18000, "D202");
Add_Employee(employees, "Claire Buckman ", "E39876", 27800, "D202");
Add_Employee(employees, "David McClellan", "E04242", 41500, "D101");
Add_Employee(employees, "Rich Holcomb ", "E01234", 49500, "D202");
Add_Employee(employees, "Nathan Adams ", "E41298", 21900, "D050");
Add_Employee(employees, "Richard Potter ", "E43128", 15900, "D101");
Add_Employee(employees, "David Motsinger", "E27002", 19250, "D202");
Add_Employee(employees, "Tim Sampair ", "E03033", 27000, "D101");
Add_Employee(employees, "Kim Arlich ", "E10001", 57000, "D190");
Add_Employee(employees, "Timothy Grove ", "E16398", 29900, "D190");
collect(top, employees);
top.wcall(print_department, 0, 1);
0;
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #ALGOL-M | ALGOL-M | begin
procedure move(n, src, via, dest);
integer n;
string(1) src, via, dest;
begin
if n > 0 then
begin
move(n-1, src, dest, via);
write("Move disk from pole ");
writeon(src);
writeon(" to pole ");
writeon(dest);
move(n-1, via, src, dest);
end;
end;
move(4, "1", "2", "3");
end |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #Arturo | Arturo | thueMorse: function [maxSteps][
result: new []
val: [0]
count: new 0
while [true][
'result ++ join to [:string] val
inc 'count
if count = maxSteps -> return result
val: val ++ map val 'v -> 1 - v
]
return result
]
loop thueMorse 6 'bits ->
print bits |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #AutoHotkey | AutoHotkey | ThueMorse(num, iter){
if !iter
return num
for i, n in StrSplit(num)
opp .= !n
res := ThueMorse(num . opp, --iter)
return res
} |
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm | Tonelli-Shanks algorithm |
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computational number theory, the Tonelli–Shanks algorithm is a technique for solving for x in a congruence of the form:
x2 ≡ n (mod p)
where n is an integer which is a quadratic residue (mod p), p is an odd prime, and x,n ∈ Fp where Fp = {0, 1, ..., p - 1}.
It is used in cryptography techniques.
To apply the algorithm, we need the Legendre symbol:
The Legendre symbol (a | p) denotes the value of a(p-1)/2 (mod p).
(a | p) ≡ 1 if a is a square (mod p)
(a | p) ≡ -1 if a is not a square (mod p)
(a | p) ≡ 0 if a ≡ 0 (mod p)
Algorithm pseudo-code
All ≡ are taken to mean (mod p) unless stated otherwise.
Input: p an odd prime, and an integer n .
Step 0: Check that n is indeed a square: (n | p) must be ≡ 1 .
Step 1: By factoring out powers of 2 from p - 1, find q and s such that p - 1 = q2s with q odd .
If p ≡ 3 (mod 4) (i.e. s = 1), output the two solutions r ≡ ± n(p+1)/4 .
Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq .
Step 3: Set r ≡ n(q+1)/2, t ≡ nq, m = s .
Step 4: Loop the following:
If t ≡ 1, output r and p - r .
Otherwise find, by repeated squaring, the lowest i, 0 < i < m , such that t2i ≡ 1 .
Let b ≡ c2(m - i - 1), and set r ≡ rb, t ≡ tb2, c ≡ b2 and m = i .
Task
Implement the above algorithm.
Find solutions (if any) for
n = 10 p = 13
n = 56 p = 101
n = 1030 p = 10009
n = 1032 p = 10009
n = 44402 p = 100049
Extra credit
n = 665820697 p = 1000000009
n = 881398088036 p = 1000000000039
n = 41660815127637347468140745042827704103445750172002 p = 10^50 + 577
See also
Modular exponentiation
Cipolla's algorithm
| #D | D | import std.bigint;
import std.stdio;
import std.typecons;
alias Pair = Tuple!(long, "n", long, "p");
enum BIGZERO = BigInt("0");
enum BIGONE = BigInt("1");
enum BIGTWO = BigInt("2");
enum BIGTEN = BigInt("10");
struct Solution {
BigInt root1, root2;
bool exists;
}
/// https://en.wikipedia.org/wiki/Modular_exponentiation#Right-to-left_binary_method
BigInt modPow(BigInt b, BigInt e, BigInt n) {
if (n == 1) return BIGZERO;
BigInt result = 1;
b = b % n;
while (e > 0) {
if (e % 2 == 1) {
result = (result * b) % n;
}
e >>= 1;
b = (b*b) % n;
}
return result;
}
Solution ts(long n, long p) {
return ts(BigInt(n), BigInt(p));
}
Solution ts(BigInt n, BigInt p) {
auto powMod(BigInt a, BigInt e) {
return a.modPow(e, p);
}
auto ls(BigInt a) {
return powMod(a, (p-1)/2);
}
if (ls(n) != 1) return Solution(BIGZERO, BIGZERO, false);
auto q = p - 1;
auto ss = BIGZERO;
while ((q & 1) == 0) {
ss = ss + 1;
q = q >> 1;
}
if (ss == BIGONE) {
auto r1 = powMod(n, (p + 1) / 4);
return Solution(r1, p - r1, true);
}
auto z = BIGTWO;
while (ls(z) != p - 1) z = z + 1;
auto c = powMod(z, q);
auto r = powMod(n, (q + 1) / 2);
auto t = powMod(n, q);
auto m = ss;
while (true) {
if (t == 1) return Solution(r, p - r, true);
auto i = BIGZERO;
auto zz = t;
while (zz != 1 && i < m - 1) {
zz = zz * zz % p;
i = i + 1;
}
auto b = c;
auto e = m - i - 1;
while (e > 0) {
b = b * b % p;
e = e - 1;
}
r = r * b % p;
c = b * b % p;
t = t * c % p;
m = i;
}
}
void main() {
auto pairs = [
Pair( 10L, 13L),
Pair( 56L, 101L),
Pair( 1_030L, 10_009L),
Pair( 1_032L, 10_009L),
Pair( 44_402L, 100_049L),
Pair( 665_820_697L, 1_000_000_009L),
Pair(881_398_088_036L, 1_000_000_000_039L),
];
foreach (pair; pairs) {
auto sol = ts(pair.n, pair.p);
writeln("n = ", pair.n);
writeln("p = ", pair.p);
if (sol.exists) {
writeln("root1 = ", sol.root1);
writeln("root2 = ", sol.root2);
}
else writeln("No solution exists");
writeln();
}
auto bn = BigInt("41660815127637347468140745042827704103445750172002");
auto bp = BIGTEN ^^ 50 + 577L;
auto sol = ts(bn, bp);
writeln("n = ", bn);
writeln("p = ", bp);
if (sol.exists) {
writeln("root1 = ", sol.root1);
writeln("root2 = ", sol.root2);
}
else writeln("No solution exists");
} |
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
| #BQN | BQN | str ← "one^|uno||three^^^^|four^^^|^cuatro|"
Split ← ((⊢-˜+`׬)∘=⊔⊢)
SplitE ← {
esc ← <`'^'=𝕩
rem ← »esc
spl ← (¬rem)∧'|'=𝕩
𝕩⊔˜(⊢-(esc∨spl)×1⊸+)+`spl
}
•Show SplitE str |
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
| #C | C | #include <stdlib.h>
#include <stdio.h>
#define STR_DEMO "one^|uno||three^^^^|four^^^|^cuatro|"
#define SEP '|'
#define ESC '^'
typedef char* Str; /* just for an easier reading */
/* ===> FUNCTION PROTOTYPES <================================================ */
unsigned int ElQ( const char *s, char sep, char esc );
Str *Tokenize( char *s, char sep, char esc, unsigned int *q );
/*==============================================================================
Main function.
Just passes a copy of the STR_DEMO string to the tokenization function and shows
the results.
==============================================================================*/
int main() {
char s[] = STR_DEMO;
unsigned int i, q;
Str *list = Tokenize( s, SEP, ESC, &q );
if( list != NULL ) {
printf( "\n Original string: %s\n\n", STR_DEMO );
printf( " %d tokens:\n\n", q );
for( i=0; i<q; ++i )
printf( " %4d. %s\n", i+1, list[i] );
free( list );
}
return 0;
}
/*==============================================================================
"ElQ" stands for "Elements Quantity". Counts the amount of valid element in the
string s, according to the separator character provided in sep and the escape
character provided in esc.
==============================================================================*/
unsigned int ElQ( const char *s, char sep, char esc ) {
unsigned int q, e;
const char *p;
for( e=0, q=1, p=s; *p; ++p ) {
if( *p == esc )
e = !e;
else if( *p == sep )
q += !e;
else e = 0;
}
return q;
}
/*==============================================================================
The actual tokenization function.
Allocates as much dynamic memory as needed to contain the pointers to the
tokenized portions of the string passed as the "s" parameter, then looks for the
separators characters sep, paying attention to the occurrences of the escape
character provided in esc. When a valid separator is found, the function swaps
it with a '\0' terminator character and stores the pointer to the next string
into the array of pointers in dynamic memory. On output, the value of *q is the
number of pointers in the array. The caller is responsible for deallocating with
free() the returned array of pointers when it is no longer needed.
In case of failure, NULL is returned.
==============================================================================*/
Str *Tokenize( char *s, char sep, char esc, unsigned int *q ) {
Str *list = NULL;
*q = ElQ( s, sep, esc );
list = malloc( *q * sizeof(Str) );
if( list != NULL ) {
unsigned int e, i;
char *p;
i = 0;
list[i++] = s;
for( e=0, p=s; *p; ++p ) {
if( *p == esc ) {
e = !e;
}
else if( *p == sep && !e ) {
list[i++] = p+1;
*p = '\0';
}
else {
e = 0;
}
}
}
return list;
} |
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
| #Julia | Julia | using Printf
# Total circles area: https://rosettacode.org/wiki/Total_circles_area
xc = [1.6417233788, -1.4944608174, 0.6110294452, 0.3844862411, -0.2495892950, 1.7813504266,
-0.1985249206, -1.7011985145, -0.4319462812, 0.2178372997, -0.6294854565, 1.7952608455,
1.4168575317, 1.4637371396, -0.5263668798, -1.2197352481, -0.1389358881, 1.5293954595,
-0.5258728625, -0.1403562064, 0.8055826339, -0.6311979224, 1.4685857879, -0.6855727502,
0.0152957411]
yc = [1.6121789534, 1.2077959613, -0.6907087527, 0.2923344616, -0.3832854473, 1.6178237031,
-0.8343333301, -0.1263820964, 1.4104420482, -0.9499557344, -1.3078893852, 0.6281269104,
1.0683357171, 0.9463877418, 1.7315156631, 0.9144146579, 0.1092805780, 0.0030278255,
1.3782633069, 0.2437382535, -0.0482092025, 0.7184578971, -0.8347049536, 1.6465021616,
0.0638919221]
r = [0.0848270516, 1.1039549836, 0.9089162485, 0.2375743054, 1.0845181219, 0.8162655711,
0.0538864941, 0.4776976918, 0.7886291537, 0.0357871187, 0.7653357688, 0.2727652452,
1.1016025378, 1.1846214562, 1.4428514068, 1.0727263474, 0.7350208828, 1.2472867347,
1.3495508831, 1.3804956588, 0.3327165165, 0.2491045282, 1.3670667538, 1.0593087096,
0.9771215985]
# Size of my grid -- higher values => higher accuracy.
function main(xc::Vector{<:Real}, yc::Vector{<:Real}, r::Vector{<:Real}, ngrid::Integer=10000)
r2 = r .* r
ncircles = length(xc)
# Compute the bounding box of the circles.
xmin = minimum(xc .- r)
xmax = maximum(xc .+ r)
ymin = minimum(yc .- r)
ymax = maximum(yc .+ r)
# Keep a counter.
inside = 0
# For every point in my grid.
for x in linspace(xmin, xmax, ngrid), y = linspace(ymin, ymax, ngrid)
inside += any(r2 .> (x - xc) .^ 2 + (y - yc) .^ 2)
end
boxarea = (xmax - xmin) * (ymax - ymin)
return boxarea * inside / ngrid ^ 2
end
println(@time main(xc, yc, r, 1000)) |
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]
| #Clojure | Clojure | (use 'clojure.set)
(use 'clojure.contrib.seq-utils)
(defn dep
"Constructs a single-key dependence, represented as a map from
item to a set of items, ensuring that item is not in the set."
[item items]
{item (difference (set items) (list item))})
(defn empty-dep
"Constructs a single-key dependence from item to an empty set."
[item]
(dep item '()))
(defn pair-dep
"Invokes dep after destructuring item and items from the argument."
[[item items]]
(dep item items))
(defn default-deps
"Constructs a default dependence map taking every item
in the argument to an empty set"
[items]
(apply merge-with union (map empty-dep (flatten items))))
(defn declared-deps
"Constructs a dependence map from a list containaining
alternating items and list of their predecessor items."
[items]
(apply merge-with union (map pair-dep (partition 2 items))))
(defn deps
"Constructs a full dependence map containing both explicitly
represented dependences and default empty dependences for
items without explicit predecessors."
[items]
(merge (default-deps items) (declared-deps items)))
(defn no-dep-items
"Returns all keys from the argument which have no (i.e. empty) dependences."
[deps]
(filter #(empty? (deps %)) (keys deps)))
(defn remove-items
"Returns a dependence map with the specified items removed from keys
and from all dependence sets of remaining keys."
[deps items]
(let [items-to-remove (set items)
remaining-keys (difference (set (keys deps)) items-to-remove)
remaining-deps (fn [x] (dep x (difference (deps x) items-to-remove)))]
(apply merge (map remaining-deps remaining-keys))))
(defn topo-sort-deps
"Given a dependence map, returns either a list of items in which each item
follows all of its predecessors, or a string showing the items among which
there is a cyclic dependence preventing a linear order."
[deps]
(loop [remaining-deps deps
result '()]
(if (empty? remaining-deps)
(reverse result)
(let [ready-items (no-dep-items remaining-deps)]
(if (empty? ready-items)
(str "ERROR: cycles remain among " (keys remaining-deps))
(recur (remove-items remaining-deps ready-items)
(concat ready-items result)))))))
(defn topo-sort
"Given a list of alternating items and predecessor lists, constructs a
full dependence map and then applies topo-sort-deps to that map."
[items]
(topo-sort-deps (deps items)))
|
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.
| #Go | Go | package turing
type Symbol byte
type Motion byte
const (
Left Motion = 'L'
Right Motion = 'R'
Stay Motion = 'N'
)
type Tape struct {
data []Symbol
pos, left int
blank Symbol
}
// NewTape returns a new tape filled with 'data' and position set to 'start'.
// 'start' does not need to be range, the tape will be extended if required.
func NewTape(blank Symbol, start int, data []Symbol) *Tape {
t := &Tape{
data: data,
blank: blank,
}
if start < 0 {
t.Left(-start)
}
t.Right(start)
return t
}
func (t *Tape) Stay() {}
func (t *Tape) Data() []Symbol { return t.data[t.left:] }
func (t *Tape) Read() Symbol { return t.data[t.pos] }
func (t *Tape) Write(s Symbol) { t.data[t.pos] = s }
func (t *Tape) Dup() *Tape {
t2 := &Tape{
data: make([]Symbol, len(t.Data())),
blank: t.blank,
}
copy(t2.data, t.Data())
t2.pos = t.pos - t.left
return t2
}
func (t *Tape) String() string {
s := ""
for i := t.left; i < len(t.data); i++ {
b := t.data[i]
if i == t.pos {
s += "[" + string(b) + "]"
} else {
s += " " + string(b) + " "
}
}
return s
}
func (t *Tape) Move(a Motion) {
switch a {
case Left:
t.Left(1)
case Right:
t.Right(1)
case Stay:
t.Stay()
}
}
const minSz = 16
func (t *Tape) Left(n int) {
t.pos -= n
if t.pos < 0 {
// Extend left
var sz int
for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {
}
newd := make([]Symbol, sz)
newl := len(newd) - cap(t.data[t.left:])
n := copy(newd[newl:], t.data[t.left:])
t.data = newd[:newl+n]
t.pos += newl - t.left
t.left = newl
}
if t.pos < t.left {
if t.blank != 0 {
for i := t.pos; i < t.left; i++ {
t.data[i] = t.blank
}
}
t.left = t.pos
}
}
func (t *Tape) Right(n int) {
t.pos += n
if t.pos >= cap(t.data) {
// Extend right
var sz int
for sz = minSz; t.pos >= sz; sz <<= 1 {
}
newd := make([]Symbol, sz)
n := copy(newd[t.left:], t.data[t.left:])
t.data = newd[:t.left+n]
}
if i := len(t.data); t.pos >= i {
t.data = t.data[:t.pos+1]
if t.blank != 0 {
for ; i < len(t.data); i++ {
t.data[i] = t.blank
}
}
}
}
type State string
type Rule struct {
State
Symbol
Write Symbol
Motion
Next State
}
func (i *Rule) key() key { return key{i.State, i.Symbol} }
func (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }
type key struct {
State
Symbol
}
type action struct {
write Symbol
Motion
next State
}
type Machine struct {
tape *Tape
start, state State
transition map[key]action
l func(string, ...interface{}) // XXX
}
func NewMachine(rules []Rule) *Machine {
m := &Machine{transition: make(map[key]action, len(rules))}
if len(rules) > 0 {
m.start = rules[0].State
}
for _, r := range rules {
m.transition[r.key()] = r.action()
}
return m
}
func (m *Machine) Run(input *Tape) (int, *Tape) {
m.tape = input.Dup()
m.state = m.start
for cnt := 0; ; cnt++ {
if m.l != nil {
m.l("%3d %4s: %v\n", cnt, m.state, m.tape)
}
sym := m.tape.Read()
act, ok := m.transition[key{m.state, sym}]
if !ok {
return cnt, m.tape
}
m.tape.Write(act.write)
m.tape.Move(act.Motion)
m.state = act.next
}
} |
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).
| #Factor | Factor | USING: combinators formatting io kernel math math.primes.factors
math.ranges sequences ;
IN: rosetta-code.totient-function
: Φ ( n -- m )
{
{ [ dup 1 < ] [ drop 0 ] }
{ [ dup 1 = ] [ drop 1 ] }
[
dup unique-factors
[ 1 [ 1 - * ] reduce ] [ product ] bi / *
]
} cond ;
: show-info ( n -- )
[ Φ ] [ swap 2dup - 1 = ] bi ", prime" "" ?
"Φ(%2d) = %2d%s\n" printf ;
: totient-demo ( -- )
25 [1,b] [ show-info ] each nl 0 100,000 [1,b] [
[ dup Φ - 1 = [ 1 + ] when ]
[ dup { 100 1,000 10,000 100,000 } member? ] bi
[ dupd "%4d primes <= %d\n" printf ] [ drop ] if
] each drop ;
MAIN: totient-demo |
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
| #Lua | Lua | -- Return an iterator to produce every permutation of list
function permute (list)
local function perm (list, n)
if n == 0 then coroutine.yield(list) end
for i = 1, n do
list[i], list[n] = list[n], list[i]
perm(list, n - 1)
list[i], list[n] = list[n], list[i]
end
end
return coroutine.wrap(function() perm(list, #list) end)
end
-- Perform one topswop round on table t
function swap (t)
local new, limit = {}, t[1]
for i = 1, #t do
if i <= limit then
new[i] = t[limit - i + 1]
else
new[i] = t[i]
end
end
return new
end
-- Find the most swaps needed for any starting permutation of n cards
function topswops (n)
local numTab, highest, count = {}, 0
for i = 1, n do numTab[i] = i end
for numList in permute(numTab) do
count = 0
while numList[1] ~= 1 do
numList = swap(numList)
count = count + 1
end
if count > highest then highest = count end
end
return highest
end
-- Main procedure
for i = 1, 10 do print(i, topswops(i)) 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.
| #Clojure | Clojure | (ns user
(:require [clojure.contrib.generic.math-functions :as generic]))
;(def pi Math/PI)
(def pi (* 4 (atan 1)))
(def dtor (/ pi 180))
(def rtod (/ 180 pi))
(def radians (/ pi 4))
(def degrees 45)
(println (str (sin radians) " " (sin (* degrees dtor))))
(println (str (cos radians) " " (cos (* degrees dtor))))
(println (str (tan radians) " " (tan (* degrees dtor))))
(println (str (asin (sin radians) ) " " (* (asin (sin (* degrees dtor))) rtod)))
(println (str (acos (cos radians) ) " " (* (acos (cos (* degrees dtor))) rtod)))
(println (str (atan (tan radians) ) " " (* (atan (tan (* degrees dtor))) rtod))) |
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).
| #Haskell | Haskell | import Control.Monad (replicateM, mapM_)
f :: Floating a => a -> a
f x = sqrt (abs x) + 5 * x ** 3
main :: IO ()
main = do
putStrLn "Enter 11 numbers for evaluation"
x <- replicateM 11 readLn
mapM_
((\x ->
if x > 400
then putStrLn "OVERFLOW"
else print x) .
f) $
reverse x |
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).
| #Icon_and_Unicon | Icon and Unicon | procedure main()
S := []
writes("Enter 11 numbers: ")
read() ? every !11 do (tab(many(' \t'))|0,put(S, tab(upto(' \t')|0)))
every item := !reverse(S) do
write(item, " -> ", (400 >= f(item)) | "overflows")
end
procedure f(x)
return abs(x)^0.5 + 5*x^3
end |
http://rosettacode.org/wiki/Twelve_statements | Twelve statements | This puzzle is borrowed from math-frolic.blogspot.
Given the following twelve statements, which of them are true?
1. This is a numbered list of twelve statements.
2. Exactly 3 of the last 6 statements are true.
3. Exactly 2 of the even-numbered statements are true.
4. If statement 5 is true, then statements 6 and 7 are both true.
5. The 3 preceding statements are all false.
6. Exactly 4 of the odd-numbered statements are true.
7. Either statement 2 or 3 is true, but not both.
8. If statement 7 is true, then 5 and 6 are both true.
9. Exactly 3 of the first 6 statements are true.
10. The next two statements are both true.
11. Exactly 1 of statements 7, 8 and 9 are true.
12. Exactly 4 of the preceding statements are true.
Task
When you get tired of trying to figure it out in your head,
write a program to solve it, and print the correct answer or answers.
Extra credit
Print out a table of near misses, that is, solutions that are contradicted by only a single statement.
| #Swift_Playground | Swift Playground |
import UIKit
import Foundation
internal enum PaddingOption {
case Left
case Right
}
extension Array {
func pad(element: Element, times: Int, toThe: PaddingOption) -> Array<Element> {
let padded = [Element](repeating: element, count: times)
switch(toThe) {
case .Left:
return padded + self
case .Right:
return self + padded
}
}
func take(n: Int) -> Array<Element> {
if n <= 0 {
return []
}
return Array(self[0..<Swift.min(n, self.count)])
}
func drop(n: Int) -> Array<Element> {
if n <= 0 {
return self
} else if n >= self.count {
return []
}
return Array(self[n..<self.count])
}
func stride(n: Int) -> Array<Element> {
var result:[Element] = []
for i in Swift.stride(from: 0, to: self.count, by: n) {
result.append(self[i])
}
return result
}
func zipWithIndex() -> Array<(Element, Int)> {
let result = [(Element, Int)](zip(self, self.indices))
return result
}
}
extension Int {
func binaryRepresentationOfLength(length: Int) -> [Int] {
var binaryRepresentation:[Int] = []
var value = self
while (value != 0) {
binaryRepresentation.append(value & 1)
value /= 2
}
let result = binaryRepresentation.pad(element: 0, times: length-binaryRepresentation.count, toThe: .Right)
return result
}
}
let problem = [
"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."]
let statements:[(([Bool]) -> Bool)] = [
{ s in s.count == 12 },
{ s in s.drop(n: 6).filter({ $0 }).count == 3 },
{ s in s.drop(n: 1).stride(n: 2).filter({ $0 }).count == 2 },
{ s in s[4] ? (s[5] && s[6]) : true },
{ s in s.drop(n: 1).take(n: 3).filter({ $0 }).count == 0 },
{ s in s.stride(n: 2).filter({ $0 }).count == 4 },
{ s in [s[1], s[2]].filter({ $0 }).count == 1 },
{ s in s[6] ? (s[4] && s[5]) : true },
{ s in s.take(n: 6).filter({ $0 }).count == 3 },
{ s in [s[10], s[11]].filter({ $0 }).count == 2 },
{ s in [s[6], s[7], s[8]].filter({ $0 }).count == 1 },
{ s in s.take(n: 11).filter({ $0 }).count == 4 }
]
for variant in 0..<(1<<statements.count) {
let attempt = variant.binaryRepresentationOfLength(length: statements.count).map { $0 == 1 }
if statements.map({ $0(attempt) }) == attempt {
let trueAre = attempt.zipWithIndex().filter { $0.0 }.map { $0.1 + 1 }
print("Solution found! True are: \(trueAre)")
}
}
|
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.
| #Tcl | Tcl | package require Tcl 8.6
# Function to evaluate the truth of a statement
proc tcl::mathfunc::S {idx} {
upvar 1 state s
apply [lindex $s [expr {$idx - 1}]] $s
}
# Procedure to count the number of statements which are true
proc S+ args {
upvar 1 state state
tcl::mathop::+ {*}[lmap i $args {expr {S($i)}}]
}
# Turn a list of expressions into a list of lambda terms
proc lambdas items {lmap x $items {list state [list expr $x]}}
# Find the truth assignment that produces consistency. And those that are
# near misses too.
proc findTruthMatch {statements} {
set n [llength $statements]
for {set i 0} {$i < 2**$n} {incr i} {
set state [split [format %0.*b $n $i] ""]
set truths [lmap f $statements {apply $f [lambdas $state]}]
set counteq [tcl::mathop::+ {*}[lmap s $state t $truths {expr {
$s == $t
}}]]
if {$counteq == $n} {
lappend exact $state
} elseif {$counteq == $n-1} {
set j 0
foreach s $state t $truths {
incr j
if {$s != $t} {
lappend differ $state $j
break
}
}
}
}
return [list $exact $differ]
}
# Rendering code
proc renderstate state {
return ([join [lmap s $state {
incr i
expr {$s ? "S($i)" : "\u00acS($i)"}
}] "\u22c0"])
}
# The statements, encoded as expressions
set statements {
{[llength $state] == 12}
{[S+ 7 8 9 10 11 12] == 3}
{[S+ 2 4 6 8 10 12] == 2}
{S(5) ? S(6) && S(7) : 1}
{[S+ 2 3 4] == 0}
{[S+ 1 3 5 7 9 11] == 4}
{S(2) != S(3)}
{S(7) ? S(5) && S(6) : 1}
{[S+ 1 2 3 4 5 6] == 3}
{S(11) && S(12)}
{[S+ 7 8 9] == 1}
{[S+ 1 2 3 4 5 6 7 8 9 10 11] == 4}
}
# Find the truth assignment(s) that give consistency
lassign [findTruthMatch [lambdas $statements]] exact differ
# Print the results
foreach state $exact {
puts "exact match\t[renderstate $state ]"
}
foreach {state j} $differ {
puts "almost found\t[renderstate $state] \u21d2 [expr {[lindex $state $j-1]?"\u00ac":{}}]S($j)"
} |
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.
| #Python | Python | from itertools import product
while True:
bexp = input('\nBoolean expression: ')
bexp = bexp.strip()
if not bexp:
print("\nThank you")
break
code = compile(bexp, '<string>', 'eval')
names = code.co_names
print('\n' + ' '.join(names), ':', bexp)
for values in product(range(2), repeat=len(names)):
env = dict(zip(names, values))
print(' '.join(str(v) for v in values), ':', eval(code, env))
|
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
| #Racket | Racket | #lang racket
(require (only-in math/number-theory prime?))
(define ((cell-fn n (start 1)) x y)
(let* ((y (- y (quotient n 2)))
(x (- x (quotient (sub1 n) 2)))
(l (* 2 (if (> (abs x) (abs y)) (abs x) (abs y))))
(d (if (>= y x) (+ (* l 3) x y) (- l x y))))
(+ (sqr (- l 1)) d start -1)))
(define (show-spiral n
#:symbol (smb "# ")
#:start (start 1)
#:space (space (and smb (make-string (string-length smb) #\space))))
(define top (+ start (* n n) 1))
(define cell (cell-fn n start))
(define print-cell
(if smb
(λ (i p?) (display (if p? smb space)))
(let* ((max-len (string-length (~a (+ (sqr n) start -1))))
(space (or space (make-string (string-length (~a (+ (sqr n) start -1))) #\_))))
(λ (i p?)
(display (if p? (~a #:width max-len i #:align 'right) space))
(display #\space)))))
(for* ((y (in-range 0 n)) #:when (unless (= y 0) (newline)) (x (in-range 0 n)))
(define c (cell x y))
(define p? (prime? c))
(print-cell c p?))
(newline))
(show-spiral 9 #:symbol #f)
(show-spiral 10 #:symbol "♞" #:space "♘") ; black are the primes
(show-spiral 50 #:symbol "*" #:start 42)
; for filling giant terminals
; (show-spiral 1001 #:symbol "*" #:start 42) |
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.]
| #jq | jq | def is_left_truncatable_prime:
def removeleft: recurse(if length <= 1 then empty else .[1:] end);
tostring
| index("0") == null and
all(removeleft|tonumber; is_prime);
def is_right_truncatable_prime:
def removeright: recurse(if length <= 1 then empty else .[:-1] end);
tostring
| index("0") == null and
all(removeright|tonumber; is_prime);
first( range(999999; 1; -2) | select(is_left_truncatable_prime)),
first( range(999999; 1; -2) | select(is_right_truncatable_prime)) |
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.
| #AWK | AWK |
function preorder(tree, node, res, child) {
if (node == "")
return
res[res["count"]++] = node
split(tree[node], child, ",")
preorder(tree,child[1],res)
preorder(tree,child[2],res)
}
function inorder(tree, node, res, child) {
if (node == "")
return
split(tree[node], child, ",")
inorder(tree,child[1],res)
res[res["count"]++] = node
inorder(tree,child[2],res)
}
function postorder(tree, node, res, child) {
if (node == "")
return
split(tree[node], child, ",")
postorder(tree,child[1], res)
postorder(tree,child[2], res)
res[res["count"]++] = node
}
function levelorder(tree, node, res, nextnode, queue, child) {
if (node == "")
return
queue["tail"] = 0
queue[queue["head"]++] = node
while (queue["head"] - queue["tail"] >= 1) {
nextnode = queue[queue["tail"]]
delete queue[queue["tail"]++]
res[res["count"]++] = nextnode
split(tree[nextnode], child, ",")
if (child[1] != "")
queue[queue["head"]++] = child[1]
if (child[2] != "")
queue[queue["head"]++] = child[2]
}
delete queue
}
BEGIN {
tree["1"] = "2,3"
tree["2"] = "4,5"
tree["3"] = "6,"
tree["4"] = "7,"
tree["5"] = ","
tree["6"] = "8,9"
tree["7"] = ","
tree["8"] = ","
tree["9"] = ","
preorder(tree,"1",result)
printf "preorder:\t"
for (n = 0; n < result["count"]; n += 1)
printf result[n]" "
printf "\n"
delete result
inorder(tree,"1",result)
printf "inorder:\t"
for (n = 0; n < result["count"]; n += 1)
printf result[n]" "
printf "\n"
delete result
postorder(tree,"1",result)
printf "postorder:\t"
for (n = 0; n < result["count"]; n += 1)
printf result[n]" "
printf "\n"
delete result
levelorder(tree,"1",result)
printf "level-order:\t"
for (n = 0; n < result["count"]; n += 1)
printf result[n]" "
printf "\n"
delete result
}
|
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #8086_Assembly | 8086 Assembly | cpu 8086
org 100h
section .text
jmp demo
;;; Split the string at DS:SI on the character in DL.
;;; Store pointers to strings starting at ES:DI.
;;; The amount of strings is returned in CX.
split: xor cx,cx ; Zero out counter
.loop: mov ax,si ; Store pointer to current location
stosw
inc cx ; Increment counter
.scan: lodsb ; Get byte
cmp al,'$' ; End of string?
je .done
cmp al,dl ; Character to split on?
jne .scan
mov [si-1],byte '$' ; Terminate string
jmp .loop
.done: ret
;;; Test on the string given in the task
demo: mov si,hello ; String to split
mov di,parts ; Place to store pointers
mov dl,',' ; Character to split string on
call split
;;; Print the resulting strings, and periods
mov si,parts ; Array of string pointers
print: lodsw ; Load next pointer
mov dx,ax ; Print string using DOS
mov ah,9
int 21h
mov dx,period ; Then print a period
int 21h
loop print ; Loop while there are strings
ret
section .data
period: db '. $'
hello: db 'Hello,How,Are,You,Today$'
section .bss
parts: resw 10 |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
Find the top N salaries in each department, where N is provided as a parameter.
Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:
Employee Name,Employee ID,Salary,Department
Tyler Bennett,E10297,32000,D101
John Rappl,E21437,47000,D050
George Woltman,E00127,53500,D101
Adam Smith,E63535,18000,D202
Claire Buckman,E39876,27800,D202
David McClellan,E04242,41500,D101
Rich Holcomb,E01234,49500,D202
Nathan Adams,E41298,21900,D050
Richard Potter,E43128,15900,D101
David Motsinger,E27002,19250,D202
Tim Sampair,E03033,27000,D101
Kim Arlich,E10001,57000,D190
Timothy Grove,E16398,29900,D190
| #AppleScript | AppleScript | use AppleScript version "2.3.1" -- Mac OS X 10.9 (Mavericks) or later for these 'use' commands!
use sorter : script "Custom Iterative Ternary Merge Sort" -- <https://macscripter.net/viewtopic.php?pid=194430#p194430>
on topNSalariesPerDepartment(employeeRecords, n)
set output to {}
set employeeCount to (count employeeRecords)
if ((employeeCount > 0) and (n > 0)) then
-- Sort a copy of the employee record list by department with descending subsorts on salary.
copy employeeRecords to employeeRecords
script comparer
on isGreater(a, b)
return ((a's department > b's department) or ((a's department = b's department) and (a's salary < b's salary)))
end isGreater
end script
considering numeric strings
tell sorter to sort(employeeRecords, 1, employeeCount, {comparer:comparer})
end considering
-- Initialise the output with data from the first record in the sorted list, then work through the rest of the list.
set {department:previousDepartment, salary:previousSalary} to beginning of employeeRecords
set {padValue, topSalaries, counter} to {missing value, {previousSalary}, 1}
set end of output to {department:previousDepartment, salaries:topSalaries}
repeat with i from 2 to employeeCount
set {department:thisDepartment, salary:thisSalary} to item i of employeeRecords
if (thisDepartment is previousDepartment) then
-- Another record from the same department. Include its salary in the output if different from
-- the previous one's and if fewer than n salaries from the department have been included so far.
if ((thisSalary < previousSalary) and (counter < n)) then
set end of topSalaries to thisSalary
set counter to counter + 1
set previousSalary to thisSalary
end if
else
-- First record of the next department.
-- Pad the previous department's salary list with missing values if it has fewer than n entries.
repeat (n - counter) times
set end of topSalaries to padValue
end repeat
-- Start a result record for the new department and add it to the output.
set topSalaries to {thisSalary}
set counter to 1
set end of output to {department:thisDepartment, salaries:topSalaries}
set previousDepartment to thisDepartment
set previousSalary to thisSalary
end if
end repeat
-- Pad the last department's salary list if necessary.
repeat (n - counter) times
set end of topSalaries to padValue
end repeat
end if
return output
end topNSalariesPerDepartment
on demo()
set employeeRecords to {¬
{|name|:"Tyler Bennett", |ID|:"E10297", salary:32000, department:"D101"}, ¬
{|name|:"John Rappl", |ID|:"E21437", salary:47000, department:"D050"}, ¬
{|name|:"George Woltman", |ID|:"E00127", salary:53500, department:"D101"}, ¬
{|name|:"Adam Smith", |ID|:"E63535", salary:18000, department:"D202"}, ¬
{|name|:"Claire Buckman", |ID|:"E39876", salary:27800, department:"D202"}, ¬
{|name|:"David McClellan", |ID|:"E04242", salary:41500, department:"D101"}, ¬
{|name|:"Rich Holcomb", |ID|:"E01234", salary:49500, department:"D202"}, ¬
{|name|:"Nathan Adams", |ID|:"E41298", salary:21900, department:"D050"}, ¬
{|name|:"Richard Potter", |ID|:"E43128", salary:15900, department:"D101"}, ¬
{|name|:"David Motsinger", |ID|:"E27002", salary:19250, department:"D202"}, ¬
{|name|:"Tim Sampair", |ID|:"E03033", salary:27000, department:"D101"}, ¬
{|name|:"Kim Arlich", |ID|:"E10001", salary:57000, department:"D190"}, ¬
{|name|:"Timothy Grove", |ID|:"E16398", salary:29900, department:"D190"}, ¬
{|name|:"Simila Pey", |ID|:"E16399", salary:29900, department:"D190"} ¬
}
set n to 4
set topSalaryRecords to topNSalariesPerDepartment(employeeRecords, n)
--> eg. {{department:"D050", salaries:{47000, 21900, missing value, missing value}}, … }
-- Derive a text report from the result.
set report to {"Top " & n & " salaries per department:"}
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to " "
repeat with thisRecord in topSalaryRecords
set i to n
repeat while (item i of thisRecord's salaries is missing value)
set item i of thisRecord's salaries to "-"
set i to i - 1
end repeat
set end of report to thisRecord's department & ": " & thisRecord's salaries
end repeat
set AppleScript's text item delimiters to linefeed
set report to report as text
set AppleScript's text item delimiters to astid
return report
end demo
demo() |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #ALGOL_W | ALGOL W | begin
procedure move ( integer value n, from, to, via ) ;
if n > 0 then begin
move( n - 1, from, via, to );
write( i_w := 1, s_w := 0, "Move disk from peg: ", from, " to peg: ", to );
move( n - 1, via, to, from )
end move ;
move( 4, 1, 2, 3 )
end. |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #AWK | AWK | BEGIN{print x="0"}
{gsub(/./," &",x);gsub(/ 0/,"01",x);gsub(/ 1/,"10",x);print x} |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #BASIC | BASIC |
tm = "0"
Function Thue_Morse(s)
k = ""
For i = 1 To Length(s)
If Mid(s, i, 1) = "1" Then
k += "0"
Else
k += "1"
End If
Next i
Thue_Morse = s + k
End Function
Print tm
For j = 1 To 7
tm = Thue_Morse(tm)
Print tm
Next j
End
|
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm | Tonelli-Shanks algorithm |
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computational number theory, the Tonelli–Shanks algorithm is a technique for solving for x in a congruence of the form:
x2 ≡ n (mod p)
where n is an integer which is a quadratic residue (mod p), p is an odd prime, and x,n ∈ Fp where Fp = {0, 1, ..., p - 1}.
It is used in cryptography techniques.
To apply the algorithm, we need the Legendre symbol:
The Legendre symbol (a | p) denotes the value of a(p-1)/2 (mod p).
(a | p) ≡ 1 if a is a square (mod p)
(a | p) ≡ -1 if a is not a square (mod p)
(a | p) ≡ 0 if a ≡ 0 (mod p)
Algorithm pseudo-code
All ≡ are taken to mean (mod p) unless stated otherwise.
Input: p an odd prime, and an integer n .
Step 0: Check that n is indeed a square: (n | p) must be ≡ 1 .
Step 1: By factoring out powers of 2 from p - 1, find q and s such that p - 1 = q2s with q odd .
If p ≡ 3 (mod 4) (i.e. s = 1), output the two solutions r ≡ ± n(p+1)/4 .
Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq .
Step 3: Set r ≡ n(q+1)/2, t ≡ nq, m = s .
Step 4: Loop the following:
If t ≡ 1, output r and p - r .
Otherwise find, by repeated squaring, the lowest i, 0 < i < m , such that t2i ≡ 1 .
Let b ≡ c2(m - i - 1), and set r ≡ rb, t ≡ tb2, c ≡ b2 and m = i .
Task
Implement the above algorithm.
Find solutions (if any) for
n = 10 p = 13
n = 56 p = 101
n = 1030 p = 10009
n = 1032 p = 10009
n = 44402 p = 100049
Extra credit
n = 665820697 p = 1000000009
n = 881398088036 p = 1000000000039
n = 41660815127637347468140745042827704103445750172002 p = 10^50 + 577
See also
Modular exponentiation
Cipolla's algorithm
| #EchoLisp | EchoLisp |
(require 'bigint)
;; test equality mod p
(define-syntax-rule (mod= a b p)
(zero? (% (- a b) p)))
;; assign mod p
(define-syntax-rule (mod:≡ s v p)
(set! s (% v p)))
(define (Legendre a p)
(powmod a (/ (1- p) 2) p))
(define (Tonelli n p)
(unless (= 1 (Legendre n p)) (error "not a square (mod p)" (list n p)))
(define q (1- p))
(define s 0)
(while (even? q)
(/= q 2)
(++ s))
(if (= s 1) (powmod n (/ (1+ p) 4) p)
(begin
(define z
(for ((z (in-range 2 p)))
#:break (= (1- p) (Legendre z p)) => z ))
(define c (powmod z q p))
(define r (powmod n (/ (1+ q) 2) p))
(define t (powmod n q p))
(define m s)
(define t2 0)
(while #t
#:break (mod= 1 t p) => r
(mod:≡ t2 (* t t) p)
(define i
(for ((i (in-range 1 m)))
#:break (mod= t2 1 p) => i
(mod:≡ t2 (* t2 t2) p)))
(define b (powmod c (expt 2 (- m i 1)) p))
(mod:≡ r (* r b) p)
(mod:≡ c (* b b) p)
(mod:≡ t (* t c) p)
(set! m i)))))
|
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
| #C.23 | C# | using System;
using System.Text;
using System.Collections.Generic;
public class TokenizeAStringWithEscaping
{
public static void Main() {
string testcase = "one^|uno||three^^^^|four^^^|^cuatro|";
foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) {
Console.WriteLine(": " + token); //Adding a : so we can see empty lines
}
}
}
public static class Extensions
{
public static IEnumerable<string> Tokenize(this string input, char separator, char escape) {
if (input == null) yield break;
var buffer = new StringBuilder();
bool escaping = false;
foreach (char c in input) {
if (escaping) {
buffer.Append(c);
escaping = false;
} else if (c == escape) {
escaping = true;
} else if (c == separator) {
yield return buffer.Flush();
} else {
buffer.Append(c);
}
}
if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush();
}
public static string Flush(this StringBuilder stringBuilder) {
string result = stringBuilder.ToString();
stringBuilder.Clear();
return result;
}
} |
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
| #Kotlin | Kotlin | // version 1.1.2
class Circle(val x: Double, val y: Double, val r: Double)
val circles = arrayOf(
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)
)
fun Double.sq() = this * this
fun main(args: Array<String>) {
val xMin = circles.map { it.x - it.r }.min()!!
val xMax = circles.map { it.x + it.r }.max()!!
val yMin = circles.map { it.y - it.r }.min()!!
val yMax = circles.map { it.y + it.r }.max()!!
val boxSide = 5000
val dx = (xMax - xMin) / boxSide
val dy = (yMax - yMin) / boxSide
var count = 0
for (r in 0 until boxSide) {
val y = yMin + r * dy
for (c in 0 until boxSide) {
val x = xMin + c * dx
val b = circles.any { (x - it.x).sq() + (y - it.y).sq() <= it.r.sq() }
if (b) count++
}
}
println("Approximate area = ${count * dx * dy}")
}
|
http://rosettacode.org/wiki/Topological_sort | Topological sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon.
The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on.
A tool exists that extracts library dependencies.
Task
Write a function that will return a valid compile order of VHDL libraries from their dependencies.
Assume library names are single words.
Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given.
Any self dependencies should be ignored.
Any un-orderable dependencies should be flagged.
Use the following data as an example:
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys
Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01.
C.f.
Topological sort/Extracted top item.
There are two popular algorithms for topological sorting:
Kahn's 1962 topological sort [1]
depth-first search [2] [3]
| #CoffeeScript | CoffeeScript |
toposort = (targets) ->
# targets is hash of sets, where keys are parent nodes and
# where values are sets that contain nodes that must precede the parent
# Start by identifying obviously independent nodes
independents = []
do ->
for k of targets
if targets[k].cnt == 0
delete targets[k]
independents.push k
# Note reverse dependencies for theoretical O(M+N) efficiency.
reverse_deps = []
do ->
for k of targets
for child of targets[k].v
reverse_deps[child] ?= []
reverse_deps[child].push k
# Now be greedy--start with independent nodes, then start
# breaking dependencies, and keep going as long as we still
# have independent nodes left.
result = []
while independents.length > 0
k = independents.pop()
result.push k
for parent in reverse_deps[k] or []
set_remove targets[parent], k
if targets[parent].cnt == 0
independents.push parent
delete targets[parent]
# Show unresolvable dependencies
for k of targets
console.log "WARNING: node #{k} is part of cyclical dependency"
result
parse_deps = ->
# parse string data, remove self-deps, and fill in gaps
#
# e.g. this would transform {a: "a b c", d: "e"} to this:
# a: set(b, c)
# b: set()
# c: set()
# d: set(e)
# e: set()
targets = {}
deps = set()
for k, v of data
targets[k] = set()
children = v.split(' ')
for child in children
continue if child == ''
set_add targets[k], child unless child == k
set_add deps, child
# make sure even leaf nodes are in targets
for dep of deps.v
if dep not of targets
targets[dep] = set()
targets
set = ->
cnt: 0
v: {}
set_add = (s, e) ->
return if s.v[e]
s.cnt += 1
s.v[e] = true
set_remove = (s, e) ->
return if !s.v[e]
s.cnt -= 1
delete s.v[e]
data =
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: ""
targets = parse_deps()
console.log toposort targets
|
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.
| #Haskell | Haskell | -- Some elementary types for Turing Machine
data Move = MLeft | MRight | Stay deriving (Show, Eq)
data Tape a = Tape a [a] [a]
data Action state val = Action val Move state deriving (Show)
instance (Show a) => Show (Tape a) where
show (Tape x lts rts) = concat $ left ++ [hd] ++ right
where hd = "[" ++ show x ++ "]"
left = map show $ reverse $ take 10 lts
right = map show $ take 10 rts
-- new tape
tape blank lts rts | null rts = Tape blank left blanks
| otherwise = Tape (head rts) left right
where blanks = repeat blank
left = reverse lts ++ blanks
right = tail rts ++ blanks
-- Turing Machine
step rules (state, Tape x (lh:lts) (rh:rts)) = (state', tape')
where Action x' dir state' = rules state x
tape' = move dir
move Stay = Tape x' (lh:lts) (rh:rts)
move MLeft = Tape lh lts (x':rh:rts)
move MRight = Tape rh (x':lh:lts) rts
runUTM rules stop start tape = steps ++ [final]
where (steps, final:_) = break ((== stop) . fst) $ iterate (step rules) (start, 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).
| #FreeBASIC | FreeBASIC |
#define esPar(n) (((n) And 1) = 0)
#define esImpar(n) (esPar(n) = 0)
Function Totient(n As Integer) As Integer
'delta son números no divisibles por 2,3,5
Dim delta(7) As Integer = {6,4,2,4,2,4,6,2}
Dim As Integer i, quot, idx, result
' div mod por constante es rápido.
'i = 2
result = n
If (2*2 <= n) Then
If Not(esImpar(n)) Then
' eliminar números con factor 2,4,8,16,...
While Not(esImpar(n))
n = n \ 2
Wend
'eliminar los múltiplos de 2
result -= result \ 2
End If
End If
'i = 3
If (3*3 <= n) And (n Mod 3 = 0) Then
Do
quot = n \ 3
If n <> quot*3 Then
Exit Do
Else
n = quot
End If
Loop Until false
result -= result \ 3
End If
'i = 5
If (5*5 <= n) And (n Mod 5 = 0) Then
Do
quot = n \ 5
If n <> quot*5 Then
Exit Do
Else
n = quot
End If
Loop Until false
result -= result \ 5
End If
i = 7
idx = 1
'i = 7,11,13,17,19,23,29,...,49 ..
While i*i <= n
quot = n \ i
If n = quot*i Then
Do
If n <> quot*i Then
Exit Do
Else
n = quot
End If
quot = n \ i
Loop Until false
result -= result \ i
End If
i = i + delta(idx)
idx = (idx+1) And 7
Wend
If n > 1 Then result -= result \ n
Totient = result
End Function
Sub ContandoPrimos(n As Integer)
Dim As Integer i, cnt = 0
For i = 1 To n
If Totient(i) = (i-1) Then cnt += 1
Next i
Print Using " ####### ######"; i-1; cnt
End Sub
Function esPrimo(n As Ulongint) As String
esPrimo = "False"
If n = 1 then Return "False"
If (n=2) Or (n=3) Then Return "True"
If n Mod 2=0 Then Exit Function
If n Mod 3=0 Then Exit Function
Dim As Ulongint limite = Sqr(N)+1
For i As Ulongint = 6 To limite Step 6
If N Mod (i-1)=0 Then Exit Function
If N Mod (i+1)=0 Then Exit Function
Next i
Return "True"
End Function
Sub display(n As Integer)
Dim As Integer idx, phi
If n = 0 Then Exit Sub
Print " n phi(n) esPrimo"
For idx = 1 To n
phi = Totient(idx)
Print Using "### ### \ \"; idx; phi; esPrimo(idx)
Next idx
End Sub
Dim l As Integer
display(25)
Print Chr(10) & " Limite Son primos"
ContandoPrimos(25)
l = 100
Do
ContandoPrimos(l)
l = l*10
Loop Until l > 1000000
End
|
http://rosettacode.org/wiki/Topswops | Topswops | Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is composed of reversing the first m cards where m is the value of the topmost card.
Rounds are repeated until the topmost card is the number 1 and the number of swaps is recorded.
For our example the swaps produce:
[2, 4, 1, 3] # Initial shuffle
[4, 2, 1, 3]
[3, 1, 2, 4]
[2, 1, 3, 4]
[1, 2, 3, 4]
For a total of four swaps from the initial ordering to produce the terminating case where 1 is on top.
For a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards.
Task
The task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive.
Note
Topswops is also known as Fannkuch from the German word Pfannkuchen meaning pancake.
Related tasks
Number reversal game
Sorting algorithms/Pancake sort
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | flip[a_] := Block[{a1 = First@a}, If[a1 == Length@a, Reverse[a], Join[Reverse[a[[;; a1]]], a[[a1 + 1 ;;]]]]]
swaps[a_] := Length@FixedPointList[flip, a] - 2
Print[#, ": ", Max[swaps /@ Permutations[Range@#]]] & /@ Range[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.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. Trig.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Pi-Third USAGE COMP-2.
01 Degree USAGE COMP-2.
01 60-Degrees USAGE COMP-2.
01 Result USAGE COMP-2.
PROCEDURE DIVISION.
COMPUTE Pi-Third = FUNCTION PI / 3
DISPLAY "Radians:"
DISPLAY " Sin(π / 3) = " FUNCTION SIN(Pi-Third)
DISPLAY " Cos(π / 3) = " FUNCTION COS(Pi-Third)
DISPLAY " Tan(π / 3) = " FUNCTION TAN(Pi-Third)
DISPLAY " Asin(0.5) = " FUNCTION ASIN(0.5)
DISPLAY " Acos(0.5) = " FUNCTION ACOS(0.5)
DISPLAY " Atan(0.5) = " FUNCTION ATAN(0.5)
COMPUTE Degree = FUNCTION PI / 180
COMPUTE 60-Degrees = Degree * 60
DISPLAY "Degrees:"
DISPLAY " Sin(60°) = " FUNCTION SIN(60-Degrees)
DISPLAY " Cos(60°) = " FUNCTION COS(60-Degrees)
DISPLAY " Tan(60°) = " FUNCTION TAN(60-Degrees)
COMPUTE Result = FUNCTION ASIN(0.5) / 60
DISPLAY " Asin(0.5) = " Result
COMPUTE Result = FUNCTION ACOS(0.5) / 60
DISPLAY " Acos(0.5) = " Result
COMPUTE Result = FUNCTION ATAN(0.5) / 60
DISPLAY " Atan(0.5) = " Result
GOBACK
. |
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).
| #Io | Io |
// Initialize objects to be used
in_num := File standardInput()
nums := List clone
result := Number
// Prompt the user and get numbers from standard input
"Please enter 11 numbers:" println
11 repeat(nums append(in_num readLine() asNumber()))
// Reverse the numbers received
nums reverseInPlace
// Apply the function and tell the user if the result is above
// our limit. Otherwise, tell them the result.
nums foreach(v,
// v needs parentheses around it for abs to properly convert v to its absolute value
result = (v) abs ** 0.5 + 5 * v ** 3
if (result > 400,
"Overflow!" println
,
result println
)
)
|
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).
| #J | J | tpk=: 3 :0
smoutput 'Enter 11 numbers: '
t1=: ((5 * ^&3) + (^&0.5@* *))"0 |. _999&".;._1 ' ' , 1!:1 [ 1
smoutput 'Values of functions of reversed input: ' , ": t1
; <@(,&' ')@": ` ((<'user alert ')&[) @. (>&400)"0 t1
) |
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.
| #TXR | TXR | (defmacro defconstraints (name size-name (var) . forms)
^(progn (defvar ,size-name ,(length forms))
(defun ,name (,var)
(list ,*forms))))
(defconstraints con con-count (s)
(= (length s) con-count) ;; tautology
(= (countq t [s -6..t]) 3)
(= (countq t (mapcar (op if (evenp @1) @2) (range 1) s)) 2)
(if [s 4] (and [s 5] [s 6]) t)
(none [s 1..3])
(= (countq t (mapcar (op if (oddp @1) @2) (range 1) s)) 4)
(and (or [s 1] [s 2]) (not (and [s 1] [s 2])))
(if [s 6] (and [s 4] [s 5]) t)
(= (countq t [s 0..6]) 3)
(and [s 10] [s 11])
(= (countq t [s 6..9]) 1)
(= (countq t [s 0..con-count]) 4))
(defun true-indices (truths)
(mappend (do if @1 ^(,@2)) truths (range 1)))
(defvar results
(append-each ((truths (rperm '(nil t) con-count)))
(let* ((vals (con truths))
(consist [mapcar eq truths vals])
(wrong-count (countq nil consist))
(pos-wrong (+ 1 (or (posq nil consist) -2))))
(cond
((zerop wrong-count)
^((:----> ,*(true-indices truths))))
((= 1 wrong-count)
^((:close ,*(true-indices truths) (:wrong ,pos-wrong))))))))
(each ((r results))
(put-line `@r`)) |
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.
| #uBasic.2F4tH | uBasic/4tH | S = 12
For T = 0 To (2^S)-1
For I = 1 To 12
Push T, 2^(I-1) : Gosub 100
@(I) = Pop() # 0
Next
REM Test consistency:
@(101) = @(1) = (S = 12)
@(102) = @(2) = ((@(7)+@(8)+@(9)+@(10)+@(11)+@(12)) = 3)
@(103) = @(3) = ((@(2)+@(4)+@(6)+@(8)+@(10)+@(12)) = 2)
@(104) = @(4) = ((@(5)=0) + (@(6) * @(7)) # 0)
@(105) = @(5) = ((@(2)=0) * (@(3)=0) * (@(4)=0))
@(106) = @(6) = ((@(1)+@(3)+@(5)+@(7)+@(9)+@(11)) = 4)
@(107) = @(7) = ((@(2) + @(3)) = 1)
@(108) = @(8) = ((@(7)=0) + (@(5) * @(6)) # 0)
@(109) = @(9) = ((@(1)+@(2)+@(3)+@(4)+@(5)+@(6)) = 3)
@(110) = @(10) = (@(11) * @(12))
@(111) = @(11) = ((@(7)+@(8)+@(9)) = 1)
@(112) = @(12) = ((@(1)+@(2)+@(3)+@(4)+@(5)+@(6)+@(7)+@(8)+@(9)+@(10)+@(11)) = 4)
Q = 0
For I = 101 To 112
Q = Q + @(I)
Next
If (Q = 11) Then
Print "Near miss with statements ";
For I = 1 To 12
If @(I) Then
Print I; " ";
Endif
If (@(I+100) = 0) Then
M = I
Endif
Next
Print "true (failed " ;M; ")."
Endif
If (Q = 12) Then
Print "Solution! with statements ";
For I = 1 TO 12
If @(I) Then
Print I; " ";
Endif
Next
Print "true."
Endif
Next
End
100 Rem a hard way to do a binary AND
q = Pop() : p = Pop() : Push 0
Do While (p * q) * (Tos() = 0)
Push Pop() + (p % 2) * (q % 2)
p = p / 2
q = q / 2
Loop
Return |
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.
| #Quackery | Quackery | [ stack ] is args ( --> s )
[ stack ] is results ( --> s )
[ stack ] is function ( --> s )
[ args share times
[ sp
2 /mod iff
[ char t ]
else
[ char f ]
emit ]
drop
say " | " ] is echoargs ( n --> )
[ args share times
[ 2 /mod swap ]
drop ] is preparestack ( n --> b*n )
[ results share times
[ sp
iff
[ char t ]
else
[ char f ]
emit ] ] is echoresults ( b*? --> )
[ say "Please input your function, preceded" cr
$ "by the number of arguments and results: " input
trim nextword quackery args put
trim nextword quackery results put
trim build function put
args share bit times
[ cr
i^ echoargs
i^ preparestack
function share do
echoresults ]
cr
args release
results release
function release ] is truthtable ( --> )
|
http://rosettacode.org/wiki/Ulam_spiral_(for_primes) | Ulam spiral (for primes) | An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1), constructed on a square grid, starting at the "center".
An Ulam spiral is also known as a prime spiral.
The first grid (green) is shown with sequential integers, starting at 1.
In an Ulam spiral of primes, only the primes are shown (usually indicated by some glyph such as a dot or asterisk), and all non-primes as shown as a blank (or some other whitespace).
Of course, the grid and border are not to be displayed (but they are displayed here when using these Wiki HTML tables).
Normally, the spiral starts in the "center", and the 2nd number is to the viewer's right and the number spiral starts from there in a counter-clockwise direction.
There are other geometric shapes that are used as well, including clock-wise spirals.
Also, some spirals (for the 2nd number) is viewed upwards from the 1st number instead of to the right, but that is just a matter of orientation.
Sometimes, the starting number can be specified to show more visual striking patterns (of prime densities).
[A larger than necessary grid (numbers wise) is shown here to illustrate the pattern of numbers on the diagonals (which may be used by the method to orientate the direction of spiral-construction algorithm within the example computer programs)].
Then, in the next phase in the transformation of the Ulam prime spiral, the non-primes are translated to blanks.
In the orange grid below, the primes are left intact, and all non-primes are changed to blanks.
Then, in the final transformation of the Ulam spiral (the yellow grid), translate the primes to a glyph such as a • or some other suitable glyph.
65
64
63
62
61
60
59
58
57
66
37
36
35
34
33
32
31
56
67
38
17
16
15
14
13
30
55
68
39
18
5
4
3
12
29
54
69
40
19
6
1
2
11
28
53
70
41
20
7
8
9
10
27
52
71
42
21
22
23
24
25
26
51
72
43
44
45
46
47
48
49
50
73
74
75
76
77
78
79
80
81
61
59
37
31
67
17
13
5
3
29
19
2
11
53
41
7
71
23
43
47
73
79
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
The Ulam spiral becomes more visually obvious as the grid increases in size.
Task
For any sized N × N grid, construct and show an Ulam spiral (counter-clockwise) of primes starting at some specified initial number (the default would be 1), with some suitably dotty (glyph) representation to indicate primes, and the absence of dots to indicate non-primes.
You should demonstrate the generator by showing at Ulam prime spiral large enough to (almost) fill your terminal screen.
Related tasks
Spiral matrix
Zig-zag matrix
Identity matrix
Sequence of primes by Trial Division
See also
Wikipedia entry: Ulam spiral
MathWorld™ entry: Prime Spiral
| #Raku | Raku | sub MAIN($max = 160, $start = 1) {
(my %world){0}{0} = 0;
my $loc = 0+0i;
my $dir = 1;
my $n = $start;
my $side = 0;
while ++$side < $max {
step for ^$side;
turn-left;
step for ^$side;
turn-left;
}
braille-graphics %world;
sub step {
$loc += $dir;
%world{$loc.im}{$loc.re} = $n if (++$n).is-prime;
}
sub turn-left { $dir *= -i; }
sub turn-right { $dir *= i; }
}
sub braille-graphics (%a) {
my ($ylo, $yhi, $xlo, $xhi);
for %a.keys -> $y {
$ylo min= +$y; $yhi max= +$y;
for %a{$y}.keys -> $x {
$xlo min= +$x; $xhi max= +$x;
}
}
for $ylo, $ylo + 4 ...^ * > $yhi -> \y {
for $xlo, $xlo + 2 ...^ * > $xhi -> \x {
my $cell = 0x2800;
$cell += 1 if %a{y + 0}{x + 0};
$cell += 2 if %a{y + 1}{x + 0};
$cell += 4 if %a{y + 2}{x + 0};
$cell += 8 if %a{y + 0}{x + 1};
$cell += 16 if %a{y + 1}{x + 1};
$cell += 32 if %a{y + 2}{x + 1};
$cell += 64 if %a{y + 3}{x + 0};
$cell += 128 if %a{y + 3}{x + 1};
print chr($cell);
}
print "\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.]
| #Julia | Julia |
function isltruncprime{T<:Integer}(n::T, base::T=10)
isprime(n) || return false
p = n
f = prevpow(base, p)
while 1 < f
(d, p) = divrem(p, f)
isprime(p) || return false
d != 0 || return false
f = div(f, base)
end
return true
end
function isrtruncprime{T<:Integer}(n::T, base::T=10)
isprime(n) || return false
p = n
while base < p
p = div(p, base)
isprime(p) || return false
end
return true
end
hi = 10^6
for i in reverse(primes(hi))
isltruncprime(i) || continue
println("The largest left truncatable prime ≤ ", hi, " is ", i, ".")
break
end
for i in reverse(primes(hi))
isrtruncprime(i) || continue
println("The largest right truncatable prime ≤ ", hi, " is ", i, ".")
break
end
|
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.
| #Bracmat | Bracmat | (
( tree
= 1
. (2.(4.7.) (5.))
(3.6.(8.) (9.))
)
& ( preorder
= K sub
. !arg:(?K.?sub) ?arg
& !K preorder$!sub preorder$!arg
|
)
& out$("preorder: " preorder$!tree)
& ( inorder
= K lhs rhs
. !arg:(?K.?sub) ?arg
& ( !sub:%?lhs ?rhs
& inorder$!lhs !K inorder$!rhs inorder$!arg
| !K
)
)
& out$("inorder: " inorder$!tree)
& ( postorder
= K sub
. !arg:(?K.?sub) ?arg
& postorder$!sub !K postorder$!arg
|
)
& out$("postorder: " postorder$!tree)
& ( levelorder
= todo tree sub
. !arg:(.)&
| !arg:(?tree.?todo)
& ( !tree:(?K.?sub) ?tree
& !K levelorder$(!tree.!todo !sub)
| levelorder$(!todo.)
)
)
& out$("level-order:" levelorder$(!tree.))
&
) |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program strTokenize64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ NBPOSTESECLAT, 20
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessFinal: .asciz "Words are : \n"
szString: .asciz "Hello,How,Are,You,Today"
szMessError: .asciz "Error tokenize !!\n"
szCarriageReturn: .asciz "\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main:
ldr x0,qAdrszString // string address
mov x1,',' // separator
bl stTokenize
cmp x0,-1 // error ?
beq 99f
mov x2,x0 // table address
ldr x0,qAdrszMessFinal // display message
bl affichageMess
ldr x4,[x2] // number of areas
add x2,x2,8 // first area
mov x3,0 // loop counter
mov x0,x2
1: // display loop
ldr x0,[x2,x3, lsl 3] // address area
bl affichageMess
ldr x0,qAdrszCarriageReturn // display carriage return
bl affichageMess
add x3,x3,1 // counter + 1
cmp x3,x4 // end ?
blt 1b // no -> loop
b 100f
99: // display error message
ldr x0,qAdrszMessError
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrszString: .quad szString
//qAdrszFinalString: .quad szFinalString
qAdrszMessFinal: .quad szMessFinal
qAdrszMessError: .quad szMessError
qAdrszCarriageReturn: .quad szCarriageReturn
/*******************************************************************/
/* Separate string by separator into an array */
/* areas are store on the heap Linux */
/*******************************************************************/
/* x0 contains string address */
/* x1 contains separator character (, or . or : ) */
/* x0 returns table address with first item = number areas */
/* and other items contains pointer of each string */
stTokenize:
stp x1,lr,[sp,-16]! // save registers
mov x16,x0
mov x9,x1 // save separator
mov x14,0
1: // compute length string for place reservation on the heap
ldrb w12,[x0,x14]
cbz x12, 2f
add x14,x14,1
b 1b
2:
ldr x12,qTailleTable
add x15,x12,x14
and x15,x15,0xFFFFFFFFFFFFFFF0
add x15,x15,16 // align word on the heap
// place reservation on the heap
mov x0,0 // heap address
mov x8,BRK // call system linux 'brk'
svc 0 // call system
cmp x0,-1 // error call system
beq 100f
mov x14,x0 // save address heap begin = begin array
add x0,x0,x15 // reserve x15 byte on the heap
mov x8,BRK // call system linux 'brk'
svc 0
cmp x0,-1
beq 100f
// string copy on the heap
add x13,x14,x12 // behind the array
mov x0,x16
mov x1,x13
3: // loop copy string
ldrb w12,[x0],1 // read one byte and increment pointer one byte
strb w12,[x1],1 // store one byte and increment pointer one byte
cbnz x12,3b // end of string ? no -> loop
mov x0,#0
str x0,[x14]
str x13,[x14,8]
mov x12,#1 // areas counter
4: // loop load string character
ldrb w0,[x13]
cbz x0,5f // end string
cmp x0,x9 // separator ?
cinc x13,x13,ne // no -> next location
bne 4b // and loop
strb wzr,[x13] // store zero final of string
add x13,x13,1 // next character
add x12,x12,1 // areas counter + 1
str x13,[x14,x12, lsl #3] // store address area in the table at index x2
b 4b // and loop
5:
str x12,[x14] // store number areas
mov x0,x14 // returns array address
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qTailleTable: .quad 8 * NBPOSTESECLAT
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ACL2 | ACL2 | (defun split-at (xs delim)
(if (or (endp xs) (eql (first xs) delim))
(mv nil (rest xs))
(mv-let (before after)
(split-at (rest xs) delim)
(mv (cons (first xs) before) after))))
(defun split (xs delim)
(if (endp xs)
nil
(mv-let (before after)
(split-at xs delim)
(cons before (split after delim)))))
(defun css->strs (css)
(if (endp css)
nil
(cons (coerce (first css) 'string)
(css->strs (rest css)))))
(defun split-str (str delim)
(css->strs (split (coerce str 'list) delim)))
(defun print-with (strs delim)
(if (endp strs)
(cw "~%")
(progn$ (cw (first strs))
(cw (coerce (list delim) 'string))
(print-with (rest strs) delim)))) |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
Find the top N salaries in each department, where N is provided as a parameter.
Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:
Employee Name,Employee ID,Salary,Department
Tyler Bennett,E10297,32000,D101
John Rappl,E21437,47000,D050
George Woltman,E00127,53500,D101
Adam Smith,E63535,18000,D202
Claire Buckman,E39876,27800,D202
David McClellan,E04242,41500,D101
Rich Holcomb,E01234,49500,D202
Nathan Adams,E41298,21900,D050
Richard Potter,E43128,15900,D101
David Motsinger,E27002,19250,D202
Tim Sampair,E03033,27000,D101
Kim Arlich,E10001,57000,D190
Timothy Grove,E16398,29900,D190
| #Arturo | Arturo | printTopEmployees: function [count, entries][
data: read.csv.withHeaders entries
departments: sort unique map data 'row -> row\Department
loop departments 'd [
print "----------------------"
print ["department:" d]
print "----------------------"
loop first.n: count
sort.descending.by:"Salary"
select data 'row [row\Department = d] 'employee ->
print [get employee "Employee Name" "->" employee\Salary]
print ""
]
]
printTopEmployees 2 {
Employee Name,Employee ID,Salary,Department
Tyler Bennett,E10297,32000,D101
John Rappl,E21437,47000,D050
George Woltman,E00127,53500,D101
Adam Smith,E63535,18000,D202
Claire Buckman,E39876,27800,D202
David McClellan,E04242,41500,D101
Rich Holcomb,E01234,49500,D202
Nathan Adams,E41298,21900,D050
Richard Potter,E43128,15900,D101
David Motsinger,E27002,19250,D202
Tim Sampair,E03033,27000,D101
Kim Arlich,E10001,57000,D190
Timothy Grove,E16398,29900,D190
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #AmigaE | AmigaE | PROC move(n, from, to, via)
IF n > 0
move(n-1, from, via, to)
WriteF('Move disk from pole \d to pole \d\n', from, to)
move(n-1, via, to, from)
ENDIF
ENDPROC
PROC main()
move(4, 1,2,3)
ENDPROC |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #BBC_BASIC | BBC BASIC | REM >thuemorse
tm$ = "0"
PRINT tm$
FOR i% = 1 TO 8
tm$ = FN_thue_morse(tm$)
PRINT tm$
NEXT
END
:
DEF FN_thue_morse(previous$)
LOCAL i%, tm$
tm$ = ""
FOR i% = 1 TO LEN previous$
IF MID$(previous$, i%, 1) = "1" THEN tm$ += "0" ELSE tm$ += "1"
NEXT
= previous$ + tm$ |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #BCPL | BCPL | get "libhdr"
let parity(x) =
x=0 -> 0,
(x&1) neqv parity(x>>1)
let start() be
$( for i=0 to 63 do writen(parity(i))
wrch('*N')
$) |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #Befunge | Befunge | :0\:!v!:\+g20\<>*:*-!#@_
86%2$_:2%02p2/^^82:+1,+* |
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm | Tonelli-Shanks algorithm |
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computational number theory, the Tonelli–Shanks algorithm is a technique for solving for x in a congruence of the form:
x2 ≡ n (mod p)
where n is an integer which is a quadratic residue (mod p), p is an odd prime, and x,n ∈ Fp where Fp = {0, 1, ..., p - 1}.
It is used in cryptography techniques.
To apply the algorithm, we need the Legendre symbol:
The Legendre symbol (a | p) denotes the value of a(p-1)/2 (mod p).
(a | p) ≡ 1 if a is a square (mod p)
(a | p) ≡ -1 if a is not a square (mod p)
(a | p) ≡ 0 if a ≡ 0 (mod p)
Algorithm pseudo-code
All ≡ are taken to mean (mod p) unless stated otherwise.
Input: p an odd prime, and an integer n .
Step 0: Check that n is indeed a square: (n | p) must be ≡ 1 .
Step 1: By factoring out powers of 2 from p - 1, find q and s such that p - 1 = q2s with q odd .
If p ≡ 3 (mod 4) (i.e. s = 1), output the two solutions r ≡ ± n(p+1)/4 .
Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq .
Step 3: Set r ≡ n(q+1)/2, t ≡ nq, m = s .
Step 4: Loop the following:
If t ≡ 1, output r and p - r .
Otherwise find, by repeated squaring, the lowest i, 0 < i < m , such that t2i ≡ 1 .
Let b ≡ c2(m - i - 1), and set r ≡ rb, t ≡ tb2, c ≡ b2 and m = i .
Task
Implement the above algorithm.
Find solutions (if any) for
n = 10 p = 13
n = 56 p = 101
n = 1030 p = 10009
n = 1032 p = 10009
n = 44402 p = 100049
Extra credit
n = 665820697 p = 1000000009
n = 881398088036 p = 1000000000039
n = 41660815127637347468140745042827704103445750172002 p = 10^50 + 577
See also
Modular exponentiation
Cipolla's algorithm
| #FreeBASIC | FreeBASIC | ' version 11-04-2017
' compile with: fbc -s console
' maximum for p is 17 digits to be on the save side
' TRUE/FALSE are built-in constants since FreeBASIC 1.04
' But we have to define them for older versions.
#Ifndef TRUE
#Define FALSE 0
#Define TRUE Not FALSE
#EndIf
Function mul_mod(a As ULongInt, b As ULongInt, modulus As ULongInt) As ULongInt
' returns a * b mod modulus
Dim As ULongInt x, y = a Mod modulus
While b > 0
If (b And 1) = 1 Then
x = (x + y) Mod modulus
End If
y = (y Shl 1) Mod modulus
b = b Shr 1
Wend
Return x
End Function
Function pow_mod(b As ULongInt, power As ULongInt, modulus As ULongInt) As ULongInt
' returns b ^ power mod modulus
Dim As ULongInt x = 1
While power > 0
If (power And 1) = 1 Then
' x = (x * b) Mod modulus
x = mul_mod(x, b, modulus)
End If
' b = (b * b) Mod modulus
b = mul_mod(b, b, modulus)
power = power Shr 1
Wend
Return x
End Function
Function Isprime(n As ULongInt, k As Long) As Long
' miller-rabin prime test
If n > 9223372036854775808ull Then ' limit 2^63, pow_mod/mul_mod can't handle bigger numbers
Print "number is to big, program will end"
Sleep
End
End If
' 2 is a prime, if n is smaller then 2 or n is even then n = composite
If n = 2 Then Return TRUE
If (n < 2) OrElse ((n And 1) = 0) Then Return FALSE
Dim As ULongInt a, x, n_one = n - 1, d = n_one
Dim As UInteger s
While (d And 1) = 0
d = d Shr 1
s = s + 1
Wend
While k > 0
k = k - 1
a = Int(Rnd * (n -2)) +2 ' 2 <= a < n
x = pow_mod(a, d, n)
If (x = 1) Or (x = n_one) Then Continue While
For r As Integer = 1 To s -1
x = pow_mod(x, 2, n)
If x = 1 Then Return FALSE
If x = n_one Then Continue While
Next
If x <> n_one Then Return FALSE
Wend
Return TRUE
End Function
Function legendre_symbol (a As LongInt, p As LongInt) As LongInt
Dim As LongInt x = pow_mod(a, ((p -1) \ 2), p)
If p -1 = x Then
Return x - p
Else
Return x
End If
End Function
' ------=< MAIN >=------
Dim As LongInt b, c, i, k, m, n, p, q, r, s, t, z
For k = 1 To 7
Read n, p
Print "Find solution for n ="; n; " and p =";p
If legendre_symbol(n, p) <> 1 Then
Print n;" is not a quadratic residue"
Print
Continue For
End If
If p = 2 OrElse Isprime(p, 15) = FALSE Then
Print p;" is not a odd prime"
Print
Continue For
End If
s = 0 : q = p -1
Do
s += 1
q \= 2
Loop Until (q And 1) = 1
If s = 1 And (p Mod 4) = 3 Then
r = pow_mod(n, ((p +1) \ 4), p)
Print "Solution found:"; r; " and"; p - r
Print
Continue For
End If
z = 1
Do
z += 1
Loop Until legendre_symbol(z, p) = -1
c = pow_mod(z, q, p)
r = pow_mod(n, (q +1) \ 2, p)
t = pow_mod(n, q, p)
m = s
Do
i = 0
If (t Mod p) = 1 Then
Print "Solution found:"; r; " and"; p - r
Print
Continue For
End If
Do
i += 1
If i >= m Then Continue For
Loop Until pow_mod(t, 2 ^ i, p) = 1
b = pow_mod(c, (2 ^ (m - i -1)), p)
r = mul_mod(r, b, p)
c = mul_mod(b, b, p)
t = mul_mod(t, c, p)' t = t * b ^ 2
m = i
Loop
Next
Data 10, 13, 56, 101, 1030, 10009, 1032, 10009, 44402, 100049
Data 665820697, 1000000009, 881398088036, 1000000000039
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
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
| #C.2B.2B | C++ | #include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
vector<string> tokenize(const string& input, char seperator, char escape) {
vector<string> output;
string token;
bool inEsc = false;
for (char ch : input) {
if (inEsc) {
inEsc = false;
} else if (ch == escape) {
inEsc = true;
continue;
} else if (ch == seperator) {
output.push_back(token);
token = "";
continue;
}
token += ch;
}
if (inEsc)
throw new invalid_argument("Invalid terminal escape");
output.push_back(token);
return output;
}
int main() {
string sample = "one^|uno||three^^^^|four^^^|^cuatro|";
cout << sample << endl;
cout << '[';
for (auto t : tokenize(sample, '|', '^')) {
cout << '"' << t << "\", ";
}
cout << ']' << endl;
return 0;
} |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | data = ImportString[" 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", "Table"];
toDisk[{x_, y_, r_}] := Disk[{x, y}, r];
RegionMeasure[RegionUnion[toDisk /@ data]] |
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]
| #Common_Lisp | Common Lisp | (defun topological-sort (graph &key (test 'eql))
"Graph is an association list whose keys are objects and whose
values are lists of objects on which the corresponding key depends.
Test is used to compare elements, and should be a suitable test for
hash-tables. Topological-sort returns two values. The first is a
list of objects sorted toplogically. The second is a boolean
indicating whether all of the objects in the input graph are present
in the topological ordering (i.e., the first value)."
(let ((entries (make-hash-table :test test)))
(flet ((entry (vertex)
"Return the entry for vertex. Each entry is a cons whose
car is the number of outstanding dependencies of vertex
and whose cdr is a list of dependants of vertex."
(multiple-value-bind (entry presentp) (gethash vertex entries)
(if presentp entry
(setf (gethash vertex entries) (cons 0 '()))))))
;; populate entries initially
(dolist (vertex graph)
(destructuring-bind (vertex &rest dependencies) vertex
(let ((ventry (entry vertex)))
(dolist (dependency dependencies)
(let ((dentry (entry dependency)))
(unless (funcall test dependency vertex)
(incf (car ventry))
(push vertex (cdr dentry))))))))
;; L is the list of sorted elements, and S the set of vertices
;; with no outstanding dependencies.
(let ((L '())
(S (loop for entry being each hash-value of entries
using (hash-key vertex)
when (zerop (car entry)) collect vertex)))
;; Until there are no vertices with no outstanding dependencies,
;; process vertices from S, adding them to L.
(do* () ((endp S))
(let* ((v (pop S)) (ventry (entry v)))
(remhash v entries)
(dolist (dependant (cdr ventry) (push v L))
(when (zerop (decf (car (entry dependant))))
(push dependant S)))))
;; return (1) the list of sorted items, (2) whether all items
;; were sorted, and (3) if there were unsorted vertices, the
;; hash table mapping these vertices to their dependants
(let ((all-sorted-p (zerop (hash-table-count entries))))
(values (nreverse L)
all-sorted-p
(unless all-sorted-p
entries))))))) |
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.
| #Icon_and_Unicon | Icon and Unicon | record TM(start,final,delta,tape,blank)
record delta(old_state, input_symbol, new_state, output_symbol, direction)
global start_tape
global show_count, full_display, trace_list # trace flags
procedure main(args)
init(args)
runTuringMachine(get_tm())
end
procedure init(args)
trace_list := ":"
while arg := get(args) do {
if arg == "-f" then full_display := "yes"
else if match("-t",arg) then trace_list ||:= arg[3:0]||":"
else show_count := integer(arg)
}
end
procedure get_tm()
D := table()
writes("What is the start state? ")
start := !&input
writes("What are the final states (colon separated)? ")
finals := !&input
(finals||":") ? every insert(fStates := set(), 1(tab(upto(':')),move(1)))
writes("What is the tape blank symbol?")
blank := !&input
write("Enter the delta mappings, using the following format:")
write("\tenter delta(curState,tapeSymbol) = (newState,newSymbol,direct) as")
write("\t curState:tapeSymbol:newState:newSymbol:direct");
write("\t\twhere direct is left, right, stay, or halt")
write("End with a blank line.")
write("")
every line := !&input do {
if *line = 0 then break
line ?
if (os := tab(upto(':')), move(1), ic := tab(upto(':')), move(1),
ns := tab(upto(':')), move(1), oc := tab(upto(':')), move(1),
d := map(tab(0))) then D[os||":"||ic] := delta(os,ic,ns,oc,d)
else write(line, " is in bad form, correct it")
}
if /start_tape then {
write("Enter the input tape")
start_tape := !&input
}
return TM(start,fStates,D,start_tape,blank)
end
procedure runTuringMachine(tm)
trans := tm.delta
rightside := tm.tape
if /rightside | (*rightside = 0) then rightside := tm.blank
leftside := ""
cur_state := tm.start
write("Machine starts in ",cur_state," with tape:")
show_tape(tm,leftside,rightside)
while mapping := \trans[cur_state||":"||rightside[1]] do {
rightside[1] := mapping.output_symbol
case mapping.direction of {
"left" : {
if *leftside = 0 then leftside := tm.blank
rightside := leftside[-1] || rightside
leftside[-1] := ""
}
"right" : {
leftside ||:= rightside[1]
rightside[1] := ""
if *rightside = 0 then rightside := tm.blank
}
"halt" : break
}
cur_state := mapping.new_state
if member(tm.final,cur_state) then break
trace(tm,cur_state,leftside,rightside)
}
write()
write("Machine halts in ",cur_state," with tape:")
show_tape(tm,leftside,rightside)
end
procedure trace(tm,cs,ls,rs)
static count, last_state
initial {
count := 0
last_state := ""
}
count +:= 1
if \show_count & (count % show_count = 0) then show_tape(tm,ls,rs)
if find(":"||cs||":",trace_list) & (last_state ~== cs) then {
writes("\tnow in state: ",cs," ")
if \full_display then show_delta(tm.delta[cs||":"||rs[1]])
else write()
}
last_state := cs
return
end
procedure show_delta(m)
if /m then write("NO MOVE!")
else {
writes("\tnext move is ")
writes("delta(",m.old_state,",",m.input_symbol,") ::= ")
write("(",m.new_state,",",m.output_symbol,",",m.direction,")")
}
end
procedure show_tape(tm,l,r)
l := reverse(trim(reverse(l),tm.blank))
r := trim(r,tm.blank)
write(l,r)
write(repl(" ",*l),"^")
end |
http://rosettacode.org/wiki/Totient_function | Totient function | The totient function is also known as:
Euler's totient function
Euler's phi totient function
phi totient function
Φ function (uppercase Greek phi)
φ function (lowercase Greek phi)
Definitions (as per number theory)
The totient function:
counts the integers up to a given positive integer n that are relatively prime to n
counts the integers k in the range 1 ≤ k ≤ n for which the greatest common divisor gcd(n,k) is equal to 1
counts numbers ≤ n and prime to n
If the totient number (for N) is one less than N, then N is prime.
Task
Create a totient function and:
Find and display (1 per line) for the 1st 25 integers:
the integer (the index)
the totient number for that integer
indicate if that integer is prime
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000 (optional)
Show all output here.
Related task
Perfect totient numbers
Also see
Wikipedia: Euler's totient function.
MathWorld: totient function.
OEIS: Euler totient function phi(n).
| #F.C5.8Drmul.C3.A6 | Fōrmulæ |
: totient \ n -- n' ;
DUP DUP 2 ?DO ( tot n )
DUP I DUP * < IF LEAVE THEN \ for(i=2;i*i<=n;i+=2){
DUP I MOD 0= IF \ if(n%i==0){
BEGIN DUP I /MOD SWAP 0= WHILE ( tot n n/i ) \ while(n%i==0);
NIP ( tot n/i ) \ n/=i;
REPEAT
DROP ( tot n ) \ Remove the new n on exit from loop
SWAP DUP I / - SWAP ( tot' n ) \ tot-=tot/i;
THEN
2 I 2 = + +LOOP \ If I = 2 add 1 else add 2 to loop index.
DUP 1 > IF OVER SWAP / - ELSE DROP THEN ;
: bool. \ f -- ;
IF ." True " ELSE ." False" THEN ;
: count-primes \ n -- n' ;
0 SWAP 2 ?DO I DUP totient 1+ = - LOOP ;
: challenge \ -- ;
CR ." n φ prime" CR
26 1 DO
I 3 .r
I totient DUP 4 .r 4 SPACES
1+ I = bool. CR
LOOP CR
100001 100 DO
." Number of primes up to " I 6 .R ." is " I count-primes 4 .R CR
I 9 * +LOOP ;
|
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
| #Nim | Nim | import strformat
const maxBest = 32
var best: array[maxBest, int]
proc trySwaps(deck: seq[int], f, d, n: int) =
if d > best[n]:
best[n] = d
for i in countdown(n - 1, 0):
if deck[i] == -1 or deck[i] == i:
break
if d + best[i] <= best[n]:
return
var deck2 = deck
for i in 1..<n:
var k = 1 shl i
if deck2[i] == -1:
if (f and k) != 0:
continue
elif deck2[i] != i:
continue
deck2[0] = i
for j in countdown(i - 1, 0):
deck2[i - j] = deck[j]
trySwaps(deck2, f or k, d + 1, n)
proc topswops(n: int): int =
assert(n > 0 and n < maxBest)
best[n] = 0
var deck0 = newSeq[int](n + 1)
for i in 1..<n:
deck0[i] = -1
trySwaps(deck0, 1, 0, n)
best[n]
for i in 1..10:
echo &"{i:2}: {topswops(i):2}" |
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
| #PARI.2FGP | PARI/GP | flip(v:vec)={
my(t=v[1]+1);
if (t==2, return(0));
for(i=1,t\2, [v[t-i],v[i]]=[v[i],v[t-i]]);
1+flip(v)
}
topswops(n)={
my(mx);
for(i=0,n!-1,
mx=max(flip(Vecsmall(numtoperm(n,i))),mx)
);
mx;
}
vector(10,n,topswops(n)) |
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.
| #Common_Lisp | Common Lisp | (defun deg->rad (x) (* x (/ pi 180)))
(defun rad->deg (x) (* x (/ 180 pi)))
(mapc (lambda (x) (format t "~s => ~s~%" x (eval x)))
'((sin (/ pi 4))
(sin (deg->rad 45))
(cos (/ pi 6))
(cos (deg->rad 30))
(tan (/ pi 3))
(tan (deg->rad 60))
(asin 1)
(rad->deg (asin 1))
(acos 1/2)
(rad->deg (acos 1/2))
(atan 15)
(rad->deg (atan 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).
| #Java | Java | /**
* Alexander Alvonellos
*/
import java.util.*;
import java.io.*;
public class TPKA {
public static void main(String... args) {
double[] input = new double[11];
double userInput = 0.0;
Scanner in = new Scanner(System.in);
for(int i = 0; i < 11; i++) {
System.out.print("Please enter a number: ");
String s = in.nextLine();
try {
userInput = Double.parseDouble(s);
} catch (NumberFormatException e) {
System.out.println("You entered invalid input, exiting");
System.exit(1);
}
input[i] = userInput;
}
for(int j = 10; j >= 0; j--) {
double x = input[j]; double y = f(x);
if( y < 400.0) {
System.out.printf("f( %.2f ) = %.2f\n", x, y);
} else {
System.out.printf("f( %.2f ) = %s\n", x, "TOO LARGE");
}
}
}
private static double f(double x) {
return Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));
}
}
|
http://rosettacode.org/wiki/Twelve_statements | Twelve statements | This puzzle is borrowed from math-frolic.blogspot.
Given the following twelve statements, which of them are true?
1. This is a numbered list of twelve statements.
2. Exactly 3 of the last 6 statements are true.
3. Exactly 2 of the even-numbered statements are true.
4. If statement 5 is true, then statements 6 and 7 are both true.
5. The 3 preceding statements are all false.
6. Exactly 4 of the odd-numbered statements are true.
7. Either statement 2 or 3 is true, but not both.
8. If statement 7 is true, then 5 and 6 are both true.
9. Exactly 3 of the first 6 statements are true.
10. The next two statements are both true.
11. Exactly 1 of statements 7, 8 and 9 are true.
12. Exactly 4 of the preceding statements are true.
Task
When you get tired of trying to figure it out in your head,
write a program to solve it, and print the correct answer or answers.
Extra credit
Print out a table of near misses, that is, solutions that are contradicted by only a single statement.
| #VBA | VBA | Public s As String '-- (eg "101101100010")
Public t As Integer '-- scratch
Function s1()
s1 = Len(s) = 12
End Function
Function s2()
t = 0
For i = 7 To 12
t = t - (Mid(s, i, 1) = "1")
Next i
s2 = t = 3
End Function
Function s3()
t = 0
For i = 2 To 12 Step 2
t = t - (Mid(s, i, 1) = "1")
Next i
s3 = t = 2
End Function
Function s4()
s4 = Mid(s, 5, 1) = "0" Or ((Mid(s, 6, 1) = "1" And Mid(s, 7, 1) = "1"))
End Function
Function s5()
s5 = Mid(s, 2, 1) = "0" And Mid(s, 3, 1) = "0" And Mid(s, 4, 1) = "0"
End Function
Function s6()
t = 0
For i = 1 To 12 Step 2
t = t - (Mid(s, i, 1) = "1")
Next i
s6 = t = 4
End Function
Function s7()
s7 = Mid(s, 2, 1) <> Mid(s, 3, 1)
End Function
Function s8()
s8 = Mid(s, 7, 1) = "0" Or (Mid(s, 5, 1) = "1" And Mid(s, 6, 1) = "1")
End Function
Function s9()
t = 0
For i = 1 To 6
t = t - (Mid(s, i, 1) = "1")
Next i
s9 = t = 3
End Function
Function s10()
s10 = Mid(s, 11, 1) = "1" And Mid(s, 12, 1) = "1"
End Function
Function s11()
t = 0
For i = 7 To 9
t = t - (Mid(s, i, 1) = "1")
Next i
s11 = t = 1
End Function
Function s12()
t = 0
For i = 1 To 11
t = t - (Mid(s, i, 1) = "1")
Next i
s12 = t = 4
End Function
Public Sub twelve_statements()
For i = 0 To 2 ^ 12 - 1
s = Right(CStr(WorksheetFunction.Dec2Bin(64 + i \ 128)), 5) _
& Right(CStr(WorksheetFunction.Dec2Bin(256 + i Mod 128)), 7)
For b = 1 To 12
Select Case b
Case 1: If s1 <> (Mid(s, b, 1) = "1") Then Exit For
Case 2: If s2 <> (Mid(s, b, 1) = "1") Then Exit For
Case 3: If s3 <> (Mid(s, b, 1) = "1") Then Exit For
Case 4: If s4 <> (Mid(s, b, 1) = "1") Then Exit For
Case 5: If s5 <> (Mid(s, b, 1) = "1") Then Exit For
Case 6: If s6 <> (Mid(s, b, 1) = "1") Then Exit For
Case 7: If s7 <> (Mid(s, b, 1) = "1") Then Exit For
Case 8: If s8 <> (Mid(s, b, 1) = "1") Then Exit For
Case 9: If s9 <> (Mid(s, b, 1) = "1") Then Exit For
Case 10: If s10 <> (Mid(s, b, 1) = "1") Then Exit For
Case 11: If s11 <> (Mid(s, b, 1) = "1") Then Exit For
Case 12: If s12 <> (Mid(s, b, 1) = "1") Then Exit For
End Select
If b = 12 Then Debug.Print s
Next
Next
End Sub |
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.
| #R | R |
truth_table <- function(x) {
vars <- unique(unlist(strsplit(x, "[^a-zA-Z]+")))
vars <- vars[vars != ""]
perm <- expand.grid(rep(list(c(FALSE, TRUE)), length(vars)))
names(perm) <- vars
perm[ , x] <- with(perm, eval(parse(text = x)))
perm
}
"%^%" <- xor # define unary xor operator
truth_table("!A") # not
## A !A
## 1 FALSE TRUE
## 2 TRUE FALSE
truth_table("A | B") # or
## A B A | B
## 1 FALSE FALSE FALSE
## 2 TRUE FALSE TRUE
## 3 FALSE TRUE TRUE
## 4 TRUE TRUE TRUE
truth_table("A & B") # and
## A B A & B
## 1 FALSE FALSE FALSE
## 2 TRUE FALSE FALSE
## 3 FALSE TRUE FALSE
## 4 TRUE TRUE TRUE
truth_table("A %^% B") # xor
## A B A %^% B
## 1 FALSE FALSE FALSE
## 2 TRUE FALSE TRUE
## 3 FALSE TRUE TRUE
## 4 TRUE TRUE FALSE
truth_table("S | (T %^% U)") # 3 variables with brackets
## S T U S | (T %^% U)
## 1 FALSE FALSE FALSE FALSE
## 2 TRUE FALSE FALSE TRUE
## 3 FALSE TRUE FALSE TRUE
## 4 TRUE TRUE FALSE TRUE
## 5 FALSE FALSE TRUE TRUE
## 6 TRUE FALSE TRUE TRUE
## 7 FALSE TRUE TRUE FALSE
## 8 TRUE TRUE TRUE TRUE
truth_table("A %^% (B %^% (C %^% D))") # 4 variables with nested brackets
## A B C D A %^% (B %^% (C %^% D))
## 1 FALSE FALSE FALSE FALSE FALSE
## 2 TRUE FALSE FALSE FALSE TRUE
## 3 FALSE TRUE FALSE FALSE TRUE
## 4 TRUE TRUE FALSE FALSE FALSE
## 5 FALSE FALSE TRUE FALSE TRUE
## 6 TRUE FALSE TRUE FALSE FALSE
## 7 FALSE TRUE TRUE FALSE FALSE
## 8 TRUE TRUE TRUE FALSE TRUE
## 9 FALSE FALSE FALSE TRUE TRUE
## 10 TRUE FALSE FALSE TRUE FALSE
## 11 FALSE TRUE FALSE TRUE FALSE
## 12 TRUE TRUE FALSE TRUE TRUE
## 13 FALSE FALSE TRUE TRUE FALSE
## 14 TRUE FALSE TRUE TRUE TRUE
## 15 FALSE TRUE TRUE TRUE TRUE
## 16 TRUE TRUE TRUE TRUE FALSE
|
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
| #REXX | REXX | /*REXX program shows counter─clockwise Ulam spiral of primes shown in a square matrix.*/
parse arg size init char . /*obtain optional arguments from the CL*/
if size=='' | size=="," then size= 79 /*Not specified? Then use the default.*/
if init=='' | init=="," then init= 1 /* " " " " " " */
if char=='' then char= "█" /* " " " " " " */
tot=size**2 /*the total number of numbers in spiral*/
/*define the upper/bottom right corners*/
uR.=0; bR.=0; do od=1 by 2 to tot; _=od**2+1; uR._=1; _=_+od; bR._=1; end /*od*/
/*define the bottom/upper left corners.*/
bL.=0; uL.=0; do ev=2 by 2 to tot; _=ev**2+1; bL._=1; _=_+ev; uL._=1; end /*ev*/
app=1; bigP=0; #p=0; inc=0; minR=1; maxR=1; r=1; $=0; $.=; !.=
/*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ construct the spiral #s.*/
do i=init for tot; r= r + inc; minR= min(minR, r); maxR= max(maxR, r)
x= isPrime(i); if x then bigP= max(bigP, i); #p= #p + x /*bigP, #primes.*/
if app then $.r= $.r || x /*append token.*/
else $.r= x || $.r /*prepend token.*/
if uR.i then do; app= 1; inc= +1; iterate /*i*/; end /*advance ↓ */
if bL.i then do; app= 0; inc= -1; iterate /*i*/; end /* " ↑ */
if bR.i then do; app= 0; inc= 0; iterate /*i*/; end /* " ► */
if uL.i then do; app= 1; inc= 0; iterate /*i*/; end /* " ◄ */
end /*i*/ /* [↓] pack two */
/*lines ──► one.*/
do j=minR to maxR by 2; jp= j + 1; $= $ + 1 /*fold two lines*/
do k=1 for length($.j); top= substr($.j, k, 1) /*the 1st line.*/
bot= word( substr($.jp, k, 1) 0, 1) /*the 2nd line.*/
if top then if bot then !.$= !.$'█' /*has top & bot.*/
else !.$= !.$'▀' /*has top,¬ bot.*/
else if bot then !.$= !.$'▄' /*¬ top, has bot*/
else !.$= !.$' ' /*¬ top, ¬ bot*/
end /*k*/
end /*j*/ /* [↓] show the prime spiral matrix.*/
do m=1 for $; say !.m; end /*m*/
say; say init 'is the starting point,' ,
tot 'numbers used,' #p "primes found, largest prime:" bigP
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isPrime: procedure; parse arg x; if wordpos(x, '2 3 5 7 11 13 17 19') \==0 then return 1
if x<17 then return 0; if x// 2 ==0 then return 0
if x// 3 ==0 then return 0
/*get the last digit*/ parse var x '' -1 _; if _==5 then return 0
if x// 7 ==0 then return 0
if x//11 ==0 then return 0
if x//13 ==0 then return 0
do j=17 by 6 until j*j > x; if x//j ==0 then return 0
if x//(j+2) ==0 then return 0
end /*j*/; return 1 |
http://rosettacode.org/wiki/Truncatable_primes | Truncatable primes | A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.
Examples
The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.
The number 7393 is a right-truncatable prime as the numbers 7393, 739, 73, and 7 formed by removing digits from its right are also prime.
No zeroes are allowed in truncatable primes.
Task
The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied).
Related tasks
Find largest left truncatable prime in a given base
Sieve of Eratosthenes
See also
Truncatable Prime from MathWorld.]
| #Kotlin | Kotlin | // version 1.0.5-2
fun isPrime(n: Int) : Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d : Int = 5
while (d * d <= n) {
if (n % d == 0) return false
d += 2
if (n % d == 0) return false
d += 4
}
return true
}
fun main(args: Array<String>) {
var j: Char
var p: Int
var pow: Int
var lMax: Int = 2
var rMax: Int = 2
var s: String
// calculate maximum left truncatable prime less than 1 million
loop@ for( i in 3..999997 step 2) {
s = i.toString()
if ('0' in s) continue
j = s[s.length - 1]
if (j == '1' || j == '9') continue
p = i
pow = 1
for (k in 1..s.length - 1) pow *= 10
while(pow > 1) {
if (!isPrime(p)) continue@loop
p %= pow
pow /= 10
}
lMax = i
}
// calculate maximum right truncatable prime less than 1 million
loop@ for( i in 3..799999 step 2) {
s = i.toString()
if ('0' in s) continue
j = s[0]
if (j == '1' || j == '4' || j == '6') continue
p = i
while(p > 0) {
if (!isPrime(p)) continue@loop
p /= 10
}
rMax = i
}
println("Largest left truncatable prime : " + lMax.toString())
println("Largest right truncatable prime : " + rMax.toString())
} |
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.
| #C | C | #include <stdlib.h>
#include <stdio.h>
typedef struct node_s
{
int value;
struct node_s* left;
struct node_s* right;
} *node;
node tree(int v, node l, node r)
{
node n = malloc(sizeof(struct node_s));
n->value = v;
n->left = l;
n->right = r;
return n;
}
void destroy_tree(node n)
{
if (n->left)
destroy_tree(n->left);
if (n->right)
destroy_tree(n->right);
free(n);
}
void preorder(node n, void (*f)(int))
{
f(n->value);
if (n->left)
preorder(n->left, f);
if (n->right)
preorder(n->right, f);
}
void inorder(node n, void (*f)(int))
{
if (n->left)
inorder(n->left, f);
f(n->value);
if (n->right)
inorder(n->right, f);
}
void postorder(node n, void (*f)(int))
{
if (n->left)
postorder(n->left, f);
if (n->right)
postorder(n->right, f);
f(n->value);
}
/* helper queue for levelorder */
typedef struct qnode_s
{
struct qnode_s* next;
node value;
} *qnode;
typedef struct { qnode begin, end; } queue;
void enqueue(queue* q, node n)
{
qnode node = malloc(sizeof(struct qnode_s));
node->value = n;
node->next = 0;
if (q->end)
q->end->next = node;
else
q->begin = node;
q->end = node;
}
node dequeue(queue* q)
{
node tmp = q->begin->value;
qnode second = q->begin->next;
free(q->begin);
q->begin = second;
if (!q->begin)
q->end = 0;
return tmp;
}
int queue_empty(queue* q)
{
return !q->begin;
}
void levelorder(node n, void(*f)(int))
{
queue nodequeue = {};
enqueue(&nodequeue, n);
while (!queue_empty(&nodequeue))
{
node next = dequeue(&nodequeue);
f(next->value);
if (next->left)
enqueue(&nodequeue, next->left);
if (next->right)
enqueue(&nodequeue, next->right);
}
}
void print(int n)
{
printf("%d ", n);
}
int main()
{
node n = tree(1,
tree(2,
tree(4,
tree(7, 0, 0),
0),
tree(5, 0, 0)),
tree(3,
tree(6,
tree(8, 0, 0),
tree(9, 0, 0)),
0));
printf("preorder: ");
preorder(n, print);
printf("\n");
printf("inorder: ");
inorder(n, print);
printf("\n");
printf("postorder: ");
postorder(n, print);
printf("\n");
printf("level-order: ");
levelorder(n, print);
printf("\n");
destroy_tree(n);
return 0;
} |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Action.21 | Action! | SET EndProg=* |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ActionScript | ActionScript | var hello:String = "Hello,How,Are,You,Today";
var tokens:Array = hello.split(",");
trace(tokens.join("."));
// Or as a one-liner
trace("Hello,How,Are,You,Today".split(",").join(".")); |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
Find the top N salaries in each department, where N is provided as a parameter.
Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:
Employee Name,Employee ID,Salary,Department
Tyler Bennett,E10297,32000,D101
John Rappl,E21437,47000,D050
George Woltman,E00127,53500,D101
Adam Smith,E63535,18000,D202
Claire Buckman,E39876,27800,D202
David McClellan,E04242,41500,D101
Rich Holcomb,E01234,49500,D202
Nathan Adams,E41298,21900,D050
Richard Potter,E43128,15900,D101
David Motsinger,E27002,19250,D202
Tim Sampair,E03033,27000,D101
Kim Arlich,E10001,57000,D190
Timothy Grove,E16398,29900,D190
| #AutoHotkey | AutoHotkey | Departments = D050, D101, D190, D202
StringSplit, Department_, Departments, `,, %A_Space%
; Employee Name, Employee ID, Salary, Department
Add_Employee("Tyler Bennett ", "E10297", 32000, "D101")
Add_Employee("John Rappl ", "E21437", 47000, "D050")
Add_Employee("George Woltman ", "E00127", 53500, "D101")
Add_Employee("Adam Smith ", "E63535", 18000, "D202")
Add_Employee("Claire Buckman ", "E39876", 27800, "D202")
Add_Employee("David McClellan", "E04242", 41500, "D101")
Add_Employee("Rich Holcomb ", "E01234", 49500, "D202")
Add_Employee("Nathan Adams ", "E41298", 21900, "D050")
Add_Employee("Richard Potter ", "E43128", 15900, "D101")
Add_Employee("David Motsinger", "E27002", 19250, "D202")
Add_Employee("Tim Sampair ", "E03033", 27000, "D101")
Add_Employee("Kim Arlich ", "E10001", 57000, "D190")
Add_Employee("Timothy Grove ", "E16398", 29900, "D190")
; display top 3 ranks for each department
Loop, %Department_0% ; all departments
MsgBox,, % "Department: " Department_%A_Index%
, % TopRank(3, Department_%A_Index%)
;---------------------------------------------------------------------------
TopRank(N, Department) { ; find the top N salaries in each department
;---------------------------------------------------------------------------
local Collection := Msg := ""
Loop, %m% ; all employees
If (Employee_%A_Index%_Dept = Department)
; collect all the salaries being paid in this department
Collection .= (Collection ? "," : "") Employee_%A_Index%_Salary
Sort, Collection, ND,R
StringSplit, Collection, Collection, `,
Loop, % (N < Collection0) ? N : Collection0 {
Salary := Collection%A_Index%
Loop, %m% ; find the respective employee
If (Employee_%A_Index%_Salary = Salary)
; and put out his/her details
Msg .= Employee_%A_Index%_Name "`t"
. Employee_%A_Index%_ID "`t"
. Employee_%A_Index%_Salary "`t"
. Employee_%A_Index%_Dept "`t`n"
}
Return, Msg
}
;---------------------------------------------------------------------------
Add_Employee(Name, ID, Salary, Department) {
;---------------------------------------------------------------------------
global
m++
Employee_%m%_Name := Name
Employee_%m%_ID := ID
Employee_%m%_Salary := Salary
Employee_%m%_Dept := Department
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Amazing_Hopper | Amazing Hopper |
#include <hopper.h>
#proto hanoi(_X_,_Y_,_Z_,_W_)
main:
get arg number (2,discos)
{discos}!neg? do{fail=0,mov(fail),{"I need a positive (or zero) number here, not: ",fail}println,exit(0)}
pos? do{
_hanoi( discos, "A", "B", "C" )
}
exit(0)
.locals
hanoi(discos,inicio,aux,fin)
iif( {discos}eqto(1), {inicio, "->", fin, "\n"};print, _hanoi({discos}minus(1), inicio,fin,aux);\
{inicio, "->", fin, "\n"};print;\
_hanoi({discos}minus(1), aux, inicio, fin))
back
|
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #BQN | BQN | TM ← {𝕩↑(⊢∾¬)⍟(1+⌈2⋆⁼𝕩)⥊0}
TM 25 #get first 25 elements |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){
char sequence[256+1] = "0";
char inverse[256+1] = "1";
char buffer[256+1];
int i;
for(i = 0; i < 8; i++){
strcpy(buffer, sequence);
strcat(sequence, inverse);
strcat(inverse, buffer);
}
puts(sequence);
return 0;
} |
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm | Tonelli-Shanks algorithm |
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computational number theory, the Tonelli–Shanks algorithm is a technique for solving for x in a congruence of the form:
x2 ≡ n (mod p)
where n is an integer which is a quadratic residue (mod p), p is an odd prime, and x,n ∈ Fp where Fp = {0, 1, ..., p - 1}.
It is used in cryptography techniques.
To apply the algorithm, we need the Legendre symbol:
The Legendre symbol (a | p) denotes the value of a(p-1)/2 (mod p).
(a | p) ≡ 1 if a is a square (mod p)
(a | p) ≡ -1 if a is not a square (mod p)
(a | p) ≡ 0 if a ≡ 0 (mod p)
Algorithm pseudo-code
All ≡ are taken to mean (mod p) unless stated otherwise.
Input: p an odd prime, and an integer n .
Step 0: Check that n is indeed a square: (n | p) must be ≡ 1 .
Step 1: By factoring out powers of 2 from p - 1, find q and s such that p - 1 = q2s with q odd .
If p ≡ 3 (mod 4) (i.e. s = 1), output the two solutions r ≡ ± n(p+1)/4 .
Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq .
Step 3: Set r ≡ n(q+1)/2, t ≡ nq, m = s .
Step 4: Loop the following:
If t ≡ 1, output r and p - r .
Otherwise find, by repeated squaring, the lowest i, 0 < i < m , such that t2i ≡ 1 .
Let b ≡ c2(m - i - 1), and set r ≡ rb, t ≡ tb2, c ≡ b2 and m = i .
Task
Implement the above algorithm.
Find solutions (if any) for
n = 10 p = 13
n = 56 p = 101
n = 1030 p = 10009
n = 1032 p = 10009
n = 44402 p = 100049
Extra credit
n = 665820697 p = 1000000009
n = 881398088036 p = 1000000000039
n = 41660815127637347468140745042827704103445750172002 p = 10^50 + 577
See also
Modular exponentiation
Cipolla's algorithm
| #Go | Go | package main
import "fmt"
// Arguments n, p as described in WP
// If Legendre symbol != 1, ok return is false. Otherwise ok return is true,
// R1 is WP return value R and for convenience R2 is p-R1.
func ts(n, p int) (R1, R2 int, ok bool) {
// a^e mod p
powModP := func(a, e int) int {
s := 1
for ; e > 0; e-- {
s = s * a % p
}
return s
}
// Legendre symbol, returns 1, 0, or -1 mod p -- that's 1, 0, or p-1.
ls := func(a int) int {
return powModP(a, (p-1)/2)
}
// argument validation
if ls(n) != 1 {
return 0, 0, false
}
// WP step 1, factor out powers two.
// variables Q, S named as at WP.
Q := p - 1
S := 0
for Q&1 == 0 {
S++
Q >>= 1
}
// WP step 1, direct solution
if S == 1 {
R1 = powModP(n, (p+1)/4)
return R1, p - R1, true
}
// WP step 2, select z, assign c
z := 2
for ; ls(z) != p-1; z++ {
}
c := powModP(z, Q)
// WP step 3, assign R, t, M
R := powModP(n, (Q+1)/2)
t := powModP(n, Q)
M := S
// WP step 4, loop
for {
// WP step 4.1, termination condition
if t == 1 {
return R, p - R, true
}
// WP step 4.2, find lowest i...
i := 0
for z := t; z != 1 && i < M-1; {
z = z * z % p
i++
}
// WP step 4.3, using a variable b, assign new values of R, t, c, M
b := c
for e := M - i - 1; e > 0; e-- {
b = b * b % p
}
R = R * b % p
c = b * b % p // more convenient to compute c before t
t = t * c % p
M = i
}
}
func main() {
fmt.Println(ts(10, 13))
fmt.Println(ts(56, 101))
fmt.Println(ts(1030, 10009))
fmt.Println(ts(1032, 10009))
fmt.Println(ts(44402, 100049))
} |
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
| #CLU | CLU | tokenize = iter (sep, esc: char, s: string) yields (string)
escape: bool := false
part: array[char] := array[char]$[]
for c: char in string$chars(s) do
if escape then
escape := false
array[char]$addh(part,c)
elseif c=esc then
escape := true
elseif c=sep then
yield(string$ac2s(part))
part := array[char]$[]
else
array[char]$addh(part,c)
end
end
yield(string$ac2s(part))
end tokenize
start_up = proc ()
po: stream := stream$primary_output()
testcase: string := "one^|uno||three^^^^|four^^^|^quatro|"
for part: string in tokenize('|', '^', testcase) do
stream$putl(po, "\"" || part || "\"")
end
end start_up |
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
| #COBOL | COBOL | >>SOURCE FORMAT FREE
identification division.
program-id. 'tokenizewithescaping'.
environment division.
configuration section.
repository.
function all intrinsic.
data division.
working-storage section.
01 escape-char pic x value '^'.
01 separator-char pic x value '|'.
01 reference-string pic x(64) value
'one^|uno||three^^^^|four^^^|^cuatro|'.
01 input-string pic x(64).
01 c pic 99.
01 escaped pic x.
01 t pic 99.
01 t-max pic 99.
01 t-lim pic 99 value 32.
01 token-entry occurs 32.
03 token-len pic 99.
03 token pic x(16).
01 l pic 99.
01 l-lim pic 99 value 16.
01 error-found pic x.
procedure division.
start-tokenize-with-escaping.
move reference-string to input-string
perform tokenize
move 'token' to input-string
perform tokenize
move '^^^^^^^^' to input-string
perform tokenize
move '||||||||' to input-string
perform tokenize
move all 'token' to input-string
perform tokenize
move all 't|' to input-string
perform tokenize
move spaces to input-string
perform tokenize
display space
stop run
.
tokenize.
display space
display 'string:'
display input-string
move 'N' to escaped error-found
move 1 to t-max
initialize token-entry(t-max)
move 0 to l
perform varying c from 1 by 1 until
c > length(input-string)
or input-string(c:) = spaces
evaluate escaped also input-string(c:1)
when 'N' also escape-char
move 'Y' to escaped
when 'N' also separator-char
perform increment-t-max
if error-found = 'Y'
exit paragraph
end-if
when 'N' also any
perform move-c
if error-found = 'Y'
exit paragraph
end-if
when 'Y' also any
perform move-c
if error-found = 'Y'
exit paragraph
end-if
move 'N' to escaped
end-evaluate
end-perform
if l > 0
move l to token-len(t-max)
end-if
if c = 1
display 'no tokens'
else
display 'tokens:'
perform varying t from 1 by 1 until t > t-max
if token-len(t) > 0
display t ': ' token-len(t) space token(t)
else
display t ': ' token-len(t)
end-if
end-perform
end-if
.
increment-t-max.
if t-max >= t-lim
display 'error: at ' c ' number of tokens exceeds ' t-lim
move 'Y' to error-found
else
move l to token-len(t-max)
add 1 to t-max
initialize token-entry(t-max)
move 0 to l
move 'N' to error-found
end-if
.
move-c.
if l >= l-lim
display 'error: at ' c ' token length exceeds ' l-lim
move 'Y' to error-found
else
add 1 to l
move input-string(c:1) to token(t-max)(l:1)
move 'N' to error-found
end-if
.
end program 'tokenizewithescaping'.
|
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
| #MATLAB_.2F_Octave | MATLAB / Octave | function res = circles()
tic
%
% Size of my grid -- higher values => higher accuracy.
%
ngrid = 5000;
xc = [1.6417233788 -1.4944608174 0.6110294452 0.3844862411 -0.2495892950 1.7813504266 -0.1985249206 -1.7011985145 -0.4319462812 0.2178372997 -0.6294854565 1.7952608455 1.4168575317 1.4637371396 -0.5263668798 -1.2197352481 -0.1389358881 1.5293954595 -0.5258728625 -0.1403562064 0.8055826339 -0.6311979224 1.4685857879 -0.6855727502 0.0152957411];
yc = [1.6121789534 1.2077959613 -0.6907087527 0.2923344616 -0.3832854473 1.6178237031 -0.8343333301 -0.1263820964 1.4104420482 -0.9499557344 -1.3078893852 0.6281269104 1.0683357171 0.9463877418 1.7315156631 0.9144146579 0.1092805780 0.0030278255 1.3782633069 0.2437382535 -0.0482092025 0.7184578971 -0.8347049536 1.6465021616 0.0638919221];
r = [0.0848270516 1.1039549836 0.9089162485 0.2375743054 1.0845181219 0.8162655711 0.0538864941 0.4776976918 0.7886291537 0.0357871187 0.7653357688 0.2727652452 1.1016025378 1.1846214562 1.4428514068 1.0727263474 0.7350208828 1.2472867347 1.3495508831 1.3804956588 0.3327165165 0.2491045282 1.3670667538 1.0593087096 0.9771215985];
r2 = r .* r;
ncircles = length(xc);
%
% Compute the bounding box of the circles.
%
xmin = min(xc-r);
xmax = max(xc+r);
ymin = min(yc-r);
ymax = max(yc+r);
%
% Keep a counter.
%
inside = 0;
%
% For every point in my grid.
%
for x = linspace(xmin,xmax,ngrid)
for y = linspace(ymin,ymax,ngrid)
if any(r2 > (x - xc).^2 + (y - yc).^2)
inside = inside + 1;
end
end
end
box_area = (xmax-xmin) * (ymax-ymin);
res = box_area * inside / ngrid^2;
toc
end |
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]
| #Crystal | Crystal | def dfs_topo_visit(n, g, tmp, permanent, l)
if permanent.includes?(n)
return
elsif tmp.includes?(n)
raise "unorderable: circular dependency detected involving '#{n}'"
end
tmp.add(n)
g[n].each { |m|
dfs_topo_visit(m, g, tmp, permanent, l)
}
tmp.delete(n)
permanent.add(n)
l.insert(0, n)
end
def dfs_topo_sort(g)
tmp = Set(String).new
permanent = Set(String).new
l = Array(String).new
while true
keys = g.keys.to_set - permanent
if keys.empty?
break
end
n = keys.first
dfs_topo_visit(n, g, tmp, permanent, l)
end
return l
end
def build_graph(deps)
g = {} of String => Set(String)
deps.split("\n").each { |line|
line_split = line.strip.split
line_split.each { |dep|
unless g.has_key?(dep)
g[dep] = Set(String).new
end
unless line_split[0] == dep
g[dep].add(line_split[0])
end
}
}
return g
end
data = "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"
circular_deps = "\ncyc01 cyc02
cyc02 cyc01"
puts dfs_topo_sort(build_graph(data)).join(" -> ")
puts ""
puts dfs_topo_sort(build_graph(data + circular_deps)).join(" -> ")
|
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.
| #J | J | ". noun define -. CRLF NB. Fixed tacit universal Turing machine code...
utm=.
(((":@:(]&:>)@:(6&({::)) ,: (":@] 9&({::))) ,. ':'"_) ,. 2&({::) >@:(((48 + ]
) { a."_)@[ ; (] $ ' '"_) , '^'"_) 3&({::))@:([ (0 0 $ 1!:2&2)@:('A changeles
s cycle was detected!'"_)^:(-.@:(_1"_ = 1&({::))))@:((((3&({::) + 8&({::)) ;
1 + 9&({::)) 3 9} ])@:(<@:((0 (0 {:: ])`(<@:(1 {:: ]))`(2 {:: ])} ])@:(7 3 2&
{)) 2} ])@:(<"0@:(6&({::) (<@[ { ]) 0&({::)) 7 8 1} ])@:([ (0 0 $ 1!:2&2)@:((
(":@:(]&:>)@:(6&({::)) ,: (":@] 9&({::))) ,. ':'"_) ,. 2&({::) >@:(((48 + ])
{ a."_)@[ ; (] $ ' '"_) , '^'"_) 3&({::))^:(0 = 4&({::) | 9&({::)))@:(<@:(1&(
{::) ; 3&({::) { 2&({::)) 6} ])@:(<@:(3&({::) + _1 = 3&({::)) 3} ])@:(<@:(((_
1 = 3&({::)) {:: 5&({::)) , 2&({::) , (3&({::) = #@:(2&({::))) {:: 5&({::)) 2
} ])^:(-.@:(_1"_ = 1&({::)))^:_)@:((0 ; (({. , ({: % 3:) , 3:)@:$ $ ,)@:(}."1
)@:(".;._2)@:(0&({::))) 9 0} ])@:(<@:('' ; 0"_) 5} ])@:(,&(;:',,,,,'))@:(,~)
)
|
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).
| #Forth | Forth |
: totient \ n -- n' ;
DUP DUP 2 ?DO ( tot n )
DUP I DUP * < IF LEAVE THEN \ for(i=2;i*i<=n;i+=2){
DUP I MOD 0= IF \ if(n%i==0){
BEGIN DUP I /MOD SWAP 0= WHILE ( tot n n/i ) \ while(n%i==0);
NIP ( tot n/i ) \ n/=i;
REPEAT
DROP ( tot n ) \ Remove the new n on exit from loop
SWAP DUP I / - SWAP ( tot' n ) \ tot-=tot/i;
THEN
2 I 2 = + +LOOP \ If I = 2 add 1 else add 2 to loop index.
DUP 1 > IF OVER SWAP / - ELSE DROP THEN ;
: bool. \ f -- ;
IF ." True " ELSE ." False" THEN ;
: count-primes \ n -- n' ;
0 SWAP 2 ?DO I DUP totient 1+ = - LOOP ;
: challenge \ -- ;
CR ." n φ prime" CR
26 1 DO
I 3 .r
I totient DUP 4 .r 4 SPACES
1+ I = bool. CR
LOOP CR
100001 100 DO
." Number of primes up to " I 6 .R ." is " I count-primes 4 .R CR
I 9 * +LOOP ;
|
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
| #Perl | Perl |
sub next_swop {
my( $max, $level, $p, $d ) = @_;
my $swopped = 0;
for( 2..@$p ){ # find possibilities
my @now = @$p;
if( $_ == $now[$_-1] ) {
splice @now, 0, 0, reverse splice @now, 0, $_;
$swopped = 1;
next_swop( $max, $level+1, \@now, [ @$d ] );
}
}
for( 1..@$d ) { # create possibilities
my @now = @$p;
my $next = shift @$d;
if( not $now[$next-1] ) {
$now[$next-1] = $next;
splice @now, 0, 0, reverse splice @now, 0, $next;
$swopped = 1;
next_swop( $max, $level+1, \@now, [ @$d ] );
}
push @$d, $next;
}
$$max = $level if !$swopped and $level > $$max;
}
sub topswops {
my $n = shift;
my @d = 2..$n;
my @p = ( 1, (0) x ($n-1) );
my $max = 0;
next_swop( \$max, 0, \@p, \@d );
return $max;
}
printf "Maximum swops for %2d cards: %2d\n", $_, topswops $_ for 1..10;
|
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #D | D | void main() {
import std.stdio, std.math;
enum degrees = 45.0L;
enum t0 = degrees * PI / 180.0L;
writeln("Reference: 0.7071067811865475244008");
writefln("Sine: %.20f %.20f", PI_4.sin, t0.sin);
writefln("Cosine: %.20f %.20f", PI_4.cos, t0.cos);
writefln("Tangent: %.20f %.20f", PI_4.tan, t0.tan);
writeln;
writeln("Reference: 0.7853981633974483096156");
immutable real t1 = PI_4.sin.asin;
writefln("Arcsine: %.20f %.20f", t1, t1 * 180.0L / PI);
immutable real t2 = PI_4.cos.acos;
writefln("Arccosine: %.20f %.20f", t2, t2 * 180.0L / PI);
immutable real t3 = PI_4.tan.atan;
writefln("Arctangent: %.20f %.20f", t3, t3 * 180.0L / PI);
} |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.
From the wikipedia entry:
ask for 11 numbers to be read into a sequence S
reverse sequence S
for each item in sequence S
result := call a function to do an operation
if result overflows
alert user
else
print result
The task is to implement the algorithm:
Use the function:
f
(
x
)
=
|
x
|
0.5
+
5
x
3
{\displaystyle f(x)=|x|^{0.5}+5x^{3}}
The overflow condition is an answer of greater than 400.
The 'user alert' should not stop processing of other items of the sequence.
Print a prompt before accepting eleven, textual, numeric inputs.
You may optionally print the item as well as its associated result, but the results must be in reverse order of input.
The sequence S may be 'implied' and so not shown explicitly.
Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
| #JavaScript | JavaScript | #!/usr/bin/env js
function main() {
var nums = getNumbers(11);
nums.reverse();
for (var i in nums) {
pardoKnuth(nums[i], fn, 400);
}
}
function pardoKnuth(n, f, max) {
var res = f(n);
putstr('f(' + String(n) + ')');
if (res > max) {
print(' is too large');
} else {
print(' = ' + String(res));
}
}
function fn(x) {
return Math.pow(Math.abs(x), 0.5) + 5 * Math.pow(x, 3);
}
function getNumbers(n) {
var nums = [];
print('Enter', n, 'numbers.');
for (var i = 1; i <= n; i++) {
putstr(' ' + i + ': ');
var num = readline();
nums.push(Number(num));
}
return nums;
}
main();
|
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.
| #Wren | Wren | import "/fmt" for Conv, Fmt
var predicates = [
Fn.new { |s| s.count == 13 }, // indexing starts at 0 but first bit ignored
Fn.new { |s| (7..12).count { |i| s[i] == "1" } == 3 },
Fn.new { |s| [2, 4, 6, 8, 10, 12].count { |i| s[i] == "1" } == 2 },
Fn.new { |s| s[5] == "0" || (s[6] == "1" && s[7] == "1") },
Fn.new { |s| s[2] == "0" && s[3] == "0" && s[4] == "0" },
Fn.new { |s| [1, 3, 5, 7, 9, 11].count { |i| s[i] == "1" } == 4 },
Fn.new { |s| Conv.itob(Conv.btoi(s[2] == "1") ^ Conv.btoi(s[3] == "1")) },
Fn.new { |s| s[7] == "0" || (s[5] == "1" && s[6] == "1") },
Fn.new { |s| (1..6).count { |i| s[i] == "1" } == 3 },
Fn.new { |s| s[11] == "1" && s[12] == "1" },
Fn.new { |s| (7..9).count { |i| s[i] == "1" } == 1 },
Fn.new { |s| (1..11).count { |i| s[i] == "1" } == 4 }
]
var show = Fn.new { |s, indent|
if (indent) System.write(" ")
for (i in 0...s.count) if (s[i] == "1") System.write("%(i) ")
System.print()
}
System.print("Exact hits:")
for (i in 0..4095) {
var s = Fmt.swrite("$013b", i)
var j = 1
if (predicates.all { |pred|
var res = pred.call(s) == (s[j] == "1")
j = j + 1
return res
}) show.call(s, true)
}
System.print("\nNear misses:")
for (i in 0..4095) {
var s = Fmt.swrite("$013b", i)
var j = 1
var c = predicates.count { |pred|
var res = pred.call(s) == (s[j] == "1")
j = j + 1
return res
}
if (c == 11) {
var k = 1
for (pred in predicates) {
if (pred.call(s) != (s[k] == "1") ) break
k = k + 1
}
Fmt.write(" (Fails at statement $2d) ", k)
show.call(s, false)
}
} |
http://rosettacode.org/wiki/Truth_table | Truth table | A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.
Task
Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function.
(One can assume that the user input is correct).
Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function.
Either reverse-polish or infix notation expressions are allowed.
Related tasks
Boolean values
Ternary logic
See also
Wolfram MathWorld entry on truth tables.
some "truth table" examples from Google.
| #Racket | Racket |
#lang racket
(define (collect-vars sexpr)
(sort
(remove-duplicates
(let loop ([x sexpr])
(cond [(boolean? x) '()]
[(symbol? x) (list x)]
[(list? x) (append-map loop (cdr x))]
[else (error 'truth-table "Bad expression: ~e" x)])))
string<? #:key symbol->string))
(define ns (make-base-namespace))
(define (truth-table sexpr)
(define vars (collect-vars sexpr))
(printf "~a => ~s\n" (string-join (map symbol->string vars)) sexpr)
(for ([i (expt 2 (length vars))])
(define vals
(map (λ(x) (eq? #\1 x))
(reverse (string->list (~r i #:min-width (length vars)
#:pad-string "0"
#:base 2)))))
(printf "~a => ~a\n" (string-join (map (λ(b) (if b "T" "F")) vals))
(if (eval `(let (,@(map list vars vals)) ,sexpr) ns) "T" "F"))))
(printf "Enter an expression: ")
(truth-table (read))
|
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
| #Ring | Ring |
# Project : Ulam spiral (for primes)
load "guilib.ring"
load "stdlib.ring"
paint = null
new qapp
{
win1 = new qwidget() {
setwindowtitle("Ulam spiral")
setgeometry(100,100,560,600)
label1 = new qlabel(win1) {
setgeometry(10,10,800,600)
settext("")
}
new qpushbutton(win1) {
setgeometry(220,500,100,30)
settext("draw")
setclickevent("draw()")
}
show()
}
exec()
}
func draw
p1 = new qpicture()
color = new qcolor() {
setrgb(0,0,255,255)
}
pen = new qpen() {
setcolor(color)
setwidth(1)
}
paint = new qpainter() {
begin(p1)
setpen(pen)
usn = 81
ulamspiral(usn)
endpaint()
}
label1 { setpicture(p1) show() }
return
func ulamspiral(nr)
button = list(nr)
win1{
sizenew = sqrt(nr)
for n = 1 to nr
col = n%9
if col = 0 col = 9 ok
row = ceil(n/9)
button[n] = new qpushbutton(win1)
{
setgeometry(60+col*40,60+row*40,40,40)
setclickevent("movetile(" + string(n) +")")
show()
}
next
n = 9
result = newlist(n,n)
k = 1
top = 1
bottom = n
left = 1
right = n
while (k<=n*n)
for i=left to right
result[top][i]=k
k = k + 1
next
top = top + 1
for i=top to bottom
result[i][right]=k
k = k + 1
next
right = right - 1
for i=right to left step -1
result[bottom][i]=k
k = k + 1
next
bottom = bottom - 1
for i=bottom to top step -1
result[i][left] = k
k = k + 1
next
left = left + 1
end
for m = 1 to n
for p = 1 to n
pos = (m-1)*n + p
if isprime(result[m][p])
button[pos] {settext(string(result[m][p]))}
ok
next
next
}
|
http://rosettacode.org/wiki/Truncatable_primes | Truncatable primes | A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.
Examples
The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.
The number 7393 is a right-truncatable prime as the numbers 7393, 739, 73, and 7 formed by removing digits from its right are also prime.
No zeroes are allowed in truncatable primes.
Task
The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied).
Related tasks
Find largest left truncatable prime in a given base
Sieve of Eratosthenes
See also
Truncatable Prime from MathWorld.]
| #Lua | Lua | max_number = 1000000
numbers = {}
for i = 2, max_number do
numbers[i] = i;
end
for i = 2, max_number do
for j = i+1, max_number do
if numbers[j] ~= 0 and j % i == 0 then numbers[j] = 0 end
end
end
max_prime_left, max_prime_right = 2, 2
for i = 2, max_number do
if numbers[i] ~= 0 then
local is_prime = true
local l = math.floor( i / 10 )
while l > 1 do
if numbers[l] == 0 then
is_prime = false
break
end
l = math.floor( l / 10 )
end
if is_prime then
max_prime_left = i
end
is_prime = true
local n = 10;
while math.floor( i % 10 ) ~= 0 and n < max_number do
if numbers[ math.floor( i % 10 ) ] ~= 0 then
is_prime = false
break
end
n = n * 10
end
if is_prime then
max_prime_right = i
end
end
end
print( "max_prime_left = ", max_prime_left )
print( "max_prime_right = ", max_prime_right ) |
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.
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
class Node
{
int Value;
Node Left;
Node Right;
Node(int value = default(int), Node left = default(Node), Node right = default(Node))
{
Value = value;
Left = left;
Right = right;
}
IEnumerable<int> Preorder()
{
yield return Value;
if (Left != null)
foreach (var value in Left.Preorder())
yield return value;
if (Right != null)
foreach (var value in Right.Preorder())
yield return value;
}
IEnumerable<int> Inorder()
{
if (Left != null)
foreach (var value in Left.Inorder())
yield return value;
yield return Value;
if (Right != null)
foreach (var value in Right.Inorder())
yield return value;
}
IEnumerable<int> Postorder()
{
if (Left != null)
foreach (var value in Left.Postorder())
yield return value;
if (Right != null)
foreach (var value in Right.Postorder())
yield return value;
yield return Value;
}
IEnumerable<int> LevelOrder()
{
var queue = new Queue<Node>();
queue.Enqueue(this);
while (queue.Any())
{
var node = queue.Dequeue();
yield return node.Value;
if (node.Left != null)
queue.Enqueue(node.Left);
if (node.Right != null)
queue.Enqueue(node.Right);
}
}
static void Main()
{
var tree = new Node(1, new Node(2, new Node(4, new Node(7)), new Node(5)), new Node(3, new Node(6, new Node(8), new Node(9))));
foreach (var traversal in new Func<IEnumerable<int>>[] { tree.Preorder, tree.Inorder, tree.Postorder, tree.LevelOrder })
Console.WriteLine("{0}:\t{1}", traversal.Method.Name, string.Join(" ", traversal()));
}
} |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ada | Ada | with Ada.Text_IO, Ada.Containers.Indefinite_Vectors, Ada.Strings.Fixed, Ada.Strings.Maps;
use Ada.Text_IO, Ada.Containers, Ada.Strings, Ada.Strings.Fixed, Ada.Strings.Maps;
procedure Tokenize is
package String_Vectors is new Indefinite_Vectors (Positive, String);
use String_Vectors;
Input : String := "Hello,How,Are,You,Today";
Start : Positive := Input'First;
Finish : Natural := 0;
Output : Vector := Empty_Vector;
begin
while Start <= Input'Last loop
Find_Token (Input, To_Set (','), Start, Outside, Start, Finish);
exit when Start > Finish;
Output.Append (Input (Start .. Finish));
Start := Finish + 1;
end loop;
for S of Output loop
Put (S & ".");
end loop;
end Tokenize; |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
Find the top N salaries in each department, where N is provided as a parameter.
Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:
Employee Name,Employee ID,Salary,Department
Tyler Bennett,E10297,32000,D101
John Rappl,E21437,47000,D050
George Woltman,E00127,53500,D101
Adam Smith,E63535,18000,D202
Claire Buckman,E39876,27800,D202
David McClellan,E04242,41500,D101
Rich Holcomb,E01234,49500,D202
Nathan Adams,E41298,21900,D050
Richard Potter,E43128,15900,D101
David Motsinger,E27002,19250,D202
Tim Sampair,E03033,27000,D101
Kim Arlich,E10001,57000,D190
Timothy Grove,E16398,29900,D190
| #AWK | AWK |
# syntax: GAWK -f TOP_RANK_PER_GROUP.AWK [n]
#
# sorting:
# PROCINFO["sorted_in"] is used by GAWK
# SORTTYPE is used by Thompson Automation's TAWK
#
BEGIN {
arrA[++n] = "Employee Name,Employee ID,Salary,Department" # raw data
arrA[++n] = "Tyler Bennett,E10297,32000,D101"
arrA[++n] = "John Rappl,E21437,47000,D050"
arrA[++n] = "George Woltman,E00127,53500,D101"
arrA[++n] = "Adam Smith,E63535,18000,D202"
arrA[++n] = "Claire Buckman,E39876,27800,D202"
arrA[++n] = "David McClellan,E04242,41500,D101"
arrA[++n] = "Rich Holcomb,E01234,49500,D202"
arrA[++n] = "Nathan Adams,E41298,21900,D050"
arrA[++n] = "Richard Potter,E43128,15900,D101"
arrA[++n] = "David Motsinger,E27002,19250,D202"
arrA[++n] = "Tim Sampair,E03033,27000,D101"
arrA[++n] = "Kim Arlich,E10001,57000,D190"
arrA[++n] = "Timothy Grove,E16398,29900,D190"
for (i=2; i<=n; i++) { # build internal structure
split(arrA[i],arrB,",")
arrC[arrB[4]][arrB[3]][arrB[2] " " arrB[1]] # I.E. arrC[dept][salary][id " " name]
}
show = (ARGV[1] == "") ? 1 : ARGV[1] # employees to show per department
printf("DEPT SALARY EMPID NAME\n\n") # produce report
PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1
for (i in arrC) {
PROCINFO["sorted_in"] = "@ind_str_desc" ; SORTTYPE = 9
shown = 0
for (j in arrC[i]) {
PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1
for (k in arrC[i][j]) {
if (shown++ < show) {
printf("%-4s %6s %s\n",i,j,k)
printed++
}
}
}
if (printed > 0) { print("") }
printed = 0
}
exit(0)
}
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #APL | APL | hanoi←{
move←{
n from to via←⍵
n≤0:⍬
l←∇(n-1) from via to
r←∇(n-1) via to from
l,(⊂from to),r
}
'⊂Move disk from pole ⊃,I1,⊂ to pole ⊃,I1'⎕FMT↑move ⍵
} |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #C.23 | C# | using System;
using System.Text;
namespace ThueMorse
{
class Program
{
static void Main(string[] args)
{
Sequence(6);
}
public static void Sequence(int steps)
{
var sb1 = new StringBuilder("0");
var sb2 = new StringBuilder("1");
for (int i = 0; i < steps; i++)
{
var tmp = sb1.ToString();
sb1.Append(sb2);
sb2.Append(tmp);
}
Console.WriteLine(sb1);
Console.ReadLine();
}
}
} |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #C.2B.2B | C++ |
#include <iostream>
#include <iterator>
#include <vector>
int main( int argc, char* argv[] ) {
std::vector<bool> t;
t.push_back( 0 );
size_t len = 1;
std::cout << t[0] << "\n";
do {
for( size_t x = 0; x < len; x++ )
t.push_back( t[x] ? 0 : 1 );
std::copy( t.begin(), t.end(), std::ostream_iterator<bool>( std::cout ) );
std::cout << "\n";
len = t.size();
} while( len < 60 );
return 0;
}
|
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm | Tonelli-Shanks algorithm |
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computational number theory, the Tonelli–Shanks algorithm is a technique for solving for x in a congruence of the form:
x2 ≡ n (mod p)
where n is an integer which is a quadratic residue (mod p), p is an odd prime, and x,n ∈ Fp where Fp = {0, 1, ..., p - 1}.
It is used in cryptography techniques.
To apply the algorithm, we need the Legendre symbol:
The Legendre symbol (a | p) denotes the value of a(p-1)/2 (mod p).
(a | p) ≡ 1 if a is a square (mod p)
(a | p) ≡ -1 if a is not a square (mod p)
(a | p) ≡ 0 if a ≡ 0 (mod p)
Algorithm pseudo-code
All ≡ are taken to mean (mod p) unless stated otherwise.
Input: p an odd prime, and an integer n .
Step 0: Check that n is indeed a square: (n | p) must be ≡ 1 .
Step 1: By factoring out powers of 2 from p - 1, find q and s such that p - 1 = q2s with q odd .
If p ≡ 3 (mod 4) (i.e. s = 1), output the two solutions r ≡ ± n(p+1)/4 .
Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq .
Step 3: Set r ≡ n(q+1)/2, t ≡ nq, m = s .
Step 4: Loop the following:
If t ≡ 1, output r and p - r .
Otherwise find, by repeated squaring, the lowest i, 0 < i < m , such that t2i ≡ 1 .
Let b ≡ c2(m - i - 1), and set r ≡ rb, t ≡ tb2, c ≡ b2 and m = i .
Task
Implement the above algorithm.
Find solutions (if any) for
n = 10 p = 13
n = 56 p = 101
n = 1030 p = 10009
n = 1032 p = 10009
n = 44402 p = 100049
Extra credit
n = 665820697 p = 1000000009
n = 881398088036 p = 1000000000039
n = 41660815127637347468140745042827704103445750172002 p = 10^50 + 577
See also
Modular exponentiation
Cipolla's algorithm
| #Haskell | Haskell | import Data.List (genericTake, genericLength)
import Data.Bits (shiftR)
powMod :: Integer -> Integer -> Integer -> Integer
powMod m b e = go b e 1
where
go b e r
| e == 0 = r
| odd e = go ((b*b) `mod` m) (e `div` 2) ((r*b) `mod` m)
| even e = go ((b*b) `mod` m) (e `div` 2) r
legendre :: Integer -> Integer -> Integer
legendre a p = powMod p a ((p - 1) `div` 2)
tonelli :: Integer -> Integer -> Maybe (Integer, Integer)
tonelli n p | legendre n p /= 1 = Nothing
tonelli n p =
let s = length $ takeWhile even $ iterate (`div` 2) (p-1)
q = shiftR (p-1) s
in if s == 1
then let r = powMod p n ((p+1) `div` 4)
in Just (r, p - r)
else let z = (2 +) . genericLength
$ takeWhile (\i -> p - 1 /= legendre i p)
$ [2..p-1]
in loop s
( powMod p z q )
( powMod p n $ (q+1) `div` 2 )
( powMod p n q )
where
loop m c r t
| (t - 1) `mod` p == 0 = Just (r, p - r)
| otherwise =
let i = (1 +) . genericLength . genericTake (m - 2)
$ takeWhile (\t2 -> (t2 - 1) `mod` p /= 0)
$ iterate (\t2 -> (t2*t2) `mod` p)
$ (t*t) `mod` p
b = powMod p c (2^(m - i - 1))
r' = (r*b) `mod` p
c' = (b*b) `mod` p
t' = (t*c') `mod` p
in loop i c' r' t' |
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
| #Common_Lisp | Common Lisp | (defun split (input separator escape)
(flet ((make-string-buffer ()
(make-array 0 :element-type 'character :adjustable t :fill-pointer t)))
(loop with token = (make-string-buffer)
with result = nil
with to-be-escaped = nil
for ch across input
do (cond (to-be-escaped
(vector-push-extend ch token)
(setf to-be-escaped nil))
((char= ch escape)
(setf to-be-escaped t))
((char= ch separator)
(push token result)
(setf token (make-string-buffer)))
(t
(vector-push-extend ch token)))
finally (push token result)
(return (nreverse result)))))
(defun main ()
(dolist (token (split "one^|uno||three^^^^|four^^^|^cuatro|" #\| #\^))
(format t "'~A'~%" token))) |
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
| #Nim | Nim | import sequtils
type Circle = tuple[x, y, r: float]
const circles: seq[Circle] = @[
( 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)]
template sqr(x: SomeNumber): SomeNumber = x * x
let xMin = min circles.mapIt(it.x - it.r)
let xMax = max circles.mapIt(it.x + it.r)
let yMin = min circles.mapIt(it.y - it.r)
let yMax = max circles.mapIt(it.y + it.r)
const boxSide = 500
let dx = (xMax - xMin) / boxSide
let dy = (yMax - yMin) / boxSide
var count = 0
for r in 0 ..< boxSide:
let y = yMin + float(r) * dy
for c in 0 ..< boxSide:
let x = xMin + float(c) * dx
for circle in circles:
if sqr(x - circle.x) + sqr(y - circle.y) <= sqr(circle.r):
inc count
break
echo "Approximated area: ", float(count) * dx * dy |
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
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use List::AllUtils <min max>;
my @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],
);
my $x_min = min map { $_->[0] - $_->[2] } @circles;
my $x_max = max map { $_->[0] + $_->[2] } @circles;
my $y_min = min map { $_->[1] - $_->[2] } @circles;
my $y_max = max map { $_->[1] + $_->[2] } @circles;
my $box_side = 500;
my $dx = ($x_max - $x_min) / $box_side;
my $dy = ($y_max - $y_min) / $box_side;
my $count = 0;
for my $r (0..$box_side) {
my $y = $y_min + $r * $dy;
for my $c (0..$box_side) {
my $x = $x_min + $c * $dx;
for my $c (@circles) {
$count++ and last if ($x - $$c[0])**2 + ($y - $$c[1])**2 <= $$c[2]**2
}
}
}
printf "Approximated area: %.9f\n", $count * $dx * $dy; |
http://rosettacode.org/wiki/Topological_sort | Topological sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon.
The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on.
A tool exists that extracts library dependencies.
Task
Write a function that will return a valid compile order of VHDL libraries from their dependencies.
Assume library names are single words.
Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given.
Any self dependencies should be ignored.
Any un-orderable dependencies should be flagged.
Use the following data as an example:
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys
Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01.
C.f.
Topological sort/Extracted top item.
There are two popular algorithms for topological sorting:
Kahn's 1962 topological sort [1]
depth-first search [2] [3]
| #D | D | import std.stdio, std.string, std.algorithm, std.range;
final class ArgumentException : Exception {
this(string text) pure nothrow @safe /*@nogc*/ {
super(text);
}
}
alias TDependencies = string[][string];
string[][] topoSort(TDependencies d) pure /*nothrow @safe*/ {
foreach (immutable k, v; d)
d[k] = v.sort().uniq.filter!(s => s != k).array;
foreach (immutable s; d.byValue.join.sort().uniq)
if (s !in d)
d[s] = [];
string[][] sorted;
while (true) {
string[] ordered;
foreach (immutable item, const dep; d)
if (dep.empty)
ordered ~= item;
if (!ordered.empty)
sorted ~= ordered.sort().release;
else
break;
TDependencies dd;
foreach (immutable item, const dep; d)
if (!ordered.canFind(item))
dd[item] = dep.dup.filter!(s => !ordered.canFind(s)).array;
d = dd;
}
//if (!d.empty)
if (d.length > 0)
throw new ArgumentException(format(
"A cyclic dependency exists amongst:\n%s", d));
return sorted;
}
void main() {
immutable data =
"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";
TDependencies deps;
foreach (immutable line; data.splitLines)
deps[line.split[0]] = line.split[1 .. $];
auto depw = deps.dup;
foreach (immutable idx, const subOrder; depw.topoSort)
writefln("#%d : %s", idx + 1, subOrder);
writeln;
depw = deps.dup;
depw["dw01"] ~= "dw04";
foreach (const subOrder; depw.topoSort) // Should throw.
subOrder.writeln;
} |
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.
| #Java | Java | import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.List;
import java.util.Set;
import java.util.Map;
public class UTM {
private List<String> tape;
private String blankSymbol;
private ListIterator<String> head;
private Map<StateTapeSymbolPair, Transition> transitions = new HashMap<StateTapeSymbolPair, Transition>();
private Set<String> terminalStates;
private String initialState;
public UTM(Set<Transition> transitions, Set<String> terminalStates, String initialState, String blankSymbol) {
this.blankSymbol = blankSymbol;
for (Transition t : transitions) {
this.transitions.put(t.from, t);
}
this.terminalStates = terminalStates;
this.initialState = initialState;
}
public static class StateTapeSymbolPair {
private String state;
private String tapeSymbol;
public StateTapeSymbolPair(String state, String tapeSymbol) {
this.state = state;
this.tapeSymbol = tapeSymbol;
}
// These methods can be auto-generated by Eclipse.
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((state == null) ? 0 : state.hashCode());
result = prime
* result
+ ((tapeSymbol == null) ? 0 : tapeSymbol
.hashCode());
return result;
}
// These methods can be auto-generated by Eclipse.
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StateTapeSymbolPair other = (StateTapeSymbolPair) obj;
if (state == null) {
if (other.state != null)
return false;
} else if (!state.equals(other.state))
return false;
if (tapeSymbol == null) {
if (other.tapeSymbol != null)
return false;
} else if (!tapeSymbol.equals(other.tapeSymbol))
return false;
return true;
}
@Override
public String toString() {
return "(" + state + "," + tapeSymbol + ")";
}
}
public static class Transition {
private StateTapeSymbolPair from;
private StateTapeSymbolPair to;
private int direction; // -1 left, 0 neutral, 1 right.
public Transition(StateTapeSymbolPair from, StateTapeSymbolPair to, int direction) {
this.from = from;
this.to = to;
this.direction = direction;
}
@Override
public String toString() {
return from + "=>" + to + "/" + direction;
}
}
public void initializeTape(List<String> input) { // Arbitrary Strings as symbols.
tape = input;
}
public void initializeTape(String input) { // Uses single characters as symbols.
tape = new LinkedList<String>();
for (int i = 0; i < input.length(); i++) {
tape.add(input.charAt(i) + "");
}
}
public List<String> runTM() { // Returns null if not in terminal state.
if (tape.size() == 0) {
tape.add(blankSymbol);
}
head = tape.listIterator();
head.next();
head.previous();
StateTapeSymbolPair tsp = new StateTapeSymbolPair(initialState, tape.get(0));
while (transitions.containsKey(tsp)) { // While a matching transition exists.
System.out.println(this + " --- " + transitions.get(tsp));
Transition trans = transitions.get(tsp);
head.set(trans.to.tapeSymbol); // Write tape symbol.
tsp.state = trans.to.state; // Change state.
if (trans.direction == -1) { // Go left.
if (!head.hasPrevious()) {
head.add(blankSymbol); // Extend tape.
}
tsp.tapeSymbol = head.previous(); // Memorize tape symbol.
} else if (trans.direction == 1) { // Go right.
head.next();
if (!head.hasNext()) {
head.add(blankSymbol); // Extend tape.
head.previous();
}
tsp.tapeSymbol = head.next(); // Memorize tape symbol.
head.previous();
} else {
tsp.tapeSymbol = trans.to.tapeSymbol;
}
}
System.out.println(this + " --- " + tsp);
if (terminalStates.contains(tsp.state)) {
return tape;
} else {
return null;
}
}
@Override
public String toString() {
try {
int headPos = head.previousIndex();
String s = "[ ";
for (int i = 0; i <= headPos; i++) {
s += tape.get(i) + " ";
}
s += "[H] ";
for (int i = headPos + 1; i < tape.size(); i++) {
s += tape.get(i) + " ";
}
return s + "]";
} catch (Exception e) {
return "";
}
}
public static void main(String[] args) {
// Simple incrementer.
String init = "q0";
String blank = "b";
Set<String> term = new HashSet<String>();
term.add("qf");
Set<Transition> trans = new HashSet<Transition>();
trans.add(new Transition(new StateTapeSymbolPair("q0", "1"), new StateTapeSymbolPair("q0", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("q0", "b"), new StateTapeSymbolPair("qf", "1"), 0));
UTM machine = new UTM(trans, term, init, blank);
machine.initializeTape("111");
System.out.println("Output (si): " + machine.runTM() + "\n");
// Busy Beaver (overwrite variables from above).
init = "a";
term.clear();
term.add("halt");
blank = "0";
trans.clear();
// Change state from "a" to "b" if "0" is read on tape, write "1" and go to the right. (-1 left, 0 nothing, 1 right.)
trans.add(new Transition(new StateTapeSymbolPair("a", "0"), new StateTapeSymbolPair("b", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("a", "1"), new StateTapeSymbolPair("c", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("b", "0"), new StateTapeSymbolPair("a", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("b", "1"), new StateTapeSymbolPair("b", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("c", "0"), new StateTapeSymbolPair("b", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("c", "1"), new StateTapeSymbolPair("halt", "1"), 0));
machine = new UTM(trans, term, init, blank);
machine.initializeTape("");
System.out.println("Output (bb): " + machine.runTM());
// Sorting test (overwrite variables from above).
init = "s0";
blank = "*";
term = new HashSet<String>();
term.add("see");
trans = new HashSet<Transition>();
trans.add(new Transition(new StateTapeSymbolPair("s0", "a"), new StateTapeSymbolPair("s0", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s0", "b"), new StateTapeSymbolPair("s1", "B"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s0", "*"), new StateTapeSymbolPair("se", "*"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "a"), new StateTapeSymbolPair("s1", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "b"), new StateTapeSymbolPair("s1", "b"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "*"), new StateTapeSymbolPair("s2", "*"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "a"), new StateTapeSymbolPair("s3", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "b"), new StateTapeSymbolPair("s2", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "B"), new StateTapeSymbolPair("se", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "a"), new StateTapeSymbolPair("s3", "a"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "b"), new StateTapeSymbolPair("s3", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "B"), new StateTapeSymbolPair("s0", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("se", "a"), new StateTapeSymbolPair("se", "a"), -1));
trans.add(new Transition(new StateTapeSymbolPair("se", "*"), new StateTapeSymbolPair("see", "*"), 1));
machine = new UTM(trans, term, init, blank);
machine.initializeTape("babbababaa");
System.out.println("Output (sort): " + machine.runTM() + "\n");
}
} |
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).
| #Go | Go | package main
import "fmt"
func gcd(n, k int) int {
if n < k || k < 1 {
panic("Need n >= k and k >= 1")
}
s := 1
for n&1 == 0 && k&1 == 0 {
n >>= 1
k >>= 1
s <<= 1
}
t := n
if n&1 != 0 {
t = -k
}
for t != 0 {
for t&1 == 0 {
t >>= 1
}
if t > 0 {
n = t
} else {
k = -t
}
t = n - k
}
return n * s
}
func totient(n int) int {
tot := 0
for k := 1; k <= n; k++ {
if gcd(n, k) == 1 {
tot++
}
}
return tot
}
func main() {
fmt.Println(" n phi prime")
fmt.Println("---------------")
count := 0
for n := 1; n <= 25; n++ {
tot := totient(n)
isPrime := n-1 == tot
if isPrime {
count++
}
fmt.Printf("%2d %2d %t\n", n, tot, isPrime)
}
fmt.Println("\nNumber of primes up to 25 =", count)
for n := 26; n <= 100000; n++ {
tot := totient(n)
if tot == n-1 {
count++
}
if n == 100 || n == 1000 || n%10000 == 0 {
fmt.Printf("\nNumber of primes up to %-6d = %d\n", n, count)
}
}
} |
http://rosettacode.org/wiki/Topswops | Topswops | Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is composed of reversing the first m cards where m is the value of the topmost card.
Rounds are repeated until the topmost card is the number 1 and the number of swaps is recorded.
For our example the swaps produce:
[2, 4, 1, 3] # Initial shuffle
[4, 2, 1, 3]
[3, 1, 2, 4]
[2, 1, 3, 4]
[1, 2, 3, 4]
For a total of four swaps from the initial ordering to produce the terminating case where 1 is on top.
For a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards.
Task
The task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive.
Note
Topswops is also known as Fannkuch from the German word Pfannkuchen meaning pancake.
Related tasks
Number reversal game
Sorting algorithms/Pancake sort
| #Phix | Phix | with javascript_semantics
function fannkuch(integer n)
sequence count = tagset(n),
perm1 = tagset(n)
integer maxFlipsCount = 0, r = n+1
while true do
while r!=1 do
count[r-1] = r
r -= 1
end while
if not (perm1[1]=1 or perm1[n]=n) then
sequence perm = perm1
integer flipsCount = 0,
k = perm[1]
while k!=1 do
perm = reverse(perm[1..k]) & perm[k+1..n]
flipsCount += 1
k = perm[1]
end while
if flipsCount>maxFlipsCount then
maxFlipsCount = flipsCount
end if
end if
-- Use incremental change to generate another permutation
while true do
if r>n then return maxFlipsCount end if
integer perm0 = perm1[1]
perm1[1..r-1] = perm1[2..r]
perm1[r] = perm0
count[r] -= 1
if count[r]>1 then exit end if
r += 1
end while
end while
end function -- fannkuch
atom t0 = time()
for i=1 to iff(platform()=JS?9:10) do
?fannkuch(i)
end for
?elapsed(time()-t0)
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.