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/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.]
| #PicoLisp | PicoLisp | (load "@lib/rsa.l") # Use the 'prime?' function from RSA package
(de truncatablePrime? (N Fun)
(for (L (chop N) L (Fun L))
(T (= "0" (car L)))
(NIL (prime? (format L)))
T ) )
(let (Left 1000000 Right 1000000)
(until (truncatablePrime? (dec 'Left) cdr))
(until (truncatablePrime? (dec 'Right) '((L) (cdr (rot L)))))
(cons Left Right) ) |
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.]
| #Pike | Pike | bool is_trunc_prime(int p, string direction)
{
while(p) {
if( !p->probably_prime_p() )
return false;
if(direction == "l")
p = (int)p->digits()[1..];
else
p = (int)p->digits()[..<1];
}
return true;
}
void main()
{
bool ltp_found, rtp_found;
for(int prime = 10->pow(6); prime--; prime > 0) {
if( !ltp_found && is_trunc_prime(prime, "l") ) {
ltp_found = true;
write("Largest LTP: %d\n", prime);
}
if( !rtp_found && is_trunc_prime(prime, "r") ) {
rtp_found = true;
write("Largest RTP: %d\n", prime);
}
if(ltp_found && rtp_found)
break;
}
} |
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.
| #D | D | import std.stdio, std.traits;
const final class Node(T) {
T data;
Node left, right;
this(in T data, in Node left=null, in Node right=null)
const pure nothrow {
this.data = data;
this.left = left;
this.right = right;
}
}
// 'static' templated opCall can't be used in Node
auto node(T)(in T data, in Node!T left=null, in Node!T right=null)
pure nothrow {
return new const(Node!T)(data, left, right);
}
void show(T)(in T x) {
write(x, " ");
}
enum Visit { pre, inv, post }
// 'visitor' can be any kind of callable or it uses a default visitor.
// TNode can be any kind of Node, with data, left and right fields,
// so this is more generic than a member function of Node.
void backtrackingOrder(Visit v, TNode, TyF=void*)
(in TNode node, TyF visitor=null) {
alias trueVisitor = Select!(is(TyF == void*), show, visitor);
if (node !is null) {
static if (v == Visit.pre)
trueVisitor(node.data);
backtrackingOrder!v(node.left, visitor);
static if (v == Visit.inv)
trueVisitor(node.data);
backtrackingOrder!v(node.right, visitor);
static if (v == Visit.post)
trueVisitor(node.data);
}
}
void levelOrder(TNode, TyF=void*)
(in TNode node, TyF visitor=null, const(TNode)[] more=[]) {
alias trueVisitor = Select!(is(TyF == void*), show, visitor);
if (node !is null) {
more ~= [node.left, node.right];
trueVisitor(node.data);
}
if (more.length)
levelOrder(more[0], visitor, more[1 .. $]);
}
void main() {
alias N = node;
const tree = N(1,
N(2,
N(4,
N(7)),
N(5)),
N(3,
N(6,
N(8),
N(9))));
write(" preOrder: ");
tree.backtrackingOrder!(Visit.pre);
write("\n inorder: ");
tree.backtrackingOrder!(Visit.inv);
write("\n postOrder: ");
tree.backtrackingOrder!(Visit.post);
write("\nlevelorder: ");
tree.levelOrder;
writeln;
} |
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
| #C.23 | C# | string str = "Hello,How,Are,You,Today";
// or Regex.Split ( "Hello,How,Are,You,Today", "," );
// (Regex is in System.Text.RegularExpressions namespace)
string[] strings = str.Split(',');
Console.WriteLine(String.Join(".", strings));
|
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
| #C.2B.2B | C++ | #include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>
int main()
{
std::string s = "Hello,How,Are,You,Today";
std::vector<std::string> v;
std::istringstream buf(s);
for(std::string token; getline(buf, token, ','); )
v.push_back(token);
copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, "."));
std::cout << '\n';
} |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #BBC_BASIC | BBC BASIC | start%=TIME:REM centi-second timer
REM perform processing
lapsed%=TIME-start% |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Bracmat | Bracmat | ( ( time
= fun funarg t0 ret
. !arg:(?fun.?funarg)
& clk$:?t0
& !fun$!funarg:?ret
& (!ret.flt$(clk$+-1*!t0,3) s)
)
& ( fib
=
. !arg:<2&1
| fib$(!arg+-1)+fib$(!arg+-2)
)
& time$(fib.30)
) |
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
| #Dyalect | Dyalect | type Employee(name,id,salary,department) with Lookup
func Employee.ToString() {
"$\(this.salary) (name: \(this.name), id: \(this.id), department: \(this.department)"
}
let employees = [
Employee("Tyler Bennett","E10297",32000,"D101"),
Employee("John Rappl","E21437",47000,"D050"),
Employee("George Woltman","E00127",53500,"D101"),
Employee("Adam Smith","E63535",18000,"D202"),
Employee("Claire Buckman","E39876",27800,"D202"),
Employee("David McClellan","E04242",41500,"D101"),
Employee("Rich Holcomb","E01234",49500,"D202"),
Employee("Nathan Adams","E41298",21900,"D050"),
Employee("Richard Potter","E43128",15900,"D101"),
Employee("David Motsinger","E27002",19250,"D202"),
Employee("Tim Sampair","E03033",27000,"D101"),
Employee("Kim Arlich","E10001",57000,"D190"),
Employee("Timothy Grove","E16398",29900,"D190")
]
func topNSalaries(n) {
//We sort employees based on salary
employees.Sort((x,y) => y.salary - x.salary)
let max =
if n > employees.Length() - 1 {
employees.Length() - 1
} else {
n
}
for i in 0..max {
yield employees[i]
}
}
var seq = topNSalaries(5)
for e in seq {
print(e)
} |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #BASIC | BASIC |
# basado en código de Antonio Rodrigo dos Santos Silva (gracias):
# http://statusgear.freeforums.net/thread/17/basic-256-tic-tac-toe
global playerturn$
global endGame$
global space$
global player1Score$
global player2Score$
global invalidMove$
global tecla$
global keyQ$
global keyW$
global keyE$
global keyA$
global keyS$
global keyD$
global keyZ$
global keyX$
global keyC$
global keySpace$
global keyEsc$
keyQ$ = 81
keyW$ = 87
keyE$ = 69
keyA$ = 65
keyS$ = 83
keyD$ = 68
keyZ$ = 90
keyX$ = 88
keyC$ = 67
keySpace$ = 32
keyEsc$ = 16777216
dim space$(9)
subroutine clearGameVars()
playerturn$ = 1
invalidMove$ = 0
endGame$ = 0
tecla$ = 0
for t = 0 to space$[?]-1
space$[t] = 0
next t
end subroutine
subroutine endGame()
cls
print "¡Hasta pronto!..."
end
end subroutine
subroutine printBoard()
print " " + space$[0]+" | "+space$[1]+" | "+space$[2]
print " " + "— + — + —"
print " " + space$[3]+" | "+space$[4]+" | "+space$[5]
print " " + "— + — + —"
print " " + space$[6]+" | "+space$[7]+" | "+space$[8]
print ""
end subroutine
subroutine changePlayer()
if playerturn$ = 1 then
playerturn$ = 2
else
playerturn$ = 1
end if
end subroutine
subroutine endMatchWithWinner()
cls
call printPlayerScore()
call printBoard()
endGame$ = 1
if playerturn$ = 1 then
player1Score$ += 1
else
player2Score$ += 1
end if
print "¡Jugador " + playerturn$ + " gana!" + chr(10)
print "Pulsa [SPACE] para jugar otra partida"
print "Pulsa [ESC] para dejar de jugar"
do
tecla$ = key
pause .01
if tecla$ = keySpace$ then call gamePlay()
if tecla$ = keyEsc$ then call endGame()
until false
end subroutine
subroutine endMatchWithoutWinner()
cls
call printPlayerScore()
call printBoard()
endGame$ = 1
print " Nadie ganó :( " + chr(10)
print " Pulsa [SPACE] para comenzar o [ESC] para salir. "
do
tecla$ = key
pause .01
if tecla$ = keySpace$ then call gamePlay()
if tecla$ = keyEsc$ then call endGame()
until false
end subroutine
subroutine printPlayerScore()
print "--------------------------------------------"
print " Jugador #1: " + player1Score$ + " pts"
print " Jugador #2: " + player2Score$ + " pts"
print "--------------------------------------------" + chr(10)
end subroutine
subroutine printPlayerMessage()
print "Jugador: " + playerturn$ + ", elige una casilla, por favor."
end subroutine
subroutine gamePlay()
call clearGameVars()
cls
call printPlayerScore()
call printBoard()
call printPlayerMessage()
while 0 = 0
invalidMove$ = 0
if endGame$ = 0 then
do
tecla$ = key
pause .01
validKeypressed$ = 0
if tecla$ = keyQ$ or tecla$ = keyW$ or tecla$ = keyE$ or tecla$ = keyA$ or tecla$ = keyS$ or tecla$ = keyD$ or tecla$ = keyZ$ or tecla$ = keyX$ or tecla$ = keyC$ then validKeypressed$ = 1
until validKeypressed$ = 1
endif
if tecla$ = keyQ$ then
if space$[0] = 0 then
space$[0] = playerturn$
else
invalidMove$ = 1
endif
endif
if tecla$ = keyW$ then
if space$[1] = 0 then
space$[1] = playerturn$
else
invalidMove$ = 1
endif
endif
if tecla$ = keyE$ then
if space$[2] = 0 then
space$[2] = playerturn$
else
invalidMove$ = 1
endif
endif
if tecla$ = keyA$ then
if space$[3] = 0 then
space$[3] = playerturn$
else
invalidMove$ = 1
endif
endif
if tecla$ = keyS$ then
if space$[4] = 0 then
space$[4] = playerturn$
else
invalidMove$ = 1
endif
endif
if tecla$ = keyD$ then
if space$[5] = 0 then
space$[5] = playerturn$
else
invalidMove$ = 1
endif
endif
if tecla$ = keyZ$ then
if space$[6] = 0 then
space$[6] = playerturn$
else
invalidMove$ = 1
endif
endif
if tecla$ = keyX$ then
if space$[7] = 0 then
space$[7] = playerturn$
else
invalidMove$ = 1
endif
endif
if tecla$ = keyC$ then
if space$[8] = 0 then
space$[8] = playerturn$
else
invalidMove$ = 1
endif
endif
if invalidMove$ = 0 then
tecla$ = 0
if space$[0] = 1 and space$[1] = 1 and space$[2] = 1 then call endMatchWithWinner()
if space$[3] = 1 and space$[4] = 1 and space$[5] = 1 then call endMatchWithWinner()
if space$[6] = 1 and space$[7] = 1 and space$[8] = 1 then call endMatchWithWinner()
if space$[0] = 1 and space$[3] = 1 and space$[6] = 1 then call endMatchWithWinner()
if space$[1] = 1 and space$[4] = 1 and space$[7] = 1 then call endMatchWithWinner()
if space$[2] = 1 and space$[5] = 1 and space$[8] = 1 then call endMatchWithWinner()
if space$[0] = 1 and space$[4] = 1 and space$[8] = 1 then call endMatchWithWinner()
if space$[2] = 1 and space$[4] = 1 and space$[6] = 1 then call endMatchWithWinner()
if space$[0] = 2 and space$[1] = 2 and space$[2] = 2 then call endMatchWithWinner()
if space$[3] = 2 and space$[4] = 2 and space$[5] = 2 then call endMatchWithWinner()
if space$[6] = 2 and space$[7] = 2 and space$[8] = 2 then call endMatchWithWinner()
if space$[0] = 2 and space$[3] = 2 and space$[6] = 2 then call endMatchWithWinner()
if space$[1] = 2 and space$[4] = 2 and space$[7] = 2 then call endMatchWithWinner()
if space$[2] = 2 and space$[5] = 2 and space$[8] = 2 then call endMatchWithWinner()
if space$[0] = 2 and space$[4] = 2 and space$[8] = 2 then call endMatchWithWinner()
if space$[2] = 2 and space$[4] = 2 and space$[6] = 2 then call endMatchWithWinner()
if space$[0] <> 0 and space$[1] <> 0 and space$[2] <> 0 and space$[3] <> 0 and space$[4] <> 0 and space$[5] <> 0 and space$[6] <> 0 and space$[7] <> 0 and space$[8] <> 0 then call endMatchWithoutWinner()
call changePlayer()
cls
call printPlayerScore()
call printBoard()
call printPlayerMessage()
end if
end while
end subroutine
subroutine gameMenu()
cls
call clearGameVars()
player1Score$ = 0
player2Score$ = 0
print "================================================="
print "| TIC-TAC-TOE |"
print "=================================================" + chr(10)
print " Teclas para jugar:"
print "---------------------"
print " | q | w | e |"
print " | a | s | d |"
print " | z | x | c |" + chr(10)
print " Pulsa [SPACE] para comenzar o [ESC] para salir. "
do
tecla$ = key
pause .01
if tecla$ = keySpace$ then call gamePlay()
if tecla$ = keyEsc$ then call endGame()
until false
end subroutine
call gameMenu()
end
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
%==The main thing==%
%==First param - Number of disks==%
%==Second param - Start pole==%
%==Third param - End pole==%
%==Fourth param - Helper pole==%
call :move 4 START END HELPER
echo.
pause
exit /b 0
%==The "function"==%
:move
setlocal
set n=%1
set from=%2
set to=%3
set via=%4
if %n% gtr 0 (
set /a x=!n!-1
call :move !x! %from% %via% %to%
echo Move top disk from pole %from% to pole %to%.
call :move !x! %via% %to% %from%
)
exit /b 0 |
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
| #J | J | (, -.)@]^:[&0]9
0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 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
| #REXX | REXX | /* REXX (required by some interpreters) */
Numeric Digits 1000000
ttest ='[(10, 13), (56, 101), (1030, 10009), (44402, 100049)]'
Do While pos('(',ttest)>0
Parse Var ttest '(' n ',' p ')' ttest
r = tonelli(n, p)
Say "n =" n "p =" p
Say " roots :" r (p - r)
End
Exit
legendre: Procedure
Parse Arg a, p
return pow(a, (p - 1) % 2, p)
tonelli: Procedure
Parse Arg n, p
q = p - 1
s = 0
Do while q // 2 == 0
q = q % 2
s = s+1
End
if s == 1 Then
return pow(n, (p + 1) % 4, p)
Do z=2 To p
if p - 1 == legendre(z, p) Then
Leave
End
c = pow(z, q, p)
r = pow(n, (q + 1) / 2, p)
t = pow(n, q, p)
m = s
t2 = 0
Do while (t - 1) // p <> 0
t2 = (t * t) // p
Do i=1 To m
if (t2 - 1) // p == 0 Then
Leave
t2 = (t2 * t2) // p
End
y=2**(m - i - 1)
b = pow(c, y, p)
If b=10008 Then Trace ?R
r = (r * b) // p
c = (b * b) // p
t = (t * c) // p
m = i
End
return r
pow: Procedure
Parse Arg x,y,z
If y>0 Then
p=x**y
Else p=x
If z>'' Then
p=p//z
Return p |
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
| #JavaScript | JavaScript | function tokenize(s, esc, sep) {
for (var a=[], t='', i=0, e=s.length; i<e; i+=1) {
var c = s.charAt(i)
if (c == esc) t+=s.charAt(++i)
else if (c != sep) t+=c
else a.push(t), t=''
}
a.push(t)
return a
}
var s = 'one^|uno||three^^^^|four^^^|^cuatro|'
document.write(s, '<br>')
for (var a=tokenize(s,'^','|'), i=0; i<a.length; i+=1) document.write(i, ': ', a[i], '<br>') |
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
| #Wren | Wren | import "/dynamic" for Tuple
import "/math" for Nums
var Circle = Tuple.create("Circle", ["x", "y", "r"])
var circles = [
Circle.new( 1.6417233788, 1.6121789534, 0.0848270516),
Circle.new(-1.4944608174, 1.2077959613, 1.1039549836),
Circle.new( 0.6110294452, -0.6907087527, 0.9089162485),
Circle.new( 0.3844862411, 0.2923344616, 0.2375743054),
Circle.new(-0.2495892950, -0.3832854473, 1.0845181219),
Circle.new( 1.7813504266, 1.6178237031, 0.8162655711),
Circle.new(-0.1985249206, -0.8343333301, 0.0538864941),
Circle.new(-1.7011985145, -0.1263820964, 0.4776976918),
Circle.new(-0.4319462812, 1.4104420482, 0.7886291537),
Circle.new( 0.2178372997, -0.9499557344, 0.0357871187),
Circle.new(-0.6294854565, -1.3078893852, 0.7653357688),
Circle.new( 1.7952608455, 0.6281269104, 0.2727652452),
Circle.new( 1.4168575317, 1.0683357171, 1.1016025378),
Circle.new( 1.4637371396, 0.9463877418, 1.1846214562),
Circle.new(-0.5263668798, 1.7315156631, 1.4428514068),
Circle.new(-1.2197352481, 0.9144146579, 1.0727263474),
Circle.new(-0.1389358881, 0.1092805780, 0.7350208828),
Circle.new( 1.5293954595, 0.0030278255, 1.2472867347),
Circle.new(-0.5258728625, 1.3782633069, 1.3495508831),
Circle.new(-0.1403562064, 0.2437382535, 1.3804956588),
Circle.new( 0.8055826339, -0.0482092025, 0.3327165165),
Circle.new(-0.6311979224, 0.7184578971, 0.2491045282),
Circle.new( 1.4685857879, -0.8347049536, 1.3670667538),
Circle.new(-0.6855727502, 1.6465021616, 1.0593087096),
Circle.new( 0.0152957411, 0.0638919221, 0.9771215985)
]
var sq = Fn.new { |v| v * v }
var xMin = Nums.min(circles.map { |c| c.x - c.r })
var xMax = Nums.max(circles.map { |c| c.x + c.r })
var yMin = Nums.min(circles.map { |c| c.y - c.r })
var yMax = Nums.max(circles.map { |c| c.y + c.r })
var boxSide = 3000
var dx = (xMax - xMin) / boxSide
var dy = (yMax - yMin) / boxSide
var count = 0
for (r in 0...boxSide) {
var y = yMin + r * dy
for (c in 0...boxSide) {
var x = xMin + c * dx
var b = circles.any { |c| sq.call(x-c.x) + sq.call(y-c.y) <= sq.call(c.r) }
if (b) count = count + 1
}
}
System.print("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]
| #Haskell | Haskell | import Data.List ((\\), elemIndex, intersect, nub)
import Data.Bifunctor (bimap, first)
combs 0 _ = [[]]
combs _ [] = []
combs k (x:xs) = ((x :) <$> combs (k - 1) xs) ++ combs k xs
depLibs :: [(String, String)]
depLibs =
[ ( "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", [])
]
toposort :: [(String, String)] -> [String]
toposort xs
| (not . null) cycleDetect =
error $ "Dependency cycle detected for libs " ++ show cycleDetect
| otherwise = foldl makePrecede [] dB
where
dB = (\(x, y) -> (x, y \\ x)) . bimap return words <$> xs
makePrecede ts ([x], xs) =
nub $
case elemIndex x ts of
Just i -> uncurry (++) $ first (++ xs) $ splitAt i ts
_ -> ts ++ xs ++ [x]
cycleDetect =
filter ((> 1) . length) $
(\[(a, as), (b, bs)] -> (a `intersect` bs) ++ (b `intersect` as)) <$>
combs 2 dB
main :: IO ()
main = print $ toposort depLibs |
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.
| #NetLogo | NetLogo |
;; "A Turing Turtle": a Turing Machine implemented in NetLogo
;; by Dan Dewey 1/16/2016
;;
;; This NetLogo code implements a Turing Machine, see, e.g.,
;; http://en.wikipedia.org/wiki/Turing_machine
;; The Turing machine fits nicely into the NetLogo paradigm in which
;; there are agents (aka the turtles), that move around
;; in a world of "patches" (2D cells).
;; Here, a single agent represents the Turing machine read/write head
;; and the patches represent the Turing tape values via their colors.
;; The 2D array of patches is treated as a single long 1D tape in an
;; obvious way.
;; This program is presented as a NetLogo example on the page:
;; http://rosettacode.org/wiki/Universal_Turing_machine
;; This file may be larger than others on that page, note however
;; that I include many comments in the code and I have made no
;; effort to 'condense' the code, prefering clarity over compactness.
;; A demo and discussion of this program is on the web page:
;; http://sites.google.com/site/dan3deweyscspaimsportfolio/extra-turing-machine
;; The Copy example machine was taken from:
;; http://en.wikipedia.org/wiki/Turing_machine_examples
;; The "Busy Beaver" machines encoded below were taken from:
;; http://www.logique.jussieu.fr/~michel/ha.html
;; The implementation here allows 3 symbols (blank, 0, 1) on the tape
;; and 3 head motions (left, stay, right).
;; The 2D world is nominally set to be 29x29, going from (-14,-14) to
;; (14,14) from lower left to upper right and with (0,0) at the center.
;; This gives a total Turing tape length of 29^2 = 841 cells, sufficient for the
;; "Lazy" Beaver 5,2 example.
;; Since the max-pxcor variable is used in the code below (as opposed to
;; a hard-coded number), the effective tape size can be changed by
;; changing the size of the 2D world with the Settings... button on the interface.
;; The "Info" tab of the NetLogo interface contains some further comments.
;; - - - - - - -
;; - - - - - - - - - - - Global/Agent variables
;; These three 2D arrays (lists of lists) encode the Turing Machine rules:
;; WhatToWrite: -1 (Blank), 0, 1
;; HowToMove: -1 (left), 0(stay), 1 (right)
;; NextState: 0 to N-1, negative value goes to a halt state.
;; The above are a function of the current state and the current tape (patch) value.
;; MachineState is used by the turtle to pass the current state of the Turing machine
;; (or the halt code) to the observer.
globals [ WhatToWrite HowToMove NextState MachineState
;; some other golobals of secondary importance...
;; set different patch colors to record the Turing tape values
BlankColor ZeroColor OneColor
;; a delay constant to slow down the operation
RealTimePerTick ]
;; We'll have one turtle which is the Turing machine read/write head
;; it will keep track of the current Turing state in its own MyState value
turtles-own [ MyState ]
;; - - - - - - - - - - -
to Setup ;; sets up the world
clear-all ;; clears the world first
;; Try to not have (too many) ad hoc numbers in the code,
;; collect and set various values here especially if they might be used in multiple places:
;; The colors for Blank, Zero and One : (user can can change as desired)
set BlankColor 2 ;; dark gray
set OneColor green
set ZeroColor red
;; slow it down for the humans to watch
set RealTimePerTick 0.2 ;; have simulation go at nice realtime speed
create-turtles 1 ;; create the one Turing turtle
[ ;; set default parameters
set size 2 ;; set a nominal size
set color yellow ;; color of border
;; set the starting location, some Turing programs will adjust this if needed:
setxy 0 0 ;; -1 * max-pxcor -1 * max-pxcor
set shape "square2empty" ;; edited version of "square 2" to have clear in middle
;; set the starting state - always 0
set MyState 0
set MachineState 0 ;; the turtle will update this global value from now on
]
;; Define the Turing machine rules with 2D lists.
;; Based on the selection made on interface panel, setting the string Turing_Program_Selection.
;; This routine has all the Turing 'programs' in it - it's at the very bottom of this file.
LoadTuringProgram
;; the environment, e.g. the Turing tape
ask patches
[
;; all patches are set to the blank color
set pcolor BlankColor
]
;; keep track of time; each tick is a Turing step
reset-ticks
end
;; - - - - - - - - - - - - - - - -
to Go ;; this repeatedly does steps
;; The turtle does the main work
ask turtles
[
DoOneStep
wait RealTimePerTick
]
tick
;; The Turing turtle will die if it tries to go beyond the cells,
;; in that case (no turtles left) we'll stop.
;; Also stop if the MachineState has been set to a negative number (a halt state).
if ((count turtles = 0) or (MachineState < 0))
[ stop ]
end
to DoOneStep
;; have the turtle do one Turing step
;; First, 'read the tape', i.e., based on the patch color here:
let tapeValue GetTapeValue
;; using the tapeValue and MyState, get the desired actions here:
;; (the item commands extract the appropriate value from the list-of-lists)
let myWrite item (tapeValue + 1) (item MyState WhatToWrite)
let myMove item (tapeValue + 1) (item MyState HowToMove)
let myNextState item (tapeValue + 1) (item MyState NextState)
;; Write to the tape as appropriate
SetTapeValue myWrite
;; Move as appropriate
if (myMove = 1) [MoveForward]
if (myMove = -1) [MoveBackward]
;; Go to the next state; check if it is a halt state.
;; Update the global MachineState value
set MachineState myNextState
ifelse (myNextState < 0)
[
;; It's a halt state. The negative MachineState will signal the stop.
;; Go back to the starting state so it can be re-run if desired.
set MyState 0]
[
;; Not a halt state, so change to the desired next state
set MyState myNextState
]
end
to MoveForward
;; move the turtle forward one cell, including line wrapping.
set heading 90
ifelse (xcor = max-pxcor)
[set xcor -1 * max-pxcor
;; and go up a row if possible... otherwise die
ifelse ycor = max-pxcor
[ die ] ;; tape too short - a somewhat crude end of things ;-)
[set ycor ycor + 1]
]
[jump 1]
end
to MoveBackward
;; move the turtle backward one cell, including line-wrapping.
set heading -90
ifelse (xcor = -1 * max-pxcor)
[
set xcor max-pxcor
;; and go down a row... or die
ifelse ycor = -1 * max-pxcor
[ die ] ;; tape too short - a somewhat crude end of things ;-)
[set ycor ycor - 1]
]
[jump 1]
end
to-report GetTapeValue
;; report the tape color equivalent value
if (pcolor = ZeroColor) [report 0]
if (pcolor = OneColor) [report 1]
report -1
end
to SetTapeValue [ value ]
;; write the appropriate color on the tape
ifelse (value = 1)
[set pcolor OneColor]
[ ifelse (value = 0)
[set pcolor ZeroColor][set pcolor BlankColor]]
end
;; - - - - - OK, here are the data for the various Turing programs...
;; Note that besdes settting the rules (array values) these sections can also
;; include commands to clear the tape, position the r/w head, adjust wait time, etc.
to LoadTuringProgram
;; A template of the rules structure: a list of lists
;; E.g. values are given for States 0 to 4, when looking at Blank, Zero, One:
;; For 2-symbol machines use Blank(-1) and One(1) and ignore the middle values (never see zero).
;; Normal Halt will be state -1, the -9 default shows an unexpected halt.
;; state 0 state 1 state 2 state 3 state 4
set WhatToWrite (list (list -1 0 1) (list -1 0 1) (list -1 0 1) (list -1 0 1) (list -1 0 1) )
set HowToMove (list (list 0 0 0) (list 0 0 0) (list 0 0 0) (list 0 0 0) (list 0 0 0) )
set NextState(list (list -9 -9 -9) (list -9 -9 -9) (list -9 -9 -9) (list -9 -9 -9) (list -9 -9 -9) )
;; Fill the rules based on the selected case
if (Turing_Program_Selection = "Simple Incrementor")
[
;; simple Incrementor - this is from the RosettaCode Universal Turing Machine page - very simple!
set WhatToWrite (list (list 1 0 1) )
set HowToMove (list (list 0 0 1) )
set NextState (list (list -1 -9 0) )
]
;; Fill the rules based on the selected case
if (Turing_Program_Selection = "Incrementor w/Return")
[
;; modified Incrementor: it returns to the first 1 on the left.
;; This version allows the "Copy Ones to right" program to directly follow it.
;; move right append one back to beginning
set WhatToWrite (list (list -1 0 1) (list 1 0 1) (list -1 0 1) )
set HowToMove (list (list 1 0 1) (list 0 0 1) (list 1 0 -1) )
set NextState (list (list 1 -9 1) (list 2 -9 1) (list -1 -9 2) )
]
;; Fill the rules based on the selected case
if (Turing_Program_Selection = "Copy Ones to right")
[
;; "Copy" from Wiki "Turing machine examples" page; slight mod so that it ends on first 1
;; of the copy allowing Copy to be re-executed to create another copy.
;; Has 5 states and uses Blank and 1 to make a copy of a string of ones;
;; this can be run after runs of the "Incrementor w/Return".
;; state 0 state 1 state 2 state 3 state 4
set WhatToWrite (list (list -1 0 -1) (list -1 0 1) (list 1 0 1) (list -1 0 1) (list 1 0 1) )
set HowToMove (list (list 1 0 1) (list 1 0 1) (list -1 0 1) (list -1 0 -1) (list 1 0 -1) )
set NextState (list (list -1 -9 1) (list 2 -9 1) (list 3 -9 2) (list 4 -9 3) (list 0 -9 4) )
]
;; Fill the rules based on the selected case
if (Turing_Program_Selection = "Binary Counter")
[
;; Count in binary - can start on a blank space.
;; States: start carry-1 back-to-beginning
set WhatToWrite (list (list 1 1 0) (list 1 1 0) (list -1 0 1) )
set HowToMove (list (list 0 0 -1) (list 0 0 -1) (list -1 1 1) )
set NextState (list (list -1 -1 1) (list 2 2 1) (list -1 2 2) )
;; Select line above from these two:
;; can either count by 1 each time it is run:
;; set NextState (list (list -1 -1 1) (list 2 2 1) (list -1 2 2) )
;; or count forever once started:
;; set NextState (list (list 0 0 1) (list 2 2 1) (list 0 2 2) )
set RealTimePerTick 0.2
]
if (Turing_Program_Selection = "Busy-Beaver 3-State, 2-Sym")
[
;; from the RosettaCode.org Universal Turing Machine page
;; state name: a b c
set WhatToWrite (list (list 1 0 1) (list 1 0 1) (list 1 0 1) (list -1 0 1) (list -1 0 1) )
set HowToMove (list (list 1 0 -1) (list -1 0 1) (list -1 0 0) (list 0 0 0) (list 0 0 0) )
set NextState (list (list 1 -9 2) (list 0 -9 1) (list 1 -9 -1) (list -9 -9 -9) (list -9 -9 -9) )
;; Clear the tape
ask Patches [set pcolor BlankColor]
]
;; should output 13 ones and take 107 steps to do it...
if (Turing_Program_Selection = "Busy-Beaver 4-State, 2-Sym")
[
;; from the RosettaCode.org Universal Turing Machine page
;; state name: A B C D
set WhatToWrite (list (list 1 0 1) (list 1 0 -1) (list 1 0 1) (list 1 0 -1) (list -1 0 1) )
set HowToMove (list (list 1 0 -1) (list -1 0 -1) (list 1 0 -1) (list 1 0 1) (list 0 0 0) )
set NextState (list (list 1 -9 1) (list 0 -9 2) (list -1 -9 3) (list 3 -9 0) (list -9 -9 -9) )
;; Clear the tape
ask Patches [set pcolor BlankColor]
]
;; This takes 38 steps to write 9 ones/zeroes
if (Turing_Program_Selection = "Busy-Beaver 2-State, 3-Sym")
[
;; A B
set WhatToWrite (list (list 0 1 0) (list 1 1 0) (list -1 0 1) (list -1 0 1) (list -1 0 1) )
set HowToMove (list (list 1 -1 1) (list -1 1 -1) (list 0 0 0) (list 0 0 0) (list 0 0 0) )
set NextState(list (list 1 1 -1) (list 0 1 1) (list -9 -9 -9) (list -9 -9 -9) (list -9 -9 -9) )
;; Clear the tape
ask Patches [set pcolor BlankColor]
]
;; This only makes 501 ones and stops after 134,467 steps -- it does do that !!!
if (Turing_Program_Selection = "Lazy-Beaver 5-State, 2-Sym")
[
;; from the RosettaCode.org Universal Turing Machine page
;; state name: A0 B1 C2 D3 E4
set WhatToWrite (list (list 1 0 -1) (list 1 0 1) (list 1 0 -1) (list -1 0 1) (list 1 0 1) )
set HowToMove (list (list 1 0 -1) (list 1 0 1) (list -1 0 1) (list 1 0 1) (list -1 0 1) )
set NextState (list (list 1 -9 2) (list 2 -9 3) (list 0 -9 1) (list 4 -9 -1) (list 2 -9 0) )
;; Clear the tape
ask Patches [set pcolor BlankColor]
;; Looks like it goes much more forward than back on the tape
;; so start the head just a row from the bottom:
ask turtles [setxy 0 -1 * max-pxcor + 1]
;; and go faster
set RealTimePerTick 0.02
]
;; The rest have large outputs and run for a long time, so I haven't confirmed
;; that they work as advertised...
;; This is the 5,2 record holder: 4098 ones in 47,176,870 steps.
;; With max-pxcor of 14 and offset r/w head start (below), this will
;; run off the tape at about 150,000+steps...
if (Turing_Program_Selection = "Busy-Beaver 5-State, 2-Sym")
[
;; from the RosettaCode.org Universal Turing Machine page
;; state name: A B C D E
set WhatToWrite (list (list 1 0 1) (list 1 0 1) (list 1 0 -1) (list 1 0 1) (list 1 0 -1) )
set HowToMove (list (list 1 0 -1) (list 1 0 1) (list 1 0 -1) (list -1 0 -1) (list 1 0 -1) )
set NextState (list (list 1 -9 2) (list 2 -9 1) (list 3 -9 4) (list 0 -9 3) (list -1 -9 0) )
;; Clear the tape
ask Patches [set pcolor BlankColor]
;; Writes more backward than forward, so start a few rows from the top:
ask turtles [setxy 0 max-pxcor - 3]
;; and go faster
set RealTimePerTick 0.02
]
if (Turing_Program_Selection = "Lazy-Beaver 3-State, 3-Sym")
[
;; This should write 5600 ones/zeros and take 29,403,894 steps.
;; Ran it to 175,000+ steps and only covered 1/2 of the cells (w/max-pxcor = 14)...
;; state name: A B C
set WhatToWrite (list (list 0 1 0) (list 1 -1 0) (list 0 1 0) (list -1 0 1) (list -1 0 1) )
set HowToMove (list (list 1 1 -1) (list -1 1 1) (list 1 -1 1) (list 0 0 0) (list 0 0 0) )
set NextState (list (list 1 0 0) (list 2 2 1) (list -1 0 1) (list -9 -9 -9) (list -9 -9 -9) )
;; Clear the tape
ask Patches [set pcolor BlankColor]
;; It goes much more forward than back on the tape
;; so start the head just a row from the bottom:
ask turtles [setxy 0 -1 * max-pxcor + 1]
;; and go faster
set RealTimePerTick 0.02
]
if (Turing_Program_Selection = "Busy-Beaver 3-State, 3-Sym")
[
;; This should write 374,676,383 ones/zeros and take 119,112,334,170,342,540 (!!!) steps.
;; Rn it to ~ 175,000 steps covering about 2/3 of the max-pxcor=14 cells.
;; state name: A B C
set WhatToWrite (list (list 0 1 0) (list -1 1 0) (list 0 0 0) (list -1 0 1) (list -1 0 1) )
set HowToMove (list (list 1 -1 -1) (list -1 1 -1) (list 1 1 1) (list 0 0 0) (list 0 0 0) )
set NextState (list (list 1 0 2) (list 0 1 1) (list -1 0 2) (list -9 -9 -9) (list -9 -9 -9) )
;; Clear the tape
ask Patches [set pcolor BlankColor]
;; Writes more backward than forward, so start a rowish from the top:
ask turtles [setxy 0 max-pxcor - 1]
;; and go faster
set RealTimePerTick 0.02
]
;; in all cases reset the machine state to 0:
ask turtles [set MyState 0]
set MachineState 0
;; and the ticks
reset-ticks
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).
| #Nim | Nim | import strformat
func totient(n: int): int =
var tot = n
var nn = n
var i = 2
while i * i <= nn:
if nn mod i == 0:
while nn mod i == 0:
nn = nn div i
dec tot, tot div i
if i == 2:
i = 1
inc i, 2
if nn > 1:
dec tot, tot div nn
tot
echo " n φ prime"
echo "---------------"
var count = 0
for n in 1..25:
let tot = totient(n)
let isPrime = n - 1 == tot
if isPrime:
inc count
echo fmt"{n:2} {tot:2} {isPrime}"
echo ""
echo fmt"Number of primes up to {25:>6} = {count:>4}"
for n in 26..100_000:
let tot = totient(n)
if tot == n - 1:
inc count
if n == 100 or n == 1000 or n mod 10_000 == 0:
echo fmt"Number of primes up to {n:>6} = {count:>4}" |
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
| #Tcl | Tcl | package require struct::list
proc swap {listVar} {
upvar 1 $listVar list
set n [lindex $list 0]
for {set i 0; set j [expr {$n-1}]} {$i<$j} {incr i;incr j -1} {
set tmp [lindex $list $i]
lset list $i [lindex $list $j]
lset list $j $tmp
}
}
proc swaps {list} {
for {set i 0} {[lindex $list 0] > 1} {incr i} {
swap list
}
return $i
}
proc topswops list {
set n 0
::struct::list foreachperm p $list {
set n [expr {max($n,[swaps $p])}]
}
return $n
}
proc topswopsTo n {
puts "n\ttopswops(n)"
for {set i 1} {$i <= $n} {incr i} {
puts $i\t[topswops [lappend list $i]]
}
}
topswopsTo 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.
| #GAP | GAP | # GAP has an improved floating-point support since version 4.5
Pi := Acos(-1.0);
# Or use the built-in constant:
Pi := FLOAT.PI;
r := Pi / 5.0;
d := 36;
Deg := x -> x * Pi / 180;
Sin(r); Asin(last);
Sin(Deg(d)); Asin(last);
Cos(r); Acos(last);
Cos(Deg(d)); Acos(last);
Tan(r); Atan(last);
Tan(Deg(d)); Atan(last); |
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).
| #PL.2FI | PL/I |
Trabb: Procedure options (main); /* 11 November 2013 */
declare (i, n) fixed binary;
declare s fixed (5,1) controlled;
declare g fixed (15,5);
put ('Please type 11 values:');
do i = 1 to 11;
allocate s;
get (s);
put (s);
end;
put skip(2) ('Results:');
do i = 1 to 11;
g = f(s); put skip list (s);
if g > 400 then put ('Too large'); else put (g);
free s;
end;
f: procedure (x) returns (fixed(15,5));
declare x fixed (5,1);
return (sqrt(abs(x)) + 5*x**3);
end f;
end Trabb;
|
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).
| #PL.2FM | PL/M | TPK: DO;
/* external I/O and real mathematical routines */
WRITE$STRING: PROCEDURE( S ) EXTERNAL; DECLARE S POINTER; END;
WRITE$REAL: PROCEDURE( R ) EXTERNAL; DECLARE R REAL; END;
WRITE$NL: PROCEDURE EXTERNAL; END;
READ$REAL: PROCEDURE( R ) REAL EXTERNAL; DECLARE R POINTER; END;
REAL$ABS: PROCEDURE( R ) REAL EXTERNAL; DECLARE R REAL; END;
REAL$SQRT: PROCEDURE( R ) REAL EXTERNAL; DECLARE R REAL; END;
/* end external routines */
F: PROCEDURE( T ) REAL;
DECLARE T REAL;
RETURN REAL$SQRT(REAL$ABS(T))+5*T*T*T;
END F;
MAIN: PROCEDURE;
DECLARE Y REAL, A( 11 ) REAL, I INTEGER;
DO I = 0 TO 10;
CALL READ$REAL( @A( I ) );
END;
DO I = 10 TO 0 BY -1;
Y = F( A( I ) );
IF Y > 400.0 THEN CALL WRITE$STRING( @( 'TOO LARGE', 0 ) );
ELSE CALL WRITE$REAL( Y );
CALL WRITE$NL();
END;
END MAIN;
END TPK; |
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).
| #PowerShell | PowerShell |
function Get-Tpk
{
[CmdletBinding()]
[OutputType([PSCustomObject])]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[double]
$Number
)
Begin
{
function Get-TpkFunction ([double]$Number)
{
[Math]::Pow([Math]::Abs($Number),(0.5)) + 5 * [Math]::Pow($Number,3)
}
[object[]]$output = @()
}
Process
{
$Number | ForEach-Object {
$n = Get-TpkFunction $_
if ($n -le 400)
{
$result = $n
}
else
{
$result = "Overflow"
}
}
$output += [PSCustomObject]@{
Number = $Number
Result = $result
}
}
End
{
[Array]::Reverse($output)
$output
}
}
|
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.
| #XBasic | XBasic |
PROGRAM "truthtables"
VERSION "0.001"
$$MaxTop = 80
TYPE VARIABLE
STRING*1 .name
SBYTE .value
END TYPE
TYPE STACKOFBOOL
SSHORT .top
SBYTE .elements[$$MaxTop]
END TYPE
DECLARE FUNCTION Entry()
INTERNAL FUNCTION IsOperator(c$)
INTERNAL FUNCTION VariableIndex(c$)
INTERNAL FUNCTION SetVariables(pos%)
INTERNAL FUNCTION ProcessExpression()
INTERNAL FUNCTION EvaluateExpression()
' Stack manipulation functions
INTERNAL FUNCTION IsFull(STACKOFBOOL @s)
INTERNAL FUNCTION IsEmpty(STACKOFBOOL @s)
INTERNAL FUNCTION Peek(STACKOFBOOL @s)
INTERNAL FUNCTION Push(STACKOFBOOL @s, val@)
INTERNAL FUNCTION Pop(STACKOFBOOL @s)
INTERNAL FUNCTION MakeEmpty(STACKOFBOOL @s)
INTERNAL FUNCTION ElementsCount(STACKOFBOOL @s)
FUNCTION Entry()
SHARED VARIABLE variables[]
SHARED variablesLength%
SHARED expression$
DIM variables[23]
PRINT "Accepts single-character variables (except for 'T' and 'F',"
PRINT "which specify explicit true or false values), postfix, with"
PRINT "&|!^ for and, or, not, xor, respectively; optionally"
PRINT "seperated by space. Just enter nothing to quit."
DO
PRINT
expression$ = INLINE$("Boolean expression: ")
ProcessExpression()
IF LEN(expression$) = 0 THEN
EXIT DO
END IF
variablesLength% = 0
FOR i% = 0 TO LEN(expression$) - 1
e$ = CHR$(expression${i%})
IF (!IsOperator(e$)) && (e$ <> "T") && (e$ <> "F") && (VariableIndex(e$) = -1) THEN
variables[variablesLength%].name = LEFT$(e$, 1)
variables[variablesLength%].value = $$FALSE
INC variablesLength%
END IF
NEXT i%
PRINT
IF variablesLength% = 0 THEN
PRINT "No variables were entered."
ELSE
FOR i% = 0 TO variablesLength% - 1
PRINT variables[i%].name; " ";
NEXT i%
PRINT expression$
PRINT CHR$(ASC("="), variablesLength% * 3 + LEN(expression$))
SetVariables(0)
END IF
LOOP
END FUNCTION
' Removes space and converts to upper case
FUNCTION ProcessExpression()
SHARED expression$
'
exprTmp$ = ""
FOR i% = 0 TO LEN(expression$) - 1
IF CHR$(expression${i%}) <> " " THEN
exprTmp$ = exprTmp$ + UCASE$(CHR$(expression${i%}))
END IF
NEXT i%
expression$ = exprTmp$
END FUNCTION
FUNCTION IsOperator(c$)
RETURN (c$ = "&") || (c$ = "|") || (c$ = "!") || (c$ = "^")
END FUNCTION
FUNCTION VariableIndex(c$)
SHARED VARIABLE variables[]
SHARED variablesLength%
'
FOR i% = 0 TO variablesLength% - 1
IF variables[i%].name = c$ THEN
RETURN i%
END IF
NEXT i%
RETURN -1
END FUNCTION
FUNCTION SetVariables(pos%)
SHARED VARIABLE variables[]
SHARED variablesLength%
'
SELECT CASE TRUE
CASE pos% > variablesLength%:
PRINT
PRINT "Argument to SetVariables cannot be greater than the number of variables."
QUIT(1)
CASE pos% = variablesLength%:
FOR i% = 0 TO variablesLength% - 1
IF variables[i%].value THEN
PRINT "T ";
ELSE
PRINT "F ";
END IF
NEXT i%
IF EvaluateExpression() THEN
PRINT "T"
ELSE
PRINT "F"
END IF
CASE ELSE:
variables[pos%].value = $$FALSE
SetVariables(pos% + 1)
variables[pos%].value = $$TRUE
SetVariables(pos% + 1)
END SELECT
END FUNCTION
FUNCTION EvaluateExpression()
SHARED VARIABLE variables[]
SHARED expression$
STACKOFBOOL s
'
MakeEmpty(@s)
FOR i% = 0 TO LEN(expression$) - 1
e$ = CHR$(expression${i%})
vi% = VariableIndex(e$)
SELECT CASE TRUE
CASE e$ = "T":
Push(@s, $$TRUE)
CASE e$ = "F":
Push(@s, $$FALSE)
CASE vi% >= 0:
Push(@s, variables[vi%].value)
CASE ELSE:
SELECT CASE e$
CASE "&":
Push(@s, Pop(@s) & Pop(@s))
CASE "|":
Push(@s, Pop(@s) | Pop(@s))
CASE "!":
Push(@s, !Pop(@s))
CASE "^":
Push(@s, Pop(@s) ^ Pop(@s))
CASE ELSE:
PRINT
PRINT "Non-conformant character "; e$; " in expression.";
QUIT(1)
END SELECT
END SELECT
NEXT i%
IF ElementsCount(@s) <> 1 THEN
PRINT
PRINT "Stack should contain exactly one element."
QUIT(1)
END IF
RETURN Peek(@s)
END FUNCTION
FUNCTION IsFull(STACKOFBOOL s)
RETURN s.top = $$MaxTop
END FUNCTION
FUNCTION IsEmpty(STACKOFBOOL s)
RETURN s.top = -1
END FUNCTION
FUNCTION Peek(STACKOFBOOL s)
IF !IsEmpty(@s) THEN
RETURN s.elements[s.top]
ELSE
PRINT "Stack is empty."
QUIT(1)
END IF
END FUNCTION
FUNCTION Push(STACKOFBOOL s, val@)
IF !IsFull(@s) THEN
INC s.top
s.elements[s.top] = val@
ELSE
PRINT "Stack is full."
QUIT(1)
END IF
END FUNCTION
FUNCTION Pop(STACKOFBOOL s)
IF !IsEmpty(@s) THEN
res@ = s.elements[s.top]
DEC s.top
RETURN res@
ELSE
PRINT
PRINT "Stack is empty."
QUIT(1)
END IF
END FUNCTION
FUNCTION MakeEmpty(STACKOFBOOL s)
s.top = -1
END FUNCTION
FUNCTION ElementsCount(STACKOFBOOL s)
RETURN s.top + 1
END FUNCTION
END PROGRAM
|
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.]
| #PL.2FI | PL/I |
tp: procedure options (main);
declare primes(1000000) bit (1);
declare max_primes fixed binary (31);
declare (i, k) fixed binary (31);
max_primes = hbound(primes, 1);
call sieve;
/* Now search for primes that are right-truncatable. */
call right_truncatable;
/* Now search for primes that are left-truncatable. */
call left_truncatable;
right_truncatable: procedure;
declare direction bit (1);
declare (i, k) fixed binary (31);
test_truncatable:
do i = max_primes to 2 by -1;
if primes(i) then /* it's a prime */
do;
k = i/10;
do while (k > 0);
if ^primes(k) then iterate test_truncatable;
k = k/10;
end;
put skip list (i || ' is right-truncatable');
return;
end;
end;
end right_truncatable;
left_truncatable: procedure;
declare direction bit (1);
declare (i, k, d, e) fixed binary (31);
test_truncatable:
do i = max_primes to 2 by -1;
if primes(i) then /* it's a prime */
do;
k = i;
do d = 100000 repeat d/10 until (d = 10);
e = k/d;
k = k - e*d;
if e = 0 then iterate test_truncatable;
if ^primes(k) then iterate test_truncatable;
end;
put skip list (i || ' is left-truncatable');
return;
end;
end;
end left_truncatable;
sieve: procedure;
declare (i, j) fixed binary (31);
primes = '1'b; primes(1) = '0'b;
do i = 2 to sqrt(max_primes);
do j = i+i to max_primes by i;
primes(j) = '0'b;
end;
end;
end sieve;
end tp;
|
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.]
| #PowerShell | PowerShell | function IsPrime ( [int] $num )
{
$isprime = @{}
2..[math]::sqrt($num) | Where-Object {
$isprime[$_] -eq $null } | ForEach-Object {
$_
$isprime[$_] = $true
for ( $i=$_*$_ ; $i -le $num; $i += $_ )
{ $isprime[$i] = $false }
}
2..$num | Where-Object { $isprime[$_] -eq $null }
}
function Truncatable ( [int] $num )
{
$declen = [math]::abs($num).ToString().Length
$primes = @()
$ltprimes = @{}
$rtprimes = @{}
1..$declen | ForEach-Object { $ltprimes[$_]=@{}; $rtprimes[$_]=@{} }
IsPrime $num | ForEach-Object {
$lastltprime = 2
$lastrtprime = 2
} {
$curprim = $_
$curdeclen = $curprim.ToString().Length
$primes += $curprim
if( $curdeclen -eq 1 ) {
$ltprimes[1][$curprim] = $true
$rtprimes[1][$curprim] = $true
$lastltprime = $curprim
$lastrtprime = $curprim
} else {
$curmod = $curprim % [math]::pow(10,$curdeclen - 1)
$curdiv = [math]::floor($curprim / 10)
if( $ltprimes[$curdeclen - 1][[int]$curmod] ) {
$ltprimes[$curdeclen][$curprim] = $true
$lastltprime = $curprim
}
if( $rtprimes[$curdeclen - 1][[int]$curdiv] ) {
$rtprimes[$curdeclen][$curprim] = $true
$lastrtprime = $curprim
}
}
if( ( $ltprimes[$curdeclen - 2].Keys.count -gt 0 ) -and ( $ltprimes[$curdeclen - 1].Keys.count -gt 0 ) ) { $ltprimes[$curdeclen -2] = @{} }
if( ( $rtprimes[$curdeclen - 2].Keys.count -gt 0 ) -and ( $rtprimes[$curdeclen - 1].Keys.count -gt 0 ) ) { $rtprimes[$curdeclen -2] = @{} }
} {
"Largest Left Truncatable Prime: $lastltprime"
"Largest Right Truncatable Prime: $lastrtprime"
}
} |
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.
| #E | E | def btree := [1, [2, [4, [7, null, null],
null],
[5, null, null]],
[3, [6, [8, null, null],
[9, null, null]],
null]]
def backtrackingOrder(node, pre, mid, post) {
switch (node) {
match ==null {}
match [value, left, right] {
pre(value)
backtrackingOrder(left, pre, mid, post)
mid(value)
backtrackingOrder(right, pre, mid, post)
post(value)
}
}
}
def levelOrder(root, func) {
var level := [root].diverge()
while (level.size() > 0) {
for node in level.removeRun(0) {
switch (node) {
match ==null {}
match [value, left, right] {
func(value)
level.push(left)
level.push(right)
} } } } }
print("preorder: ")
backtrackingOrder(btree, fn v { print(" ", v) }, fn _ {}, fn _ {})
println()
print("inorder: ")
backtrackingOrder(btree, fn _ {}, fn v { print(" ", v) }, fn _ {})
println()
print("postorder: ")
backtrackingOrder(btree, fn _ {}, fn _ {}, fn v { print(" ", v) })
println()
print("level-order:")
levelOrder(btree, fn v { print(" ", v) })
println() |
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
| #Ceylon | Ceylon | shared void tokenizeAString() {
value input = "Hello,How,Are,You,Today";
value tokens = input.split(','.equals);
print(".".join(tokens));
} |
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
| #CFEngine | CFEngine | bundle agent main
{
reports:
"${with}" with => join(".", splitstring("Hello,How,Are,You,Today", ",", 99));
}
|
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #C | C | #include <stdio.h>
#include <time.h>
int identity(int x) { return x; }
int sum(int s)
{
int i;
for(i=0; i < 1000000; i++) s += i;
return s;
}
#ifdef CLOCK_PROCESS_CPUTIME_ID
/* cpu time in the current process */
#define CLOCKTYPE CLOCK_PROCESS_CPUTIME_ID
#else
/* this one should be appropriate to avoid errors on multiprocessors systems */
#define CLOCKTYPE CLOCK_MONOTONIC
#endif
double time_it(int (*action)(int), int arg)
{
struct timespec tsi, tsf;
clock_gettime(CLOCKTYPE, &tsi);
action(arg);
clock_gettime(CLOCKTYPE, &tsf);
double elaps_s = difftime(tsf.tv_sec, tsi.tv_sec);
long elaps_ns = tsf.tv_nsec - tsi.tv_nsec;
return elaps_s + ((double)elaps_ns) / 1.0e9;
}
int main()
{
printf("identity (4) takes %lf s\n", time_it(identity, 4));
printf("sum (4) takes %lf s\n", time_it(sum, 4));
return 0;
} |
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
| #E | E | /** Turn a list of arrays into a list of maps with the given keys. */
def addKeys(keys, rows) {
def res := [].diverge()
for row in rows { res.push(__makeMap.fromColumns(keys, row)) }
return res.snapshot()
}
def data := addKeys(
["name", "id", "salary", "dept"],
[["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"]])
def topSalaries(n, out) {
var groups := [].asMap()
for row in data {
def [=> salary, => dept] | _ := row
def top := groups.fetch(dept, fn {[]}).with([-salary, row]).sort()
groups with= (dept, top.run(0, top.size().min(n)))
}
for dept => group in groups.sortKeys() {
out.println(`Department $dept`)
out.println(`---------------`)
for [_, row] in group {
out.println(`${row["id"]} $$${row["salary"]} ${row["name"]}`)
}
out.println()
}
} |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
:newgame
set a1=1
set a2=2
set a3=3
set a4=4
set a5=5
set a6=6
set a7=7
set a8=8
set a9=9
set ll=X
set /a zz=0
:display1
cls
echo Player: %ll%
echo %a7%_%a8%_%a9%
echo %a4%_%a5%_%a6%
echo %a1%_%a2%_%a3%
set /p myt=Where would you like to go (choose a number from 1-9 and press enter)?
if !a%myt%! equ %myt% (
set a%myt%=%ll%
goto check
)
goto display1
:check
set /a zz=%zz%+1
if %zz% geq 9 goto newgame
if %a7%+%a8%+%a9% equ %ll%+%ll%+%ll% goto win
if %a4%+%a5%+%a6% equ %ll%+%ll%+%ll% goto win
if %a1%+%a2%+%a3% equ %ll%+%ll%+%ll% goto win
if %a7%+%a5%+%a3% equ %ll%+%ll%+%ll% goto win
if %a1%+%a5%+%a9% equ %ll%+%ll%+%ll% goto win
if %a7%+%a4%+%a1% equ %ll%+%ll%+%ll% goto win
if %a8%+%a5%+%a2% equ %ll%+%ll%+%ll% goto win
if %a9%+%a6%+%a3% equ %ll%+%ll%+%ll% goto win
goto %ll%
:X
set ll=O
goto display1
:O
set ll=X
goto display1
:win
echo %ll% wins!
pause
goto newgame
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #BBC_BASIC | BBC BASIC | DIM Disc$(13),Size%(3)
FOR disc% = 1 TO 13
Disc$(disc%) = STRING$(disc%," ")+STR$disc%+STRING$(disc%," ")
IF disc%>=10 Disc$(disc%) = MID$(Disc$(disc%),2)
Disc$(disc%) = CHR$17+CHR$(128+disc%-(disc%>7))+Disc$(disc%)+CHR$17+CHR$128
NEXT disc%
MODE 3
OFF
ndiscs% = 13
FOR n% = ndiscs% TO 1 STEP -1
PROCput(n%,1)
NEXT
INPUT TAB(0,0) "Press Enter to start" dummy$
PRINT TAB(0,0) SPC(20);
PROChanoi(ndiscs%,1,2,3)
VDU 30
END
DEF PROChanoi(a%,b%,c%,d%)
IF a%=0 ENDPROC
PROChanoi(a%-1,b%,d%,c%)
PROCtake(a%,b%)
PROCput(a%,c%)
PROChanoi(a%-1,d%,c%,b%)
ENDPROC
DEF PROCput(disc%,peg%)
PRINTTAB(13+26*(peg%-1)-disc%,20-Size%(peg%))Disc$(disc%);
Size%(peg%) = Size%(peg%)+1
ENDPROC
DEF PROCtake(disc%,peg%)
Size%(peg%) = Size%(peg%)-1
PRINTTAB(13+26*(peg%-1)-disc%,20-Size%(peg%))STRING$(2*disc%+1," ");
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
| #Java | Java | public class ThueMorse {
public static void main(String[] args) {
sequence(6);
}
public static void sequence(int steps) {
StringBuilder sb1 = new StringBuilder("0");
StringBuilder sb2 = new StringBuilder("1");
for (int i = 0; i < steps; i++) {
String tmp = sb1.toString();
sb1.append(sb2);
sb2.append(tmp);
}
System.out.println(sb1);
}
} |
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
| #JavaScript | JavaScript | (function(steps) {
'use strict';
var i, tmp, s1 = '0', s2 = '1';
for (i = 0; i < steps; i++) {
tmp = s1;
s1 += s2;
s2 += tmp;
}
console.log(s1);
})(6); |
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
| #Sidef | Sidef | func tonelli(n, p) {
legendre(n, p) == 1 || die "not a square (mod p)"
var q = p-1
var s = valuation(q, 2)
s == 1 ? return(powmod(n, (p + 1) >> 2, p)) : (q >>= s)
var c = powmod(2 ..^ p -> first {|z| legendre(z, p) == -1}, q, p)
var r = powmod(n, (q + 1) >> 1, p)
var t = powmod(n, q, p)
var m = s
var t2 = 0
while (!p.divides(t - 1)) {
t2 = ((t * t) % p)
var b
for i in (1 ..^ m) {
if (p.divides(t2 - 1)) {
b = powmod(c, 1 << (m - i - 1), p)
m = i
break
}
t2 = ((t2 * t2) % p)
}
r = ((r * b) % p)
c = ((b * b) % p)
t = ((t * c) % p)
}
return r
}
var tests = [
[10, 13], [56, 101], [1030, 10009], [44402, 100049],
[665820697, 1000000009], [881398088036, 1000000000039],
[41660815127637347468140745042827704103445750172002, 10**50 + 577],
]
for n,p in tests {
var r = tonelli(n, p)
assert((r*r - n) % p == 0)
say "Roots of #{n} are (#{r}, #{p-r}) mod #{p}"
} |
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
| #jq | jq | # Tokenize the input using the string "escape" as the prefix escape string
def tokenize(separator; escape):
# Helper functions:
# mapper/1 is like map/1, but for each element, $e, in the input array,
# if $e is an array, then it is inserted,
# otherwise the elements of ($e|f) are inserted.
def mapper(f): reduce .[] as $e
( [];
if ($e|type) == "array" then . + [$e] else . + ($e | f) end ) ;
# interpolate x
def interpolate(x):
reduce .[] as $i ([]; . + [$i, x]) | .[0:-1];
def splitstring(s; twixt):
if type == "string" then split(s) | interpolate(twixt)
else .
end;
# concatenate sequences of non-null elements:
def reform:
reduce .[] as $x ([];
if $x == null and .[-1] == null then .[0:-1] + ["", null]
elif $x == null then . + [null]
elif .[-1] == null then .[0:-1] + [$x]
else .[0:-1] + [ .[-1] + $x ]
end)
| if .[-1] == null then .[-1] = "" else . end;
splitstring(escape + escape; [escape])
| mapper( splitstring( escape + separator; [separator]) )
| mapper( splitstring( separator; null ) )
| map( if type == "string" then split(escape) else . end)
| flatten
| reform ; |
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
| #Julia | Julia | function tokenize2(s::AbstractString, sep::Char, esc::Char)
SPE = "\ufffe"
SPF = "\uffff"
s = replace(s, "$esc$esc", SPE) |>
s -> replace(s, "$esc$sep", SPF) |>
s -> last(s) == esc ? string(replace(s[1:end-1], esc, ""), esc) : replace(s, esc, "")
return map(split(s, sep)) do token
token = replace(token, SPE, esc)
return replace(token, SPF, sep)
end
end
@show tokenize2("one^|uno||three^^^^|four^^^|^cuatro|", '|', '^') |
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
| #XPL0 | XPL0 | real Circles, MinX, MaxX, MinY, MaxY, Temp, X, Y, DX, DY, Area;
int N, Cnt1, Cnt2;
def Del = 0.0005;
def Inf = float(-1>>1);
[\ X Y R
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];
MinX:= +Inf; MaxX:= -Inf;
MinY:= +Inf; MaxY:= -Inf;
for N:= 0 to 25*3-1 do
[Temp:= Circles(N+0);
if Temp < 0.0 then Temp:= Temp - Circles(N+2)
else Temp:= Temp + Circles(N+2);
if Temp < MinX then MinX:= Temp;
if Temp > MaxX then MaxX:= Temp;
Temp:= Circles(N+1);
if Temp < 0.0 then Temp:= Temp - Circles(N+2)
else Temp:= Temp + Circles(N+2);
if Temp < MinY then MinY:= Temp;
if Temp > MaxY then MaxY:= Temp;
Circles(N+2):= sq(Circles(N+2)); \square for speed
N:= N+2;
];
Cnt1:= 0; Cnt2:= 0;
Y:= MinY;
repeat X:= MinX;
repeat
loop [for N:= 0 to 25*3-1 do
[DX:= X - Circles(N+0);
DY:= Y - Circles(N+1);
if DX*DX + DY*DY <= Circles(N+2) then
[Cnt1:= Cnt1+1; quit];
N:= N+2;
];
quit;
];
Cnt2:= Cnt2+1;
X:= X + Del;
until X >= MaxX;
Y:= Y + Del;
until Y >= MaxY;
Area:= (MaxX-MinX) * (MaxY-MinY); \of bounding box
Area:= float(Cnt1)/float(Cnt2) * Area; \of circles
RlOut(0, Area);
] |
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]
| #Huginn | Huginn | import Algorithms as algo;
import Text as text;
class DirectedGraph {
_adjecentVertices = {};
add_vertex( vertex_ ) {
_adjecentVertices[vertex_] = [];
}
add_edge( from_, to_ ) {
_adjecentVertices[from_].push( to_ );
}
adjecent_vertices( vertex_ ) {
return ( vertex_ ∈ _adjecentVertices ? _adjecentVertices.get( vertex_ ) : [] );
}
}
class DepthFirstSearch {
_visited = set();
_postOrder = [];
_cycleDetector = set();
run( graph_, start_ ) {
_cycleDetector.insert( start_ );
_visited.insert( start_ );
for ( vertex : graph_.adjecent_vertices( start_ ) ) {
if ( vertex == start_ ) {
continue;
}
if ( vertex ∈ _cycleDetector ) {
throw Exception( "A cycle involving vertices {} found!".format( _cycleDetector ) );
}
if ( vertex ∉ _visited ) {
run( graph_, vertex );
}
}
_postOrder.push( start_ );
_cycleDetector.erase( start_ );
}
topological_sort( graph_ ) {
for ( vertex : graph_._adjecentVertices ) {
if ( vertex ∉ _visited ) {
run( graph_, vertex );
}
}
return ( _postOrder );
}
}
main() {
rawdata =
"des_system_lib | std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 | ieee dw01 dware gtech\n"
"dw02 | ieee dw02 dware\n"
"dw03 | std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 | dw04 ieee dw01 dware gtech\n"
"dw05 | dw05 ieee dware\n"
"dw06 | dw06 ieee dware\n"
"dw07 | ieee dware\n"
"dware | ieee dware\n"
"gtech | ieee gtech\n"
"ramlib | std ieee\n"
"std_cell_lib | ieee std_cell_lib\n"
"synopsys |\n";
dg = DirectedGraph();
for ( l : algo.filter( text.split( rawdata, "\n" ), @( x ) { size( x ) > 0; } ) ) {
def = algo.materialize( algo.map( text.split( l, "|" ), string.strip ), list );
dg.add_vertex( def[0] );
for ( n : algo.filter( algo.map( text.split( def[1], " " ), string.strip ), @( x ) { size( x ) > 0; } ) ) {
dg.add_edge( def[0], n );
}
}
dfs = DepthFirstSearch();
print( "{}\n".format( dfs.topological_sort( dg ) ) );
} |
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.
| #Nim | Nim | import strutils, tables
proc runUTM(state, halt, blank: string, tape: seq[string] = @[],
rules: seq[seq[string]]) =
var
st = state
pos = 0
tape = tape
rulesTable: Table[tuple[s0, v0: string], tuple[v1, dr, s1: string]]
if tape.len == 0: tape = @[blank]
if pos < 0: pos += tape.len
assert pos in 0..tape.high
for r in rules:
assert r.len == 5
rulesTable[(r[0], r[1])] = (r[2], r[3], r[4])
while true:
stdout.write st, '\t'
for i, v in tape:
stdout.write if i == pos: '[' & v & ']' else: ' ' & v & ' '
echo()
if st == halt: break
if not rulesTable.hasKey((st, tape[pos])): break
let (v1, dr, s1) = rulesTable[(st, tape[pos])]
tape[pos] = v1
if dr == "left":
if pos > 0: dec pos
else: tape.insert blank
if dr == "right":
inc pos
if pos >= tape.len: tape.add blank
st = s1
echo "incr machine\n"
runUTM(halt = "qf",
state = "q0",
tape = "1 1 1".split,
blank = "B",
rules = @["q0 1 1 right q0".splitWhitespace,
"q0 B 1 stay qf".splitWhitespace])
echo "\nbusy beaver\n"
runUTM(halt = "halt",
state = "a",
blank = "0",
rules = @["a 0 1 right b".splitWhitespace,
"a 1 1 left c".splitWhitespace,
"b 0 1 left a".splitWhitespace,
"b 1 1 right b".splitWhitespace,
"c 0 1 left b".splitWhitespace,
"c 1 1 stay halt".splitWhitespace])
echo "\nsorting test\n"
runUTM(halt = "STOP",
state = "A",
blank = "0",
tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split,
rules = @["A 1 1 right A".splitWhitespace,
"A 2 3 right B".splitWhitespace,
"A 0 0 left E".splitWhitespace,
"B 1 1 right B".splitWhitespace,
"B 2 2 right B".splitWhitespace,
"B 0 0 left C".splitWhitespace,
"C 1 2 left D".splitWhitespace,
"C 2 2 left C".splitWhitespace,
"C 3 2 left E".splitWhitespace,
"D 1 1 left D".splitWhitespace,
"D 2 2 left D".splitWhitespace,
"D 3 1 right A".splitWhitespace,
"E 1 1 left E".splitWhitespace,
"E 0 0 right STOP".splitWhitespace]) |
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).
| #Pascal | Pascal | {$IFDEF FPC}
{$MODE DELPHI}
{$IFEND}
function gcd_mod(u, v: NativeUint): NativeUint;inline;
//prerequisites u > v and u,v > 0
var
t: NativeUInt;
begin
repeat
t := u;
u := v;
v := t mod v;
until v = 0;
gcd_mod := u;
end;
function Totient(n:NativeUint):NativeUint;
var
i : NativeUint;
Begin
result := 1;
For i := 2 to n do
inc(result,ORD(GCD_mod(n,i)=1));
end;
function CheckPrimeTotient(n:NativeUint):Boolean;inline;
begin
result := (Totient(n) = (n-1));
end;
procedure OutCountPrimes(n:NativeUInt);
var
i,cnt : NativeUint;
begin
cnt := 0;
For i := 1 to n do
inc(cnt,Ord(CheckPrimeTotient(i)));
writeln(n:10,cnt:8);
end;
procedure display(n:NativeUint);
var
idx,phi : NativeUint;
Begin
if n = 0 then
EXIT;
writeln('number n':5,'Totient(n)':11,'isprime':8);
For idx := 1 to n do
Begin
phi := Totient(idx);
writeln(idx:4,phi:10,(phi=(idx-1)):12);
end
end;
var
i : NativeUint;
Begin
display(25);
writeln('Limit primecount');
i := 100;
repeat
OutCountPrimes(i);
i := i*10;
until i >100000;
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
| #Wren | Wren | import "/fmt" for Fmt
var maxn = 10
var maxl = 50
var steps = Fn.new { |n|
var a = List.filled(maxl, null)
var b = List.filled(maxl, null)
var x = List.filled(maxl, 0)
for (i in 0...maxl) {
a[i] = List.filled(maxn + 1, 0)
b[i] = List.filled(maxn + 1, 0)
}
a[0][0] = 1
var m = 0
var l = 0
while (true) {
x[l] = x[l] + 1
var k = x[l]
var cont = false
if (k >= n) {
if (l <= 0) break
l = l - 1
cont = true
} else if (a[l][k] == 0) {
if (b[l][k+1] != 0) cont = true
} else if (a[l][k] != k + 1) {
cont = true
}
if (!cont) {
a[l+1] = a[l].toList
var j = 1
while (j <= k) {
a[l+1][j] = a[l][k-j]
j = j + 1
}
b[l+1] = b[l].toList
a[l+1][0] = k + 1
b[l+1][k+1] = 1
if (l > m - 1) {
m = l + 1
}
l = l + 1
x[l] = 0
}
}
return m
}
for (i in 1..maxn) Fmt.print("$2d: $d", i, steps.call(i)) |
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #Go | Go | package main
import (
"fmt"
"math"
)
const d = 30.
const r = d * math.Pi / 180
var s = .5
var c = math.Sqrt(3) / 2
var t = 1 / math.Sqrt(3)
func main() {
fmt.Printf("sin(%9.6f deg) = %f\n", d, math.Sin(d*math.Pi/180))
fmt.Printf("sin(%9.6f rad) = %f\n", r, math.Sin(r))
fmt.Printf("cos(%9.6f deg) = %f\n", d, math.Cos(d*math.Pi/180))
fmt.Printf("cos(%9.6f rad) = %f\n", r, math.Cos(r))
fmt.Printf("tan(%9.6f deg) = %f\n", d, math.Tan(d*math.Pi/180))
fmt.Printf("tan(%9.6f rad) = %f\n", r, math.Tan(r))
fmt.Printf("asin(%f) = %9.6f deg\n", s, math.Asin(s)*180/math.Pi)
fmt.Printf("asin(%f) = %9.6f rad\n", s, math.Asin(s))
fmt.Printf("acos(%f) = %9.6f deg\n", c, math.Acos(c)*180/math.Pi)
fmt.Printf("acos(%f) = %9.6f rad\n", c, math.Acos(c))
fmt.Printf("atan(%f) = %9.6f deg\n", t, math.Atan(t)*180/math.Pi)
fmt.Printf("atan(%f) = %9.6f rad\n", t, math.Atan(t))
} |
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).
| #PureBasic | PureBasic | Procedure.d f(x.d)
ProcedureReturn Pow(Abs(x), 0.5) + 5 * x * x * x
EndProcedure
Procedure split(i.s, delimeter.s, List o.d())
Protected index = CountString(i, delimeter) + 1 ;add 1 because last entry will not have a delimeter
While index > 0
AddElement(o())
o() = ValD(Trim(StringField(i, index, delimeter)))
index - 1
Wend
ProcedureReturn ListSize(o())
EndProcedure
Define i$, entriesAreValid = 0, result.d, output$
NewList numbers.d()
If OpenConsole()
Repeat
PrintN(#crlf$ + "Enter eleven numbers that are each separated by spaces or commas:")
i$ = Input(
i$ = Trim(i$)
If split(i$, ",", numbers.d()) < 11
ClearList(numbers())
If split(i$, " ", numbers.d()) < 11
PrintN("Not enough numbers were supplied.")
ClearList(numbers())
Else
entriesAreValid = 1
EndIf
Else
entriesAreValid = 1
EndIf
Until entriesAreValid = 1
ForEach numbers()
output$ = "f(" + RTrim(RTrim(StrD(numbers(), 3), "0"), ".") + ") = "
result.d = f(numbers())
If result > 400
output$ + "Too Large"
Else
output$ + RTrim(RTrim(StrD(result, 3), "0"), ".")
EndIf
PrintN(output$)
Next
Print(#crlf$ + #crlf$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf |
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.]
| #Prolog | Prolog | largest_left_truncatable_prime(N, N):-
is_left_truncatable_prime(N),
!.
largest_left_truncatable_prime(N, P):-
N > 1,
N1 is N - 1,
largest_left_truncatable_prime(N1, P).
is_left_truncatable_prime(P):-
is_prime(P),
is_left_truncatable_prime(P, P, 10).
is_left_truncatable_prime(P, _, N):-
P =< N,
!.
is_left_truncatable_prime(P, Q, N):-
Q1 is P mod N,
is_prime(Q1),
Q \= Q1,
N1 is N * 10,
is_left_truncatable_prime(P, Q1, N1).
largest_right_truncatable_prime(N, N):-
is_right_truncatable_prime(N),
!.
largest_right_truncatable_prime(N, P):-
N > 1,
N1 is N - 1,
largest_right_truncatable_prime(N1, P).
is_right_truncatable_prime(P):-
is_prime(P),
Q is P // 10,
(Q == 0, ! ; is_right_truncatable_prime(Q)).
main(N):-
find_prime_numbers(N),
largest_left_truncatable_prime(N, L),
writef('Largest left-truncatable prime less than %t: %t\n', [N, L]),
largest_right_truncatable_prime(N, R),
writef('Largest right-truncatable prime less than %t: %t\n', [N, R]).
main:-
main(1000000). |
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.
| #Eiffel | Eiffel | note
description : "Application for tree traversal demonstration"
output : "[
Prints preorder, inorder, postorder and levelorder traversal of an example binary tree.
]"
author : "Jascha Grübel"
date : "$2014-01-07$"
revision : "$1.0$"
class
APPLICATION
create
make
feature {NONE} -- Initialization
make
-- Run Tree traversal example.
local
tree:NODE
do
create tree.make (1)
tree.set_left_child (create {NODE}.make (2))
tree.set_right_child (create {NODE}.make (3))
tree.left_child.set_left_child (create {NODE}.make (4))
tree.left_child.set_right_child (create {NODE}.make (5))
tree.left_child.left_child.set_left_child (create {NODE}.make (7))
tree.right_child.set_left_child (create {NODE}.make (6))
tree.right_child.left_child.set_left_child (create {NODE}.make (8))
tree.right_child.left_child.set_right_child (create {NODE}.make (9))
Io.put_string ("preorder: ")
tree.print_preorder
Io.put_new_line
Io.put_string ("inorder: ")
tree.print_inorder
Io.put_new_line
Io.put_string ("postorder: ")
tree.print_postorder
Io.put_new_line
Io.put_string ("level-order:")
tree.print_levelorder
Io.put_new_line
end
end -- class APPLICATION |
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
| #Clojure | Clojure | (apply str (interpose "." (.split #"," "Hello,How,Are,You,Today"))) |
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
| #CLU | CLU | % This iterator splits the string on a given character,
% and returns each substring in order.
tokenize = iter (s: string, c: char) yields (string)
while ~string$empty(s) do
next: int := string$indexc(c, s)
if next = 0 then
yield(s)
break
else
yield(string$substr(s, 1, next-1))
s := string$rest(s, next+1)
end
end
end tokenize
start_up = proc ()
po: stream := stream$primary_output()
str: string := "Hello,How,Are,You,Today"
for part: string in tokenize(str, ',') do
stream$putl(po, part || ".")
end
end start_up |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #C.23 | C# | using System;
using System.Linq;
using System.Threading;
using System.Diagnostics;
class Program {
static void Main(string[] args) {
Stopwatch sw = new Stopwatch();
sw.Start();
DoSomething();
sw.Stop();
Console.WriteLine("DoSomething() took {0}ms.", sw.Elapsed.TotalMilliseconds);
}
static void DoSomething() {
Thread.Sleep(1000);
Enumerable.Range(1, 10000).Where(x => x % 2 == 0).Sum(); // Sum even numers from 1 to 10000
}
} |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #C.2B.2B | C++ | #include <ctime>
#include <iostream>
using namespace std;
int identity(int x) { return x; }
int sum(int num) {
for (int i = 0; i < 1000000; i++)
num += i;
return num;
}
double time_it(int (*action)(int), int arg) {
clock_t start_time = clock();
action(arg);
clock_t finis_time = clock();
return ((double) (finis_time - start_time)) / CLOCKS_PER_SEC;
}
int main() {
cout << "Identity(4) takes " << time_it(identity, 4) << " seconds." << endl;
cout << "Sum(4) takes " << time_it(sum, 4) << " seconds." << endl;
return 0;
} |
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
| #EchoLisp | EchoLisp |
(lib 'struct) ;; tables are based upon structures
(lib 'sql) ;; sql-select function
;; input table
(define emps (make-table (struct emp (name id salary dept))))
;; output table
(define high (make-table (struct out (dept name salary))))
;; sort/group procedure
(define (get-high num-records: N into: high)
(sql-select emp.dept emp.name emp.salary
from emps
group-by emp.dept
order-by emp.salary desc limit N into high))
|
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #Befunge | Befunge | v123456789 --- >9 >48*,:55+\-0g,1v
>9>066+0p076+0p^ ^,," |"_v#%3:- <
:,,0537051v>:#,_$#^5#,5#+<>:#v_55+
74 1098709<^+55"---+---+---"0<v520
69 04560123 >:!#v_0\1v>$2-:6%v>803
6 +0g\66++0p^ $_>#% v#9:-1_ 6/5
5 vv5!/*88\%*28 ::g0_^>9/#v_ "I",
,,5v>5++0p82*/3-:*+\:^v,_@ >"uoY",
0+5<v0+66_v#!%2:_55v >:^:" win!"\
1-^ g >$>0" :evom ruoY">:#,_$v>p
\*8+ 65_^#!/*88g0** `0\!`9:::<&<^0
v >:!67+0g:!56+0g *+*+0" :evom "
>"yM">:#,_$ :. 1234+++, 789*+ \0^<
"a s't"98:*+>:#,_$@>365*+"ward"48*
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #BCPL | BCPL | get "libhdr"
let start() be move(4, 1, 2, 3)
and move(n, src, via, dest) be if n > 0 do
$( move(n-1, src, dest, via)
writef("Move disk from pole %N to pole %N*N", src, dest);
move(n-1, via, src, dest)
$) |
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
| #jq | jq | def thueMorse:
0,
({sb0: "0", sb1: "1", n:1 }
| while( true;
{n: (.sb0|length),
sb0: (.sb0 + .sb1),
sb1: (.sb1 + .sb0)} )
| .sb0[.n:]
| explode[]
| . - 48); |
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
| #Julia | Julia | function thuemorse(len::Int)
rst = Vector{Int8}(len)
rst[1] = 0
i, imax = 2, 1
while i ≤ len
while i ≤ len && i ≤ 2 * imax
rst[i] = 1 - rst[i-imax]
i += 1
end
imax *= 2
end
return rst
end
println(join(thuemorse(100))) |
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
| #Kotlin | Kotlin | fun thueMorse(n: Int): String {
val sb0 = StringBuilder("0")
val sb1 = StringBuilder("1")
repeat(n) {
val tmp = sb0.toString()
sb0.append(sb1)
sb1.append(tmp)
}
return sb0.toString()
}
fun main() {
for (i in 0..6) println("$i : ${thueMorse(i)}")
} |
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
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Numerics
Module Module1
Class Solution
ReadOnly root1 As BigInteger
ReadOnly root2 As BigInteger
ReadOnly exists As Boolean
Sub New(r1 As BigInteger, r2 As BigInteger, e As Boolean)
root1 = r1
root2 = r2
exists = e
End Sub
Public Function GetRoot1() As BigInteger
Return root1
End Function
Public Function GetRoot2() As BigInteger
Return root2
End Function
Public Function GetExists() As Boolean
Return exists
End Function
End Class
Function Ts(n As BigInteger, p As BigInteger) As Solution
If BigInteger.ModPow(n, (p - 1) / 2, p) <> 1 Then
Return New Solution(0, 0, False)
End If
Dim q As BigInteger = p - 1
Dim ss = BigInteger.Zero
While (q Mod 2) = 0
ss += 1
q >>= 1
End While
If ss = 1 Then
Dim r1 = BigInteger.ModPow(n, (p + 1) / 4, p)
Return New Solution(r1, p - r1, True)
End If
Dim z As BigInteger = 2
While BigInteger.ModPow(z, (p - 1) / 2, p) <> p - 1
z += 1
End While
Dim c = BigInteger.ModPow(z, q, p)
Dim r = BigInteger.ModPow(n, (q + 1) / 2, p)
Dim t = BigInteger.ModPow(n, q, p)
Dim m = ss
Do
If t = 1 Then
Return New Solution(r, p - r, True)
End If
Dim i = BigInteger.Zero
Dim zz = t
While zz <> 1 AndAlso i < (m - 1)
zz = zz * zz Mod p
i += 1
End While
Dim b = c
Dim e = m - i - 1
While e > 0
b = b * b Mod p
e = e - 1
End While
r = r * b Mod p
c = b * b Mod p
t = t * c Mod p
m = i
Loop
End Function
Sub Main()
Dim pairs = New List(Of Tuple(Of Long, Long)) From {
New Tuple(Of Long, Long)(10, 13),
New Tuple(Of Long, Long)(56, 101),
New Tuple(Of Long, Long)(1030, 10009),
New Tuple(Of Long, Long)(1032, 10009),
New Tuple(Of Long, Long)(44402, 100049),
New Tuple(Of Long, Long)(665820697, 1000000009),
New Tuple(Of Long, Long)(881398088036, 1000000000039)
}
For Each pair In pairs
Dim sol = Ts(pair.Item1, pair.Item2)
Console.WriteLine("n = {0}", pair.Item1)
Console.WriteLine("p = {0}", pair.Item2)
If sol.GetExists() Then
Console.WriteLine("root1 = {0}", sol.GetRoot1())
Console.WriteLine("root2 = {0}", sol.GetRoot2())
Else
Console.WriteLine("No solution exists")
End If
Console.WriteLine()
Next
Dim bn = BigInteger.Parse("41660815127637347468140745042827704103445750172002")
Dim bp = BigInteger.Pow(10, 50) + 577
Dim bsol = Ts(bn, bp)
Console.WriteLine("n = {0}", bn)
Console.WriteLine("p = {0}", bp)
If bsol.GetExists() Then
Console.WriteLine("root1 = {0}", bsol.GetRoot1())
Console.WriteLine("root2 = {0}", bsol.GetRoot2())
Else
Console.WriteLine("No solution exists")
End If
End Sub
End Module |
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
| #Kotlin | Kotlin | // version 1.1.3
const val SPE = "\ufffe" // unused unicode char in Specials block
const val SPF = "\uffff" // ditto
fun tokenize(str: String, sep: Char, esc: Char): List<String> {
var s = str.replace("$esc$esc", SPE).replace("$esc$sep", SPF)
s = if (s.last() == esc) // i.e. 'esc' not escaping anything
s.dropLast(1).replace("$esc", "") + esc
else
s.replace("$esc", "")
return s.split(sep).map { it.replace(SPE, "$esc").replace(SPF, "$sep") }
}
fun main(args: Array<String>) {
var str = "one^|uno||three^^^^|four^^^|^cuatro|"
val sep = '|'
val esc = '^'
val items = tokenize(str, sep, esc)
for (item in items) println(if (item.isEmpty()) "(empty)" else item)
} |
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
| #zkl | zkl | circles:=File("circles.txt").pump(List,'wrap(line){
line.split().apply("toFloat") // L(x,y,r)
});
# compute the bounding box of the circles
x_min:=(0.0).min(circles.apply(fcn([(x,y,r)]){ x - r })); // (0) not used, just the list of numbers
x_max:=(0.0).max(circles.apply(fcn([(x,y,r)]){ x + r }));
y_min:=(0.0).min(circles.apply(fcn([(x,y,r)]){ y - r }));
y_max:=(0.0).max(circles.apply(fcn([(x,y,r)]){ y + r }));
box_side:=500;
dx:=(x_max - x_min)/box_side;
dy:=(y_max - y_min)/box_side;
count:=0;
foreach r in (box_side){
y:=y_min + dy*r;
foreach c in (box_side){
x:=x_min + dx*c;
count+=circles.filter1('wrap([(cx,cy,cr)]){
x-=cx; y-=cy;
x*x + y*y <= cr*cr
}).toBool(); // -->False|L(x,y,z), L(x,y,r).toBool()-->True,
}
}
println("Approximated area: ", dx*dy*count); |
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]
| #Icon_and_Unicon | Icon and Unicon | record graph(nodes,arcs)
global ex_name, in_name
procedure main()
show(tsort(getgraph()))
end
procedure tsort(g)
t := ""
while (n := g.nodes -- pnodes(g)) ~== "" do {
t ||:= "("||n||")"
g := delete(g,n)
}
if g.nodes == '' then return t
write("graph contains the cycle:")
write("\t",genpath(fn := !g.nodes,fn,g))
end
## pnodes(g) -- return the predecessor nodes of g
# (those that have an arc from them)
procedure pnodes(g)
static labels, fromnodes
initial {
labels := &ucase
fromnodes := 'ACEGIKMOQSUWY'
}
return cset(select(g.arcs,labels, fromnodes))
end
## select(s,image,object) - efficient node selection
procedure select(s,image,object)
slen := *s
ilen := *image
return if slen <= ilen then map(object[1+:slen/2],image[1+:slen],s)
else map(object,image,s[1+:ilen]) || select(s[1+ilen:0],image,object)
end
## delete(g,x) -- deletes all nodes in x from graph g
# note that arcs must be deleted as well
procedure delete(g,x)
t := ""
g.arcs ? while arc := move(2) do if not upto(x,arc) then t ||:= arc
return graph(g.nodes--x,t)
end
## getgraph() -- read and construct a graph
# graph is described via sets of arcs, as in:
#
# from to1 to2 to3
#
# external names are converted to single character names for efficiency
# self-referential arcs are ignored
procedure getgraph()
static labels
initial labels := &cset
ex_name := table()
in_name := table()
count := 0
arcstr := ""
nodes := ''
every line := !&input do {
nextWord := create genWords(line)
if nfrom := @nextWord then {
/in_name[nfrom] := &cset[count +:= 1]
/ex_name[in_name[nfrom]] := nfrom
nodes ++:= in_name[nfrom]
while nto := @nextWord do {
if nfrom ~== nto then {
/in_name[nto] := &cset[count +:= 1]
/ex_name[in_name[nto]] := nto
nodes ++:= in_name[nto]
arcstr ||:= in_name[nfrom] || in_name[nto]
}
}
}
}
return graph(nodes,arcstr)
end
# generate all 'words' in string
procedure genWords(s)
static wchars
initial wchars := &cset -- ' \t'
s ? while tab(upto(wchars))\1 do suspend tab(many(wchars))\1
end
## show(t) - return the external names (in order) for the nodes in t
# Each output line contains names that are independent of each other
procedure show(t)
line := ""
every n := !t do
case n of {
"(" : line ||:= "\n\t("
")" : line[-1] := ")"
default : line ||:= ex_name[n] || " "
}
write(line)
end
## genpath(f,t,g) -- generate paths from f to t in g
procedure genpath(f,t,g, seen)
/seen := ''
seen ++:= f
sn := nnodes(f,g)
if t ** sn == t then return ex_name[f] || " -> " || ex_name[t]
suspend ex_name[f] || " -> " || genpath(!(sn --seen),t,g,seen)
end
## nnodes(f,g) -- compute all nodes that could follow f in g
procedure nnodes(f,g)
t := ''
g.arcs ? while arc := move(2) do if arc[1] == f then t ++:= arc[2]
return t
end |
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.
| #Pascal | Pascal | program project1;
uses
Classes, sysutils;
type
TCurrent = record
state : string;
input : char;
end;
TMovesTo = record
state : string;
output : char;
moves : char;
end;
var
ST, ET: TDateTime;
C:TCurrent;
M:TMovesTo;
Tape, Rules:TStringList;
TP:integer; //TP = Tape position
Blank : char;
j:integer;
FinalState, InitialState, R : string;
Count:integer;
Function ApplyRule(C:TCurrent):TMovesTo;
var
x,k:integer;
begin
//Find the appropriate rule and pass it as the result
For k:= 0 to Rules.Count-1 do
begin
If (k mod 5 = 0) and (Rules[k] = C.state) and (Rules[k+1] = C.input) then
begin
Result.output := Rules[k+2][1];
Result.moves := Rules[k+3][1];
Result.state := Rules[k+4];
end;
end;
end;
Procedure ChangeTape(var TapePosition:integer;N:TMovesTo);
begin
Tape[TapePosition]:=N.output;
Case N.moves of
'l':begin
TapePosition := TapePosition-1;
end;
'r':begin
TapePosition := TapePosition+1;
end;
end;
end;
function GetInput(TapePosition:integer):char;
begin
Result:=Tape[TapePosition][1];
end;
procedure ShowResult;
var
k:integer;
begin
writeln('Current State :',C.state);
writeln('Input :',C.input);
write(' Tape ');
For k:= 0 to Tape.count-1 do
begin
write(Tape[k]);
end;
writeln;
writeln('New State :',M.state);
writeln('Tape position :',TP);
writeln('-----------------------');
end;
begin
writeln('Universal Turing Machine');
writeln('------------------------');
Count:=0;
ST:=Time;
//Set up the rules
Rules := TStringList.create;
R := 'q0,1,1,right,q0,q0,B,1,stay,qf';
Rules.CommaText := R;
InitialState := 'q0';
FinalState := 'qf';
//Set up the tape
Tape:=TStringList.create;
Tape.add('1');
Tape.add('1');
Tape.add('1');
Blank := 'B';
For j:= 1 to 10 do
begin
Tape.add(Blank);
end;
//Set up the initial state
writeln('Initial state');
C.state:=InitialState;
C.input:=' ';
M.state:='';
M.output:=' ';
M.moves:=' ';
TP:=0;
//Run the machine
While (TP >= 0) and (M.State <> FinalState) do
begin
C.Input := GetInput(TP);
If M.state <> '' then
begin
C.State := M.State;
end;
M:=ApplyRule(C);
ChangeTape(TP,M);
Count:=Count+1;
ShowResult;
end;
//State the outcome.
If TP < 0 then
begin
writeln('Error! Tape has slipped off at left!');
end;
If M.state = FinalState then
begin
writeln('Program has finished');
ET:=Time;
writeln('Time taken ');
writeln(FormatDateTime('sss:zzz',ET-ST));
writeln(Count, ' steps taken');
end;
Tape.free;
Rules.free;
readln;
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).
| #Perl | Perl | use utf8;
binmode STDOUT, ":utf8";
sub gcd {
my ($u, $v) = @_;
while ($v) {
($u, $v) = ($v, $u % $v);
}
return abs($u);
}
push @𝜑, 0;
for $t (1..10000) {
push @𝜑, scalar grep { 1 == gcd($_,$t) } 1..$t;
}
printf "𝜑(%2d) = %3d%s\n", $_, $𝜑[$_], $_ - $𝜑[$_] - 1 ? '' : ' Prime' for 1 .. 25;
print "\n";
for $limit (100, 1000, 10000) {
printf "Count of primes <= $limit: %d\n", scalar grep {$_ == $𝜑[$_] + 1} 0..$limit;
}
|
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
| #XPL0 | XPL0 | code ChOut=8, CrLf=9, IntOut=11;
int N, Max, Card1(16), Card2(16);
proc Topswop(D); \Conway's card swopping game
int D; \depth of recursion
int I, J, C, T;
[if D # N then \generate N! permutations of 1..N in Card1
[for I:= 0 to N-1 do
[for J:= 0 to D-1 do \check if object (letter) already used
if Card1(J) = I+1 then J:=100;
if J < 100 then
[Card1(D):= I+1; \card number not used so append it
Topswop(D+1); \recurse next level deeper
];
];
]
else [\determine number of topswops to get card 1 at beginning
for I:= 0 to N-1 do Card2(I):= Card1(I); \make working copy of deck
C:= 0; \initialize swop counter
while Card2(0) # 1 do
[I:= 0; J:= Card2(0)-1;
while I < J do
[T:= Card2(I); Card2(I):= Card2(J); Card2(J):= T;
I:= I+1; J:= J-1;
];
C:= C+1;
];
if C>Max then Max:= C;
];
];
[for N:= 1 to 10 do
[Max:= 0;
Topswop(0);
IntOut(0, N); ChOut(0, ^ ); IntOut(0, Max); CrLf(0);
];
] |
http://rosettacode.org/wiki/Topswops | Topswops | Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is composed of reversing the first m cards where m is the value of the topmost card.
Rounds are repeated until the topmost card is the number 1 and the number of swaps is recorded.
For our example the swaps produce:
[2, 4, 1, 3] # Initial shuffle
[4, 2, 1, 3]
[3, 1, 2, 4]
[2, 1, 3, 4]
[1, 2, 3, 4]
For a total of four swaps from the initial ordering to produce the terminating case where 1 is on top.
For a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards.
Task
The task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive.
Note
Topswops is also known as Fannkuch from the German word Pfannkuchen meaning pancake.
Related tasks
Number reversal game
Sorting algorithms/Pancake sort
| #zkl | zkl | fcn topswops(n){
flip:=fcn(xa){
if (not xa[0]) return(0);
xa.reverse(0,xa[0]+1); // inplace, ~4x faster than making new lists
return(1 + self.fcn(xa));
};
(0).pump(n,List):Utils.Helpers.permute(_).pump(List,"copy",flip).reduce("max");
}
foreach n in ([1 .. 10]){ println(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.
| #Groovy | Groovy | def radians = Math.PI/4
def degrees = 45
def d2r = { it*Math.PI/180 }
def r2d = { it*180/Math.PI }
println "sin(\u03C0/4) = ${Math.sin(radians)} == sin(45\u00B0) = ${Math.sin(d2r(degrees))}"
println "cos(\u03C0/4) = ${Math.cos(radians)} == cos(45\u00B0) = ${Math.cos(d2r(degrees))}"
println "tan(\u03C0/4) = ${Math.tan(radians)} == tan(45\u00B0) = ${Math.tan(d2r(degrees))}"
println "asin(\u221A2/2) = ${Math.asin(2**(-0.5))} == asin(\u221A2/2)\u00B0 = ${r2d(Math.asin(2**(-0.5)))}\u00B0"
println "acos(\u221A2/2) = ${Math.acos(2**(-0.5))} == acos(\u221A2/2)\u00B0 = ${r2d(Math.acos(2**(-0.5)))}\u00B0"
println "atan(1) = ${Math.atan(1)} == atan(1)\u00B0 = ${r2d(Math.atan(1))}\u00B0" |
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).
| #Python | Python | Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> def f(x): return abs(x) ** 0.5 + 5 * x**3
>>> print(', '.join('%s:%s' % (x, v if v<=400 else "TOO LARGE!")
for x,v in ((y, f(float(y))) for y in input('\nnumbers: ').strip().split()[:11][::-1])))
11 numbers: 1 2 3 4 5 6 7 8 9 10 11
11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0
>>> |
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).
| #R | R | S <- scan(n=11)
f <- function(x) sqrt(abs(x)) + 5*x^3
for (i in rev(S)) {
res <- f(i)
if (res > 400)
print("Too large!")
else
print(res)
} |
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.]
| #PureBasic | PureBasic | #MaxLim = 999999
Procedure is_Prime(n)
If n<=1 : ProcedureReturn #False
ElseIf n<4 : ProcedureReturn #True
ElseIf n%2=0: ProcedureReturn #False
ElseIf n<9 : ProcedureReturn #True
ElseIf n%3=0: ProcedureReturn #False
Else
Protected r=Round(Sqr(n),#PB_Round_Down)
Protected f=5
While f<=r
If n%f=0 Or n%(f+2)=0
ProcedureReturn #False
EndIf
f+6
Wend
EndIf
ProcedureReturn #True
EndProcedure
Procedure TruncateLeft(n)
Protected s.s=Str(n), l=Len(s)-1
If Not FindString(s,"0",1)
While l>0
s=Right(s,l)
If Not is_Prime(Val(s))
ProcedureReturn #False
EndIf
l-1
Wend
ProcedureReturn #True
EndIf
EndProcedure
Procedure TruncateRight(a)
Repeat
a/10
If Not a
Break
ElseIf Not is_Prime(a) Or a%10=0
ProcedureReturn #False
EndIf
ForEver
ProcedureReturn #True
EndProcedure
i=#MaxLim
Repeat
If is_Prime(i)
If Not truncateleft And TruncateLeft(i)
truncateleft=i
EndIf
If Not truncateright And TruncateRight(i)
truncateright=i
EndIf
EndIf
If truncateleft And truncateright
Break
Else
i-2
EndIf
Until i<=0
x.s="Largest TruncateLeft= "+Str(truncateleft)
y.s="Largest TruncateRight= "+Str(truncateright)
MessageRequester("Truncatable primes",x+#CRLF$+y) |
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.
| #Elena | Elena | import extensions;
import extensions'routines;
import system'collections;
singleton DummyNode
{
get generic()
= EmptyEnumerable;
}
class Node
{
rprop int Value;
rprop Node Left;
rprop Node Right;
constructor new(int value)
{
Value := value
}
constructor new(int value, Node left)
{
Value := value;
Left := left;
}
constructor new(int value, Node left, Node right)
{
Value := value;
Left := left;
Right := right
}
Preorder = new Enumerable
{
Enumerator enumerator() = CompoundEnumerator.new(
SingleEnumerable.new(Value),
(Left ?? DummyNode).Preorder,
(Right ?? DummyNode).Preorder);
};
Inorder = new Enumerable
{
Enumerator enumerator()
{
if (nil != Left)
{
^ CompoundEnumerator.new(Left.Inorder, SingleEnumerable.new(Value), (Right ?? DummyNode).Inorder)
}
else
{
^ SingleEnumerable.new(Value).enumerator()
}
}
};
Postorder = new Enumerable
{
Enumerator enumerator()
{
if (nil == Left)
{
^ SingleEnumerable.new(Value).enumerator()
}
else if (nil == Right)
{
^ CompoundEnumerator.new(Left.Postorder, SingleEnumerable.new(Value))
}
else
{
^ CompoundEnumerator.new(Left.Postorder, Right.Postorder, SingleEnumerable.new(Value))
}
}
};
LevelOrder = new Enumerable
{
Queue<Node> queue := class Queue<Node>.allocate(4).push:self;
Enumerator enumerator() = new Enumerator
{
bool next() = queue.isNotEmpty();
get()
{
Node item := queue.pop();
Node left := item.Left;
Node right := item.Right;
if (nil != left)
{
queue.push(left)
};
if (nil != right)
{
queue.push(right)
};
^ item.Value
}
reset()
{
NotSupportedException.raise()
}
enumerable() = queue;
};
};
}
public program()
{
var tree := Node.new(1, Node.new(2, Node.new(4, Node.new(7)), Node.new(5)), Node.new(3, Node.new(6, Node.new(8), Node.new(9))));
console.printLine("Preorder :", tree.Preorder);
console.printLine("Inorder :", tree.Inorder);
console.printLine("Postorder :", tree.Postorder);
console.printLine("LevelOrder:", tree.LevelOrder)
} |
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
| #COBOL | COBOL |
identification division.
program-id. tokenize.
environment division.
configuration section.
repository.
function all intrinsic.
data division.
working-storage section.
01 period constant as ".".
01 cmma constant as ",".
01 start-with.
05 value "Hello,How,Are,You,Today".
01 items.
05 item pic x(6) occurs 5 times.
procedure division.
tokenize-main.
unstring start-with delimited by cmma
into item(1) item(2) item(3) item(4) item(5)
display trim(item(1)) period trim(item(2)) period
trim(item(3)) period trim(item(4)) period
trim(item(5))
goback.
end program tokenize.
|
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Clojure | Clojure |
(defn fib []
(map first
(iterate
(fn [[a b]] [b (+ a b)])
[0 1])))
(time (take 100 (fib)))
|
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Common_Lisp | Common Lisp | CL-USER> (time (reduce #'+ (make-list 100000 :initial-element 1)))
Evaluation took:
0.151 seconds of real time
0.019035 seconds of user run time
0.01807 seconds of system run time
0 calls to %EVAL
0 page faults and
2,400,256 bytes consed. |
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
| #Elena | Elena | import system'collections;
import system'routines;
import extensions;
import extensions'routines;
import extensions'text;
class Employee
{
prop string Name;
prop string ID;
prop int Salary;
prop string Department;
string toPrintable()
= new StringWriter()
.writePaddingRight(Name, 25)
.writePaddingRight(ID, 12)
.writePaddingRight(Salary.toPrintable(), 12)
.write:Department;
}
extension reportOp
{
topNPerDepartment(n)
= self.groupBy:(x => x.Department ).selectBy:(x)
{
^ new {
Department = x.Key;
Employees
= x.orderBy:(f,l => f.Salary > l.Salary ).top(n).summarize(new ArrayList());
}
};
}
public program()
{
var employees := new Employee[]
{
new Employee{ this Name := "Tyler Bennett"; this ID := "E10297"; this Salary:=32000; this Department:="D101";},
new Employee{ this Name := "John Rappl"; this ID := "E21437"; this Salary:=47000; this Department:="D050";},
new Employee{ this Name := "George Woltman"; this ID := "E00127"; this Salary:=53500; this Department:="D101";},
new Employee{ this Name := "Adam Smith"; this ID := "E63535"; this Salary:=18000; this Department:="D202";},
new Employee{ this Name := "Claire Buckman"; this ID := "E39876"; this Salary:=27800; this Department:="D202";},
new Employee{ this Name := "David McClellan"; this ID := "E04242"; this Salary:=41500; this Department:="D101";},
new Employee{ this Name := "Rich Holcomb"; this ID := "E01234"; this Salary:=49500; this Department:="D202";},
new Employee{ this Name := "Nathan Adams"; this ID := "E41298"; this Salary:=21900; this Department:="D050";},
new Employee{ this Name := "Richard Potter"; this ID := "E43128"; this Salary:=15900; this Department:="D101";},
new Employee{ this Name := "David Motsinger"; this ID := "E27002"; this Salary:=19250; this Department:="D202";},
new Employee{ this Name := "Tim Sampair"; this ID := "E03033"; this Salary:=27000; this Department:="D101";},
new Employee{ this Name := "Kim Arlich"; this ID := "E10001"; this Salary:=57000; this Department:="D190";},
new Employee{ this Name := "Timothy Grove"; this ID := "E16398"; this Salary:=29900; this Department:="D190";}
};
employees.topNPerDepartment:2.forEach:(info)
{
console.printLine("Department: ",info.Department);
info.Employees.forEach:printingLn;
console.writeLine:"---------------------------------------------"
};
console.readChar()
} |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #C | C | #include <stdio.h>
#include <stdlib.h>
int b[3][3]; /* board. 0: blank; -1: computer; 1: human */
int check_winner()
{
int i;
for (i = 0; i < 3; i++) {
if (b[i][0] && b[i][1] == b[i][0] && b[i][2] == b[i][0])
return b[i][0];
if (b[0][i] && b[1][i] == b[0][i] && b[2][i] == b[0][i])
return b[0][i];
}
if (!b[1][1]) return 0;
if (b[1][1] == b[0][0] && b[2][2] == b[0][0]) return b[0][0];
if (b[1][1] == b[2][0] && b[0][2] == b[1][1]) return b[1][1];
return 0;
}
void showboard()
{
const char *t = "X O";
int i, j;
for (i = 0; i < 3; i++, putchar('\n'))
for (j = 0; j < 3; j++)
printf("%c ", t[ b[i][j] + 1 ]);
printf("-----\n");
}
#define for_ij for (i = 0; i < 3; i++) for (j = 0; j < 3; j++)
int best_i, best_j;
int test_move(int val, int depth)
{
int i, j, score;
int best = -1, changed = 0;
if ((score = check_winner())) return (score == val) ? 1 : -1;
for_ij {
if (b[i][j]) continue;
changed = b[i][j] = val;
score = -test_move(-val, depth + 1);
b[i][j] = 0;
if (score <= best) continue;
if (!depth) {
best_i = i;
best_j = j;
}
best = score;
}
return changed ? best : 0;
}
const char* game(int user)
{
int i, j, k, move, win = 0;
for_ij b[i][j] = 0;
printf("Board postions are numbered so:\n1 2 3\n4 5 6\n7 8 9\n");
printf("You have O, I have X.\n\n");
for (k = 0; k < 9; k++, user = !user) {
while(user) {
printf("your move: ");
if (!scanf("%d", &move)) {
scanf("%*s");
continue;
}
if (--move < 0 || move >= 9) continue;
if (b[i = move / 3][j = move % 3]) continue;
b[i][j] = 1;
break;
}
if (!user) {
if (!k) { /* randomize if computer opens, less boring */
best_i = rand() % 3;
best_j = rand() % 3;
} else
test_move(-1, 0);
b[best_i][best_j] = -1;
printf("My move: %d\n", best_i * 3 + best_j + 1);
}
showboard();
if ((win = check_winner()))
return win == 1 ? "You win.\n\n": "I win.\n\n";
}
return "A draw.\n\n";
}
int main()
{
int first = 0;
while (1) printf("%s", game(first = !first));
return 0;
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Befunge | Befunge | 48*2+1>#v_:!#@_0" ksid evoM">:#,_$:8/:.v
>8v8:<$#<+9-+*2%3\*3/3:,+55.+1%3:$_,#!>#:<
: >/!#^_:0\:8/1-8vv,_$8%:3/1+.>0" gep ot"^
^++3-%3\*2/3:%8\*<>:^:"from peg "0\*8-1< |
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
| #Lambdatalk | Lambdatalk |
{def thue_morse
{def thue_morse.r
{lambda {:steps :s1 :s2 :i}
{if {> :i :steps}
then :s1
else {thue_morse.r :steps :s1:s2 :s2:s1 {+ :i 1}}}}}
{lambda {:steps}
{thue_morse.r :steps 0 1 1}}}
-> thue_morse
{thue_morse 6}
-> 0110100110010110100101100110100110010110011010010110100110010110
|
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
| #Lua | Lua | ThueMorse = {sequence = "0"}
function ThueMorse:show ()
print(self.sequence)
end
function ThueMorse:addBlock ()
local newBlock = ""
for bit = 1, self.sequence:len() do
if self.sequence:sub(bit, bit) == "1" then
newBlock = newBlock .. "0"
else
newBlock = newBlock .. "1"
end
end
self.sequence = self.sequence .. newBlock
end
for i = 1, 5 do
ThueMorse:show()
ThueMorse:addBlock()
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
| #Wren | Wren | import "/dynamic" for Tuple
import "/big" for BigInt
var Solution = Tuple.create("Solution", ["root1", "root2", "exists"])
var ts = Fn.new { |n, p|
if (n is Num) n = BigInt.new(n)
if (p is Num) p = BigInt.new(p)
var powModP = Fn.new { |a, e| a.modPow(e, p) }
var ls = Fn.new { |a| powModP.call(a, p.dec / BigInt.two) }
if (ls.call(n) != BigInt.one) return Solution.new(BigInt.zero, BigInt.zero, false)
var q = p.dec
var ss = BigInt.zero
while (q & BigInt.one == BigInt.zero) {
ss = ss.inc
q = q >> 1
}
if (ss == BigInt.one) {
var r1 = powModP.call(n, p.inc / BigInt.four)
return Solution.new(r1, p - r1, true)
}
var z = BigInt.two
while (ls.call(z) != p.dec) z = z.inc
var c = powModP.call(z, q)
var r = powModP.call(n, q.inc/BigInt.two)
var t = powModP.call(n, q)
var m = ss
while (true) {
if (t == BigInt.one) return Solution.new(r, p - r, true)
var i = BigInt.zero
var zz = t
while (zz != BigInt.one && i < m.dec) {
zz = zz * zz % p
i = i.inc
}
var b = c
var e = m - i.inc
while (e > BigInt.zero) {
b = b * b % p
e = e.dec
}
r = r * b % p
c = b * b % p
t = t * c % p
m = i
}
}
var pairs = [
[10, 13], [56, 101], [1030, 10009], [1032, 10009], [44402, 100049],
[665820697, 1000000009], [881398088036, 1000000000039]
]
for (pair in pairs) {
var n = pair[0]
var p = pair[1]
var sol = ts.call(n, p)
System.print("n = %(n)")
System.print("p = %(p)")
if (sol.exists) {
System.print("root1 = %(sol.root1)")
System.print("root2 = %(sol.root2)")
} else {
System.print("No solution exists")
}
System.print()
}
var bn = BigInt.new("41660815127637347468140745042827704103445750172002")
var bp = BigInt.ten.pow(50) + BigInt.new(577)
var bsol = ts.call(bn, bp)
System.print("n = %(bn)")
System.print("p = %(bp)")
if (bsol.exists) {
System.print("root1 = %(bsol.root1)")
System.print("root2 = %(bsol.root2)")
} else {
System.print("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
| #Lingo | Lingo | -- in some movie script
on tokenize (str, sep, esc)
l = []
_player.itemDelimiter = sep
cnt = str.item.count
repeat with i = 1 to cnt
prev = l.getLast() -- can be VOID
if _trailEscCount(prev, esc) mod 2 then
l[l.count] = prev.char[1..prev.length-1]&sep&str.item[i]
else
l.add(str.item[i])
end if
end repeat
-- remove escape characters from tokens
cnt = l.count
repeat with i = 1 to cnt
l[i] = _removeEsc(l[i], esc)
end repeat
return l
end
-- counts number of trailing escape characters
on _trailEscCount (str, esc)
n = 0
repeat with i = str.length down to 1
if str.char[i]=esc then n=n+1
else exit repeat
end repeat
return n
end
-- could be implemented more efficiently by using offset()
on _removeEsc (str, esc)
cnt = str.length-1
repeat with i = 1 to cnt
if str.char[i]=esc then
delete char i of str
cnt = cnt-1
end if
end repeat
return str
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
| #Lua | Lua | function tokenise (str, sep, esc)
local strList, word, escaped, ch = {}, "", false
for pos = 1, #str do
ch = str:sub(pos, pos)
if ch == esc then
if escaped then
word = word .. ch
escaped = false
else
escaped = true
end
elseif ch == sep then
if escaped then
word = word .. ch
escaped = false
else
table.insert(strList, word)
word = ""
end
else
escaped = false
word = word .. ch
end
end
table.insert(strList, word)
return strList
end
local testStr = "one^|uno||three^^^^|four^^^|^cuatro|"
local testSep, testEsc = "|", "^"
for k, v in pairs(tokenise(testStr, testSep, testEsc)) do
print(k, v)
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]
| #J | J | dependencySort=: monad define
parsed=. <@;:;._2 y
names=. {.&>parsed
depends=. (> =@i.@#) names e.S:1 parsed
depends=. (+. +./ .*.~)^:_ depends
assert.-.1 e. (<0 1)|:depends
(-.&names ~.;parsed),names /: +/"1 depends
) |
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.
| #Perl | Perl | use strict;
use warnings;
sub run_utm {
my %o = @_;
my $st = $o{state} // die "init head state undefined";
my $blank = $o{blank} // die "blank symbol undefined";
my @rules = @{$o{rules}} or die "rules undefined";
my @tape = $o{tape} ? @{$o{tape}} : ($blank);
my $halt = $o{halt};
my $pos = $o{pos} // 0;
$pos += @tape if $pos < 0;
die "bad init position" if $pos >= @tape || $pos < 0;
step: while (1) {
print "$st\t";
for (0 .. $#tape) {
my $v = $tape[$_];
print $_ == $pos ? "[$v]" : " $v ";
}
print "\n";
last if $st eq $halt;
for (@rules) {
my ($s0, $v0, $v1, $dir, $s1) = @$_;
next unless $s0 eq $st and $tape[$pos] eq $v0;
$tape[$pos] = $v1;
if ($dir eq 'left') {
if ($pos == 0) { unshift @tape, $blank}
else { $pos-- }
} elsif ($dir eq 'right') {
push @tape, $blank if ++$pos >= @tape
}
$st = $s1;
next step;
}
die "no matching rules";
}
}
print "incr machine\n";
run_utm halt=>'qf',
state=>'q0',
tape=>[1,1,1],
blank=>'B',
rules=>[[qw/q0 1 1 right q0/],
[qw/q0 B 1 stay qf/]];
print "\nbusy beaver\n";
run_utm halt=>'halt',
state=>'a',
blank=>'0',
rules=>[[qw/a 0 1 right b/],
[qw/a 1 1 left c/],
[qw/b 0 1 left a/],
[qw/b 1 1 right b/],
[qw/c 0 1 left b/],
[qw/c 1 1 stay halt/]];
print "\nsorting test\n";
run_utm halt=>'STOP',
state=>'A',
blank=>'0',
tape=>[qw/2 2 2 1 2 2 1 2 1 2 1 2 1 2/],
rules=>[[qw/A 1 1 right A/],
[qw/A 2 3 right B/],
[qw/A 0 0 left E/],
[qw/B 1 1 right B/],
[qw/B 2 2 right B/],
[qw/B 0 0 left C/],
[qw/C 1 2 left D/],
[qw/C 2 2 left C/],
[qw/C 3 2 left E/],
[qw/D 1 1 left D/],
[qw/D 2 2 left D/],
[qw/D 3 1 right A/],
[qw/E 1 1 left E/],
[qw/E 0 0 right STOP/]]; |
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).
| #Phix | Phix | function totient(integer n)
integer tot = n, i = 2
while i*i<=n do
if mod(n,i)=0 then
while true do
n /= i
if mod(n,i)!=0 then exit end if
end while
tot -= tot/i
end if
i += iff(i=2?1:2)
end while
if n>1 then
tot -= tot/n
end if
return tot
end function
printf(1," n phi prime\n")
printf(1," --------------\n")
integer count = 0
for n=1 to 25 do
integer tot = totient(n),
prime = (n-1=tot)
count += prime
string isp = iff(prime?"true":"false")
printf(1,"%2d %2d %s\n",{n,tot,isp})
end for
printf(1,"\nNumber of primes up to 25 = %d\n",count)
for n=26 to 100000 do
count += (totient(n)=n-1)
if find(n,{100,1000,10000,100000}) then
printf(1,"Number of primes up to %-6d = %d\n",{n,count})
end if
end for
|
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.
| #Haskell | Haskell | fromDegrees :: Floating a => a -> a
fromDegrees deg = deg * pi / 180
toDegrees :: Floating a => a -> a
toDegrees rad = rad * 180 / pi
main :: IO ()
main =
mapM_
print
[ sin (pi / 6)
, sin (fromDegrees 30)
, cos (pi / 6)
, cos (fromDegrees 30)
, tan (pi / 6)
, tan (fromDegrees 30)
, asin 0.5
, toDegrees (asin 0.5)
, acos 0.5
, toDegrees (acos 0.5)
, atan 0.5
, toDegrees (atan 0.5)
] |
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).
| #Racket | Racket |
#lang racket
(define input
(for/list ([i 11])
(printf "Enter a number (~a of 11): " (+ 1 i))
(read)))
(for ([x (reverse input)])
(define res (+ (sqrt (abs x)) (* 5 (expt x 3))))
(if (> res 400)
(displayln "Overflow!")
(printf "f(~a) = ~a\n" x res)))
|
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).
| #Raku | Raku | my @nums = prompt("Please type 11 space-separated numbers: ").words
until @nums == 11;
for @nums.reverse -> $n {
my $r = $n.abs.sqrt + 5 * $n ** 3;
say "$n\t{ $r > 400 ?? 'Urk!' !! $r }";
} |
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.]
| #Python | Python | maxprime = 1000000
def primes(n):
multiples = set()
prime = []
for i in range(2, n+1):
if i not in multiples:
prime.append(i)
multiples.update(set(range(i*i, n+1, i)))
return prime
def truncatableprime(n):
'Return a longest left and right truncatable primes below n'
primelist = [str(x) for x in primes(n)[::-1]]
primeset = set(primelist)
for n in primelist:
# n = 'abc'; [n[i:] for i in range(len(n))] -> ['abc', 'bc', 'c']
alltruncs = set(n[i:] for i in range(len(n)))
if alltruncs.issubset(primeset):
truncateleft = int(n)
break
for n in primelist:
# n = 'abc'; [n[:i+1] for i in range(len(n))] -> ['a', 'ab', 'abc']
alltruncs = set([n[:i+1] for i in range(len(n))])
if alltruncs.issubset(primeset):
truncateright = int(n)
break
return truncateleft, truncateright
print(truncatableprime(maxprime)) |
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.
| #Elisa | Elisa |
component BinaryTreeTraversals (Tree, Element);
type Tree;
type Node = Tree;
Tree (LeftTree = Tree, Element, RightTree = Tree) -> Tree;
Leaf (Element) -> Node;
Node (Tree) -> Node;
Item (Node) -> Element;
Preorder (Tree) -> multi (Node);
Inorder (Tree) -> multi (Node);
Postorder (Tree) -> multi (Node);
Level_order(Tree) -> multi (Node);
begin
Tree (Lefttree, Item, Righttree) = Tree: [ Lefttree; Item; Righttree ];
Leaf (anItem) = Tree (null(Tree), anItem, null(Tree) );
Node (aTree) = aTree;
Item (aNode) = aNode.Item;
Preorder (=null(Tree)) = no(Tree);
Preorder (T) = ( T, Preorder (T.Lefttree), Preorder (T.Righttree));
Inorder (=null(Tree)) = no(Tree);
Inorder (T) = ( Inorder (T.Lefttree), T, Inorder (T.Righttree));
Postorder (=null(Tree)) = no(Tree);
Postorder (T) = ( Postorder (T.Lefttree), Postorder (T.Righttree), T);
Level_order(T) = [ Queue = {T};
node = Tree:items(Queue);
[ result(node);
add(Queue, node.Lefttree) when valid(node.Lefttree);
add(Queue, node.Righttree) when valid(node.Righttree);
];
no(Tree);
];
end component BinaryTreeTraversals;
|
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
| #CoffeeScript | CoffeeScript |
arr = "Hello,How,Are,You,Today".split ","
console.log arr.join "."
|
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
| #ColdFusion | ColdFusion |
<cfoutput>
<cfset wordListTag = "Hello,How,Are,You,Today">
#Replace( wordListTag, ",", ".", "all" )#
</cfoutput>
|
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #D | D | import std.stdio, std.datetime;
int identity(int x) {
return x;
}
int sum(int num) {
foreach (i; 0 .. 100_000_000)
num += i;
return num;
}
double timeIt(int function(int) func, int arg) {
StopWatch sw;
sw.start();
func(arg);
sw.stop();
return sw.peek().usecs / 1_000_000.0;
}
void main() {
writefln("identity(4) takes %f6 seconds.", timeIt(&identity, 4));
writefln("sum(4) takes %f seconds.", timeIt(&sum, 4));
} |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #E | E | def countTo(x) {
println("Counting...")
for _ in 1..x {}
println("Done!")
}
def MX := <unsafe:java.lang.management.makeManagementFactory>
def threadMX := MX.getThreadMXBean()
require(threadMX.isCurrentThreadCpuTimeSupported())
threadMX.setThreadCpuTimeEnabled(true)
for count in [10000, 100000] {
def start := threadMX.getCurrentThreadCpuTime()
countTo(count)
def finish := threadMX.getCurrentThreadCpuTime()
println(`Counting to $count takes ${(finish-start)//1000000}ms`)
} |
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
| #Elixir | Elixir | defmodule TopRank do
def per_groupe(data, n) do
String.split(data, ~r/(\n|\r\n|\r)/, trim: true)
|> Enum.drop(1)
|> Enum.map(fn person -> String.split(person,",") end)
|> Enum.group_by(fn person -> department(person) end)
|> Enum.each(fn {department,group} ->
IO.puts "Department: #{department}"
Enum.sort_by(group, fn person -> -salary(person) end)
|> Enum.take(n)
|> Enum.each(fn person -> IO.puts str_format(person) end)
end)
end
defp salary([_,_,x,_]), do: String.to_integer(x)
defp department([_,_,_,x]), do: x
defp str_format([a,b,c,_]), do: " #{a} - #{b} - #{c} annual salary"
end
data = """
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
"""
TopRank.per_groupe(data, 3) |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RosettaTicTacToe
{
class Program
{
/*================================================================
*Pieces (players and board)
*================================================================*/
static string[][] Players = new string[][] {
new string[] { "COMPUTER", "X" }, // computer player
new string[] { "HUMAN", "O" } // human player
};
const int Unplayed = -1;
const int Computer = 0;
const int Human = 1;
// GameBoard holds index into Players[] (0 or 1) or Unplayed (-1) if location not yet taken
static int[] GameBoard = new int[9];
static int[] corners = new int[] { 0, 2, 6, 8 };
static int[][] wins = new int[][] {
new int[] { 0, 1, 2 }, new int[] { 3, 4, 5 }, new int[] { 6, 7, 8 },
new int[] { 0, 3, 6 }, new int[] { 1, 4, 7 }, new int[] { 2, 5, 8 },
new int[] { 0, 4, 8 }, new int[] { 2, 4, 6 } };
/*================================================================
*Main Game Loop (this is what runs/controls the game)
*================================================================*/
static void Main(string[] args)
{
while (true)
{
Console.Clear();
Console.WriteLine("Welcome to Rosetta Code Tic-Tac-Toe for C#.");
initializeGameBoard();
displayGameBoard();
int currentPlayer = rnd.Next(0, 2); // current player represented by Players[] index of 0 or 1
Console.WriteLine("The first move goes to {0} who is playing {1}s.\n", playerName(currentPlayer), playerToken(currentPlayer));
while (true)
{
int thisMove = getMoveFor(currentPlayer);
if (thisMove == Unplayed)
{
Console.WriteLine("{0}, you've quit the game ... am I that good?", playerName(currentPlayer));
break;
}
playMove(thisMove, currentPlayer);
displayGameBoard();
if (isGameWon())
{
Console.WriteLine("{0} has won the game!", playerName(currentPlayer));
break;
}
else if (isGameTied())
{
Console.WriteLine("Cat game ... we have a tie.");
break;
}
currentPlayer = getNextPlayer(currentPlayer);
}
if (!playAgain())
return;
}
}
/*================================================================
*Move Logic
*================================================================*/
static int getMoveFor(int player)
{
if (player == Human)
return getManualMove(player);
else
{
//int selectedMove = getManualMove(player);
//int selectedMove = getRandomMove(player);
int selectedMove = getSemiRandomMove(player);
//int selectedMove = getBestMove(player);
Console.WriteLine("{0} selects position {1}.", playerName(player), selectedMove + 1);
return selectedMove;
}
}
static int getManualMove(int player)
{
while (true)
{
Console.Write("{0}, enter you move (number): ", playerName(player));
ConsoleKeyInfo keyInfo = Console.ReadKey();
Console.WriteLine(); // keep the display pretty
if (keyInfo.Key == ConsoleKey.Escape)
return Unplayed;
if (keyInfo.Key >= ConsoleKey.D1 && keyInfo.Key <= ConsoleKey.D9)
{
int move = keyInfo.KeyChar - '1'; // convert to between 0..8, a GameBoard index position.
if (GameBoard[move] == Unplayed)
return move;
else
Console.WriteLine("Spot {0} is already taken, please select again.", move + 1);
}
else
Console.WriteLine("Illegal move, please select again.\n");
}
}
static int getRandomMove(int player)
{
int movesLeft = GameBoard.Count(position => position == Unplayed);
int x = rnd.Next(0, movesLeft);
for (int i = 0; i < GameBoard.Length; i++) // walk board ...
{
if (GameBoard[i] == Unplayed && x < 0) // until we reach the unplayed move.
return i;
x--;
}
return Unplayed;
}
// plays random if no winning move or needed block.
static int getSemiRandomMove(int player)
{
int posToPlay;
if (checkForWinningMove(player, out posToPlay))
return posToPlay;
if (checkForBlockingMove(player, out posToPlay))
return posToPlay;
return getRandomMove(player);
}
// purposely not implemented (this is the thinking part).
static int getBestMove(int player)
{
return -1;
}
static bool checkForWinningMove(int player, out int posToPlay)
{
posToPlay = Unplayed;
foreach (var line in wins)
if (twoOfThreeMatchPlayer(player, line, out posToPlay))
return true;
return false;
}
static bool checkForBlockingMove(int player, out int posToPlay)
{
posToPlay = Unplayed;
foreach (var line in wins)
if (twoOfThreeMatchPlayer(getNextPlayer(player), line, out posToPlay))
return true;
return false;
}
static bool twoOfThreeMatchPlayer(int player, int[] line, out int posToPlay)
{
int cnt = 0;
posToPlay = int.MinValue;
foreach (int pos in line)
{
if (GameBoard[pos] == player)
cnt++;
else if (GameBoard[pos] == Unplayed)
posToPlay = pos;
}
return cnt == 2 && posToPlay >= 0;
}
static void playMove(int boardPosition, int player)
{
GameBoard[boardPosition] = player;
}
static bool isGameWon()
{
return wins.Any(line => takenBySamePlayer(line[0], line[1], line[2]));
}
static bool takenBySamePlayer(int a, int b, int c)
{
return GameBoard[a] != Unplayed && GameBoard[a] == GameBoard[b] && GameBoard[a] == GameBoard[c];
}
static bool isGameTied()
{
return !GameBoard.Any(spot => spot == Unplayed);
}
/*================================================================
*Misc Methods
*================================================================*/
static Random rnd = new Random();
static void initializeGameBoard()
{
for (int i = 0; i < GameBoard.Length; i++)
GameBoard[i] = Unplayed;
}
static string playerName(int player)
{
return Players[player][0];
}
static string playerToken(int player)
{
return Players[player][1];
}
static int getNextPlayer(int player)
{
return (player + 1) % 2;
}
static void displayGameBoard()
{
Console.WriteLine(" {0} | {1} | {2}", pieceAt(0), pieceAt(1), pieceAt(2));
Console.WriteLine("---|---|---");
Console.WriteLine(" {0} | {1} | {2}", pieceAt(3), pieceAt(4), pieceAt(5));
Console.WriteLine("---|---|---");
Console.WriteLine(" {0} | {1} | {2}", pieceAt(6), pieceAt(7), pieceAt(8));
Console.WriteLine();
}
static string pieceAt(int boardPosition)
{
if (GameBoard[boardPosition] == Unplayed)
return (boardPosition + 1).ToString(); // display 1..9 on board rather than 0..8
return playerToken(GameBoard[boardPosition]);
}
private static bool playAgain()
{
Console.WriteLine("\nDo you want to play again?");
return Console.ReadKey(false).Key == ConsoleKey.Y;
}
}
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #BQN | BQN | Move ← {
𝕩⊑⊸≤0 ? ⟨⟩;
𝕊 n‿from‿to‿via:
l ← 𝕊 ⟨n-1, from, via, to⟩
r ← 𝕊 ⟨n-1, via, to, from⟩
l∾(<from‿to)∾r
}
{"Move disk from pole "∾(•Fmt 𝕨)∾" to pole "∾•Fmt 𝕩}´˘>Move 4‿1‿2‿3 |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ThueMorse[Range[20]] |
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
| #Modula-2 | Modula-2 | MODULE ThueMorse;
FROM Strings IMPORT Concat;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE Sequence(steps : CARDINAL);
TYPE String = ARRAY[0..128] OF CHAR;
VAR sb1,sb2,tmp : String;
i : CARDINAL;
BEGIN
sb1 := "0";
sb2 := "1";
WHILE i<steps DO
tmp := sb1;
Concat(sb1, sb2, sb1);
Concat(sb2, tmp, sb2);
INC(i);
END;
WriteString(sb1);
WriteLn;
END Sequence;
BEGIN
Sequence(6);
ReadChar;
END ThueMorse. |
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
| #zkl | zkl | var BN=Import("zklBigNum");
fcn modEq(a,b,p) { (a-b)%p==0 }
fcn legendre(a,p){ a.powm((p - 1)/2,p) }
fcn tonelli(n,p){ //(BigInt,Int|BigInt)
_assert_(legendre(n,p)==1, "not a square (mod p)"+vm.arglist);
q,s:=p-1,0;
while(q.isEven){ q/=2; s+=1; }
if(s==1) return(n.powm((p+1)/4,p));
z:=[BN(2)..p].filter1('wrap(z){ legendre(z,p)==(p-1) });
c,r,t,m,t2:=z.powm(q,p), n.powm((q+1)/2,p), n.powm(q,p), s, 0;
while(not modEq(t,1,p)){
t2=(t*t)%p;
i:=1; while(not modEq(t2,1,p)){ i+=1; t2=(t2*t2)%p; } // assert(i<m)
b:=c.powm(BN(1).shiftLeft(m-i-1), p);
r,c,t,m = (r*b)%p, (b*b)%p, (t*c)%p, i;
}
r
} |
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[Tokenize]
Tokenize[str_String, escape_String : "^", sep_String : "|"] :=
Module[{results = {}, token = "", state = 0, a},
a = Characters[str];
Do[
If[state == 0,
Switch[c,
escape,
state = 1
,
sep,
AppendTo[results, token];
token = "";
,
_,
token = token <> c;
]
,
If[state == 1,
token = token <> c;
state = 0;
]
]
,
{c, a}
];
AppendTo[results, token];
results
]
Tokenize["one^|uno||three^^^^|four^^^|^cuatro|"] |
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
| #Nim | Nim | import streams
proc tokenize(s: Stream, sep: static[char] = '|', esc: static[char] = '^'): seq[string] =
var buff = ""
while not s.atEnd():
let c = s.readChar
case c
of sep:
result.add buff
buff = ""
of esc:
buff.add s.readChar
else:
buff.add c
result.add buff
for i, s in tokenize(newStringStream "one^|uno||three^^^^|four^^^|^cuatro|"):
echo i, ":", s
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.