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/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 i... | #F.23 | F# | open NUnit.Framework
open FsUnit
// radian
[<Test>]
let ``Verify that sin pi returns 0`` () =
let x = System.Math.Sin System.Math.PI
System.Math.Round(x,5) |> should equal 0
[<Test>]
let ``Verify that cos pi returns -1`` () =
let x = System.Math.Cos System.Math.PI
System.Math.Round(x,5) |> should equal -1... |
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... | #min | min | ((0 <) (-1 *) when) :abs
(((abs 0.5 pow) (3 pow 5 * +)) cleave) :fn
"Enter 11 numbers:" puts!
(gets float) 11 times
(fn (400 <=) (pop "Overflow") unless puts!) 11 times |
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... | #Nascom_BASIC | Nascom BASIC |
10 REM Trabb Pardo-Knuth algorithm
20 REM Used "magic numbers" because of strict
30 REM specification of the algorithm.
40 DEF FNF(N)=SQR(ABS(N))+5*N*N*N
50 DIM S(10)
60 PRINT "Enter 11 numbers."
70 FOR I=0 TO 10
80 PRINT STR$(I+1);
90 INPUT S(I)
100 NEXT I
110 PRINT
120 REM ** Reverse
130 FOR I=0 TO 10/2
140 TMP=S(... |
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 g... | #Sidef | Sidef | loop {
var expr = Sys.readln("\nBoolean expression (e.g. 'a & b'): ").strip.lc
break if expr.is_empty;
var vars = expr.scan(/[[:alpha:]]+/)
if (vars.is_empty) {
say "no variables detected in your boolean expression"
next
}
var prefix = [];
var suffix = [];
vars.each { |v|
print "#{v}\t... |
http://rosettacode.org/wiki/Ulam_spiral_(for_primes) | Ulam spiral (for primes) | An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1), constructed on a square grid, starting at the "center".
An Ulam spiral is also known as a prime spiral.
The first grid (green) is shown with sequential integers, ... | #VBScript | VBScript |
Function build_spiral(n)
'declare a two dimentional array
Dim matrix()
ReDim matrix(n-1,n-1)
'determine starting point
x = (n-1)/2 : y = (n-1)/2
'set the initial iterations
x_max = 1 : y_max = 1 : count = 1
'set initial direction
dir = "R"
'populate the array
For i = 1 To n*n
l = Len(n*n)
If IsPrime(i)... |
http://rosettacode.org/wiki/Truncatable_primes | Truncatable primes | A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.
Examples
The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.
The number 7393 is a right-truncatable prime as the numbers 7393, 7... | #OpenEdge.2FProgress | OpenEdge/Progress | FUNCTION isPrime RETURNS LOGICAL (
i_i AS INT
):
DEF VAR ii AS INT.
DO ii = 2 TO SQRT( i_i ):
IF i_i MODULO ii = 0 THEN
RETURN FALSE.
END.
RETURN TRUE AND i_i > 1.
END FUNCTION. /* isPrime */
FUNCTION isLeftTruncatablePrime RETURNS LOGICAL (
i_i AS INT
):
DEF VAR ii ... |
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
/ ... | #CoffeeScript | CoffeeScript |
# In this example, we don't encapsulate binary trees as objects; instead, we have a
# convention on how to store them as arrays, and we namespace the functions that
# operate on those data structures.
binary_tree =
preorder: (tree, visit) ->
return unless tree?
[node, left, right] = tree
visit node
... |
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:
Me... | #Arturo | Arturo | str: "Hello,How,Are,You,Today"
print join.with:"." split.by:"," str |
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:
Me... | #Astro | Astro | let text = 'Hello,How,Are,You,Today'
let tokens = text.split(||,||)
print tokens.join(with: '.') |
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 ... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program fcttime.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ N1, 1000000 @ loop number
.equ NBMEASURE, 10 @ measure number
/*********************************/
/* Initialized ... |
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... | #Ceylon | Ceylon | class Employee(name, id, salary, dept) {
shared String name;
shared String id;
shared Integer salary;
shared String dept;
string => "``name`` ``id`` $``salary``.00 ``dept``";
}
Employee[] employees = [
Employee("Tyler Bennett", "E10297", 32000, "D101"),
Employee("John Rappl", "E21437", 4... |
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.
Wikipedi... | #AppleScript | AppleScript | property OMask : missing value
property XMask : missing value
property winningNumbers : {7, 56, 73, 84, 146, 273, 292, 448}
property difficulty : missing value
repeat
set OMask to 0
set XMask to 0
if button returned of (display dialog "Who should start?" buttons {"I shoud", "CPU"}) = "CPU" then set OMask t... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #AutoIt | AutoIt | Func move($n, $from, $to, $via)
If ($n = 1) Then
ConsoleWrite(StringFormat("Move disk from pole "&$from&" To pole "&$to&"\n"))
Else
move($n - 1, $from, $via, $to)
move(1, $from, $to, $via)
move($n - 1, $via, $to, $from)
EndIf
EndFunc
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
| #Excel | Excel | thueMorse
=LAMBDA(n,
APPLYN(n)(
LAMBDA(bits,
APPENDCOLS(bits)(
LAMBDA(x,
IF(0 < x, 0, 1)
)(bits)
)
)
)(0)
) |
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm | Tonelli-Shanks algorithm |
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computational number theory, the Tonelli–Shanks algor... | #Perl | Perl | use bigint;
use ntheory qw(is_prime powmod kronecker);
sub tonelli_shanks {
my($n,$p) = @_;
return if kronecker($n,$p) <= 0;
my $Q = $p - 1;
my $S = 0;
$Q >>= 1 and $S++ while 0 == $Q%2;
return powmod($n,int(($p+1)/4), $p) if $S == 1;
my $c;
for $n (2..$p) {
next if kronecker... |
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 s... | #FreeBASIC | FreeBASIC | Sub tokenize(cadena As String, separador As String, escape As String)
Dim As Integer campo = 1
Dim As Boolean escapando = false
Dim As String char
Print ""; campo; " ";
For i As Integer = 1 To Len(cadena)
char = Mid(cadena, i, 1)
If escapando Then
Print char;
... |
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 dig... | #REXX | REXX | /*REXX program calculates the total area of (possibly overlapping) circles. */
parse arg box dig . /*obtain optional argument from the CL.*/
if box=='' | box==',' then box= 500 /*Not specified? Then use the default.*/
if dig=='' | dig==',' then dig= 12 ... |
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
... | #Forth | Forth | variable nodes 0 nodes ! \ linked list of nodes
: node. ( body -- )
body> >name name>string type ;
: nodeps ( body -- )
\ the word referenced by body has no (more) dependencies to resolve
['] drop over ! node. space ;
: processing ( body1 ... bodyn body -- body1 ... bodyn )
\ the word referenced b... |
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 ... | #Lua | Lua | -- Machine definitions
local incrementer = {
name = "Simple incrementer",
initState = "q0",
endState = "qf",
blank = "B",
rules = {
{"q0", "1", "1", "right", "q0"},
{"q0", "B", "1", "stay", "qf"}
}
}
local threeStateBB = {
name = "Three-state busy beaver",
initState = "... |
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 positiv... | #Julia | Julia | φ(n) = sum(1 for k in 1:n if gcd(n, k) == 1)
is_prime(n) = φ(n) == n - 1
function runphitests()
for n in 1:25
println(" φ($n) == $(φ(n))", is_prime(n) ? ", is prime" : "")
end
count = 0
for n in 1:100_000
count += is_prime(n)
if n in [100, 1000, 10_000, 100_000]
p... |
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 ... | #Raku | Raku | sub swops(@a is copy) {
my int $count = 0;
until @a[0] == 1 {
@a[ ^@a[0] ] .= reverse;
++$count;
}
$count
}
sub topswops($n) { max (1..$n).permutations.race.map: &swops }
say "$_ {topswops $_}" for 1 .. 10; |
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that i... | #Factor | Factor | USING: kernel math math.constants math.functions math.trig
prettyprint ;
pi 4 / 45 deg>rad [ sin ] [ cos ] [ tan ]
[ [ . ] compose dup compose ] tri@ 2tri
.5 [ asin ] [ acos ] [ atan ] tri [ dup rad>deg [ . ] bi@ ] tri@ |
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... | #Nim | Nim | import math, rdstdin, strutils, algorithm, sequtils
proc f(x: float): float = x.abs.pow(0.5) + 5 * x.pow(3)
proc ask: seq[float] =
readLineFromStdin("11 numbers: ").strip.split[0..10].map(parseFloat)
var s = ask()
reverse s
for x in s:
let result = f(x)
echo x, ": ", if result > 400: "TOO LARGE!" else: $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... | #Objective-C | Objective-C | //
// TPKA.m
// RosettaCode
//
// Created by Alexander Alvonellos on 5/26/12.
// Trabb Pardo-Knuth algorithm
//
#import <Foundation/Foundation.h>
double f(double x);
double f(double x) {
return pow(abs(x), 0.5) + 5*(pow(x, 3));
}
int main (int argc, const char * argv[])
{
@autoreleasepool {
N... |
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 g... | #Smalltalk | Smalltalk | [:repeat |
expr := Stdin
request:'Enter boolean expression (name variables a,b,c...):'
defaultAnswer:'a|b'.
ast := Parser parseExpression:expr inNameSpace:nil onError:repeat.
"
ensure that only boolean logic operations are inside (sandbox)
"
(ast messageSelectors a... |
http://rosettacode.org/wiki/Ulam_spiral_(for_primes) | Ulam spiral (for primes) | An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1), constructed on a square grid, starting at the "center".
An Ulam spiral is also known as a prime spiral.
The first grid (green) is shown with sequential integers, ... | #Wren | Wren | import "/dynamic" for Enum
import "/math" for Int
import "/str" for Char
import "/fmt" for Fmt
var Direction = Enum.create("Direction", ["right", "up", "left", "down"])
class Ulam {
static generate(n, i, c) {
if (n <= 1) Fiber.abort ("'n' must be more than 1.")
var s = List.filled(n, null)
... |
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, 7... | #PARI.2FGP | PARI/GP | left(n)={
my(v=[2,3,5,7],u,t=1,out=0);
for(i=1,n,
t*=10;
u=[];
for(j=1,#v,
forstep(a=t,t*9,t,
if(isprime(a+v[j]),u=concat(u,a+v[j]))
)
);
out=v[#v];
v=vecsort(u)
);
out
};
right(n)={
my(v=[2,3,5,7],u,out=0);
for(i=1,n,
u=[];
for(j=1,#v,
forstep(a=1,9,[2,4],
if(isprime(10*v[j]+a),u... |
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
/ ... | #Common_Lisp | Common Lisp | (defun preorder (node f)
(when node
(funcall f (first node))
(preorder (second node) f)
(preorder (third node) f)))
(defun inorder (node f)
(when node
(inorder (second node) f)
(funcall f (first node))
(inorder (third node) f)))
(defun postorder (node f)
(when node
(postorder (se... |
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:
Me... | #AutoHotkey | AutoHotkey | string := "Hello,How,Are,You,Today"
stringsplit, string, string, `,
loop, % string0
{
msgbox % string%A_Index%
} |
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:
Me... | #AWK | AWK | BEGIN {
s = "Hello,How,Are,You,Today"
split(s, arr, ",")
for(i=1; i < length(arr); i++) {
printf arr[i] "."
}
print
} |
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 ... | #Arturo | Arturo | benchmark [
print "starting function"
pause 2000
print "function ended"
] |
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 ... | #AutoHotkey | AutoHotkey | MsgBox % time("fx")
Return
fx()
{
Sleep, 1000
}
time(function, parameter=0)
{
SetBatchLines -1 ; don't sleep for other green threads
StartTime := A_TickCount
%function%(parameter)
Return ElapsedTime := A_TickCount - StartTime . " milliseconds"
} |
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... | #Clojure | Clojure | (use '[clojure.contrib.seq-utils :only (group-by)])
(defstruct employee :Name :ID :Salary :Department)
(def data
(->> '(("Tyler Bennett" E10297 32000 D101)
("John Rappl" E21437 47000 D050)
("George Woltman" E00127 53500 D101)
("Adam Smith" E63535 18000 D202)
("Cl... |
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.
Wikipedi... | #AutoHotkey | AutoHotkey | Gui, Add, Button, x12 y12 w30 h30 vB1 gButtonHandler,
Gui, Add, Button, x52 y12 w30 h30 vB2 gButtonHandler,
Gui, Add, Button, x92 y12 w30 h30 vB3 gButtonHandler,
Gui, Add, Button, x12 y52 w30 h30 vB4 gButtonHandler,
Gui, Add, Button, x52 y52 w30 h30 vB5 gButtonHandler,
Gui, Add, Button, x92 y52 w30 h30 vB6 gButtonHandl... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #AWK | AWK | $ awk 'func hanoi(n,f,t,v){if(n>0){hanoi(n-1,f,v,t);print(f,"->",t);hanoi(n-1,v,t,f)}}
BEGIN{hanoi(4,"left","middle","right")}' |
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
| #Factor | Factor | USING: io kernel math math.parser sequences ;
: thue-morse ( seq n -- seq' )
[ [ ] [ [ 1 bitxor ] map ] bi append ] times ;
: print-tm ( seq -- ) [ number>string ] map "" join print ;
7 <iota> [ { 0 } swap thue-morse print-tm ] each |
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
| #Fortran | Fortran | program thue_morse
implicit none
logical :: f(32) = .false.
integer :: n = 1
do
write(*,*) f(1:n)
if (n > size(f)/2) exit
f(n+1:2*n) = .not. f(1:n)
n = n * 2
end do
end program thue_morse |
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 algor... | #Phix | Phix | with javascript_semantics
include mpfr.e
function ts(string ns, ps)
mpz n = mpz_init(ns),
p = mpz_init(ps),
t = mpz_init(),
r = mpz_init(),
pm1 = mpz_init(),
pm2 = mpz_init()
mpz_sub_ui(pm1,p,1) -- pm1 = p-1
mpz_fdiv_q_2exp(pm2,pm1,1) -- pm... |
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 s... | #Go | Go | package main
import (
"errors"
"fmt"
)
func TokenizeString(s string, sep, escape rune) (tokens []string, err error) {
var runes []rune
inEscape := false
for _, r := range s {
switch {
case inEscape:
inEscape = false
fallthrough
default:
runes = append(runes, r)
case r == escape:
inEscape = ... |
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 dig... | #Ruby | Ruby | 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... |
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
... | #Fortran | Fortran | SUBROUTINE TSORT(NL,ND,IDEP,IORD,IPOS,NO)
IMPLICIT NONE
INTEGER NL,ND,NO,IDEP(ND,2),IORD(NL),IPOS(NL),I,J,K,IL,IR,IPL,IPR
DO 10 I=1,NL
IORD(I)=I
10 IPOS(I)=I
K=1
20 J=K
K=NL+1
DO 30 I=1,ND
IL=IDEP(I,1)
IR=IDEP(I,2)
IPL=IPOS(IL)
IPR=IPOS(IR)
... |
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 ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language |
left = 1; right = -1; stay = 0;
cmp[s_] := ToExpression[StringSplit[s, ","]];
utm[rules_, initial_, head_] :=
Module[{tape = initial, rh = head, n = 1},
Clear[nxt];
nxt[state_, field_] :=
nxt[state, field] = Position[rules, {rules[[state, 5]], field, _, _, _}][[1, 1]];
n = Position[rules, {rules[[n, ... |
http://rosettacode.org/wiki/Totient_function | Totient function | The totient function is also known as:
Euler's totient function
Euler's phi totient function
phi totient function
Φ function (uppercase Greek phi)
φ function (lowercase Greek phi)
Definitions (as per number theory)
The totient function:
counts the integers up to a given positiv... | #Kotlin | Kotlin | // Version 1.3.21
fun totient(n: Int): Int {
var tot = n
var nn = n
var i = 2
while (i * i <= nn) {
if (nn % i == 0) {
while (nn % i == 0) nn /= i
tot -= tot / i
}
if (i == 2) i = 1
i += 2
}
if (nn > 1) tot -= tot / nn
return tot
}
... |
http://rosettacode.org/wiki/Topswops | Topswops | Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is composed of reversing the first ... | #REXX | REXX | /*REXX program generates N decks of numbered cards and finds the maximum "swops". */
parse arg things .; if things=='' then things= 10
do n=1 for things; #= decks(n, n) /*create a (things) number of "decks". */
mx= n\==1 /*handle the case of a one-... |
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 i... | #Fantom | Fantom |
class Main
{
public static Void main ()
{
Float r := Float.pi / 4
echo (r.sin)
echo (r.cos)
echo (r.tan)
echo (r.asin)
echo (r.acos)
echo (r.atan)
// and from degrees
echo (45.0f.toRadians.sin)
echo (45.0f.toRadians.cos)
echo (45.0f.toRadians.tan)
echo (45.0f.toRadi... |
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... | #OCaml | OCaml | let f x = sqrt x +. 5.0 *. (x ** 3.0)
let p x = x < 400.0
let () =
print_endline "Please enter 11 Numbers:";
let lst = Array.to_list (Array.init 11 (fun _ -> read_float ())) in
List.iter (fun x ->
let res = f x in
if p res
then Printf.printf "f(%g) = %g\n%!" x res
else Printf.eprintf "f(%g) :: O... |
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... | #PARI.2FGP | PARI/GP | {
print("11 numbers: ");
v=vector(11, n, eval(input()));
v=apply(x->x=sqrt(abs(x))+5*x^3;if(x>400,"overflow",x), v);
vector(11, i, v[12-i])
} |
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 g... | #Tcl | Tcl | package require Tcl 8.5
puts -nonewline "Enter a boolean expression: "
flush stdout
set exp [gets stdin]
# Generate the nested loops as the body of a lambda term.
set vars [lsort -unique [regexp -inline -all {\$\w+} $exp]]
set cmd [list format [string repeat "%s\t" [llength $vars]]%s]
append cmd " {*}\[[list subst ... |
http://rosettacode.org/wiki/Ulam_spiral_(for_primes) | Ulam spiral (for primes) | An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1), constructed on a square grid, starting at the "center".
An Ulam spiral is also known as a prime spiral.
The first grid (green) is shown with sequential integers, ... | #XPL0 | XPL0 | func IsPrime(N); \Return 'true' if N is prime
int N, I;
[if N <= 2 then return N = 2;
if (N&1) = 0 then \even >2\ return false;
for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
int N, X, Y, Len, Dir, DX, DY, Side, Step;
[SetVid($13);
X:= 320/2; Y:= 200/2;
N:... |
http://rosettacode.org/wiki/Truncatable_primes | Truncatable primes | A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.
Examples
The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.
The number 7393 is a right-truncatable prime as the numbers 7393, 7... | #Perl | Perl | use ntheory ":all";
sub isltrunc {
my $n = shift;
return (is_prime($n) && $n !~ /0/ && ($n < 10 || isltrunc(substr($n,1))));
}
sub isrtrunc {
my $n = shift;
return (is_prime($n) && $n !~ /0/ && ($n < 10 || isrtrunc(substr($n,0,-1))));
}
for (reverse @{primes(1e6)}) {
if (isltrunc($_)) { print "ltrunc: $_\n"; ... |
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
/ ... | #Coq | Coq | Require Import Utf8.
Require Import List.
Unset Elimination Schemes.
(* Rose tree, with numbers on nodes *)
Inductive tree := Tree { value : nat ; children : list tree }.
Fixpoint height (t: tree) : nat :=
1 + fold_left (λ n t, max n (height t)) (children t) 0.
Example leaf n : tree := {| value := n ; childre... |
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:
Me... | #BASIC | BASIC | 100 T$ = "HELLO,HOW,ARE,YOU,TODAY"
110 GOSUB 200"TOKENIZE
120 FOR I = 1 TO N
130 PRINT A$(I) "." ;
140 NEXT
150 PRINT
160 END
200 IF N = 0 THEN DIM A$(256)
210 N = 1
220 A$(N) = "
230 FOR TI = 1 TO LEN(T$)
240 C$ = MID$(T$, TI, 1)
250 T = C$ = ","
260 IF T THEN C$ = "
270 N = N + T
280 IF T TH... |
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:
Me... | #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
call :tokenize %1 res
echo %res%
goto :eof
:tokenize
set str=%~1
:loop
for %%i in (%str%) do set %2=!%2!.%%i
set %2=!%2:~1!
goto :eof |
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 ... | #BaCon | BaCon | ' Time a function
SUB timed()
SLEEP 7000
END SUB
st = TIMER
timed()
et = TIMER
PRINT st, ", ", et |
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 ... | #BASIC | BASIC | DIM timestart AS SINGLE, timedone AS SINGLE, timeelapsed AS SINGLE
timestart = TIMER
SLEEP 1 'code or function to execute goes here
timedone = TIMER
'midnight check:
IF timedone < timestart THEN timedone = timedone + 86400
timeelapsed = timedone - timestart |
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... | #Common_Lisp | Common Lisp | (defun top-n-by-group (n data value-key group-key predicate &key (group-test 'eql))
(let ((not-pred (complement predicate))
(group-data (make-hash-table :test group-test)))
(labels ((value (datum)
(funcall value-key datum))
(insert (x list)
(merge 'list (list x) ... |
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.
Wikipedi... | #AWK | AWK |
# syntax: GAWK -f TIC-TAC-TOE.AWK
BEGIN {
move[12] = "3 7 4 6 8"; move[13] = "2 8 6 4 7"; move[14] = "7 3 2 8 6"
move[16] = "8 2 3 7 4"; move[17] = "4 6 8 2 3"; move[18] = "6 4 7 3 2"
move[19] = "8 2 3 7 4"; move[23] = "1 9 6 4 8"; move[24] = "1 9 3 7 8"
move[25] = "8 3 7 4 0"; move[26] = "3 7 1 9 8";... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #BASIC | BASIC | SUB move (n AS Integer, fromPeg AS Integer, toPeg AS Integer, viaPeg AS Integer)
IF n>0 THEN
move n-1, fromPeg, viaPeg, toPeg
PRINT "Move disk from "; fromPeg; " to "; toPeg
move n-1, viaPeg, toPeg, fromPeg
END IF
END SUB
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
| #FreeBASIC | FreeBASIC |
Dim As String tm = "0"
Function Thue_Morse(s As String) As String
Dim As String k = ""
For i As Integer = 1 To Len(s)
If Mid(s, i, 1) = "1" Then
k += "0"
Else
k += "1"
End If
Next i
Thue_Morse = s + k
End Function
Print tm
For j As Integer = 1 To ... |
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
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | // prints the first few members of the Thue-Morse sequence
package main
import (
"fmt"
"bytes"
)
// sets tmBuffer to the next member of the Thue-Morse sequence
// tmBuffer must contain a valid Thue-Morse sequence member before the call
func nextTMSequenceMember( tmBuffer * bytes.Buffer ) {
// "flip" t... |
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 algor... | #PicoLisp | PicoLisp | # from @lib/rsa.l
(de **Mod (X Y N)
(let M 1
(loop
(when (bit? 1 Y)
(setq M (% (* M X) N)) )
(T (=0 (setq Y (>> 1 Y)))
M )
(setq X (% (* X X) N)) ) ) )
(de legendre (N P)
(**Mod N (/ (dec P) 2) P) )
(de ts (N P)
(and
(=1 (legendre N P))
(let
... |
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 algor... | #Python | Python | def legendre(a, p):
return pow(a, (p - 1) // 2, p)
def tonelli(n, p):
assert legendre(n, p) == 1, "not a square (mod p)"
q = p - 1
s = 0
while q % 2 == 0:
q //= 2
s += 1
if s == 1:
return pow(n, (p + 1) // 4, p)
for z in range(2, p):
if p - 1 == legendre(z, ... |
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 s... | #Haskell | Haskell | splitEsc :: (Foldable t1, Eq t) => t -> t -> t1 t -> [[t]]
splitEsc sep esc = reverse . map reverse . snd . foldl process (0, [[]])
where process (st, r:rs) ch
| st == 0 && ch == esc = (1, r:rs)
| st == 0 && ch == sep = (0, []:r:rs)
| st == 1 && sep == ... |
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 dig... | #Tcl | Tcl | set 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.05... |
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
... | #FunL | FunL | def topsort( graph ) =
val L = seq()
val S = seq()
val g = dict( graph )
for (v, es) <- g
g(v) = seq( es )
for (v, es) <- g if es.isEmpty()
S.append( v )
while not S.isEmpty()
val n = S.remove( 0 )
L.append( n )
for (m, es) <- g if n in es
if (es -= n).isEmpty()
... |
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 ... | #MATLAB | MATLAB | function tape=turing(rules,tape,initial,terminal)
%"rules" is cell array of cell arrays of the following form:
%First element is number representing initial state
%Second element is number representing input from the tape
%Third element is number representing output printed onto the tape
%Fourth ele... |
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 positiv... | #Lua | Lua | -- Return the greatest common denominator of x and y
function gcd (x, y)
return y == 0 and math.abs(x) or gcd(y, x % y)
end
-- Return the totient number for n
function totient (n)
local count = 0
for k = 1, n do
if gcd(n, k) == 1 then count = count + 1 end
end
return count
end
-- Determine (inefficien... |
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 ... | #Ruby | Ruby | def f1(a)
i = 0
while (a0 = a[0]) > 1
a[0...a0] = a[0...a0].reverse
i += 1
end
i
end
def fannkuch(n)
[*1..n].permutation.map{|a| f1(a)}.max
end
for n in 1..10
puts "%2d : %d" % [n, fannkuch(n)]
end |
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that i... | #Forth | Forth | 45e pi f* 180e f/ \ radians
cr fdup fsin f. \ also available: fsincos ( r -- sin cos )
cr fdup fcos f.
cr fdup ftan f.
cr fdup fasin f.
cr fdup facos f.
cr fatan f. \ also available: fatan2 ( r1 r2 -- atan[r1/r2] ) |
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 i... | #Fortran | Fortran | PROGRAM Trig
REAL pi, dtor, rtod, radians, degrees
pi = 4.0 * ATAN(1.0)
dtor = pi / 180.0
rtod = 180.0 / pi
radians = pi / 4.0
degrees = 45.0
WRITE(*,*) SIN(radians), SIN(degrees*dtor)
WRITE(*,*) COS(radians), COS(degrees*dtor)
WRITE(*,*) TAN(radians), TAN(degrees*dtor)
WRITE(*,*) ASIN(SIN(ra... |
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... | #Perl | Perl | print "Enter 11 numbers:\n";
for ( 1..11 ) {
$number = <STDIN>;
chomp $number;
push @sequence, $number;
}
for $n (reverse @sequence) {
my $result = sqrt( abs($n) ) + 5 * $n**3;
printf "f( %6.2f ) %s\n", $n, $result > 400 ? " too large!" : sprintf "= %6.2f", $result
} |
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... | #Phix | Phix | function f(atom x)
return sqrt(abs(x))+5*power(x,3)
end function
procedure test(string s, bool fake_prompt=true)
if fake_prompt then printf(1,"Enter 11 numbers:%s\n",{s}) end if
s = substitute(s,","," ")
sequence S = scanf(s,"%f %f %f %f %f %f %f %f %f %f %f")
if length(S)!=1 then puts(1,"not 11 nu... |
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 g... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.Text
Module Module1
Structure Operator_
Public ReadOnly Symbol As Char
Public ReadOnly Precedence As Integer
Public ReadOnly Arity As Integer
Public ReadOnly Fun As Func(Of Boolean, Boolean, Boolean)
Public Sub New(symbol As Char, precedence As Integer, f A... |
http://rosettacode.org/wiki/Ulam_spiral_(for_primes) | Ulam spiral (for primes) | An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1), constructed on a square grid, starting at the "center".
An Ulam spiral is also known as a prime spiral.
The first grid (green) is shown with sequential integers, ... | #Yabasic | Yabasic | sub is_prime(n)
local p
for p=2 to n
if p*p>n break
if mod(n,p)=0 return false
next
return n>=2
end sub
sub spiral(w, h, x, y)
if y then
return w+spiral(h-1,w,y-1,w-x-1)
else
return x
end if
end sub
w = 9 : h = 9
for i=h-1 to 0 step -1
for j=w-1 to 0... |
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, 7... | #Phix | Phix | with javascript_semantics
constant N = 6, limit = power(10,N)
-- standard sieve:
enum L,R -- (with primes[i] as mini bit-field)
sequence primes = repeat(L+R, limit)
primes[1] = 0
for i=2 to floor(sqrt(limit)) do
if primes[i] then
for k=i*i to limit by i do
primes[k] = 0
end for
end ... |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ ... | #Crystal | Crystal |
class Node(T)
property left : Nil | Node(T)
property right : Nil | Node(T)
property data : T
def initialize(@data, @left = nil, @right = nil)
end
def preorder_traverse
print " #{data}"
if left = @left
left.preorder_traverse
end
if right = @right
right.preorder_traverse
... |
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:
Me... | #Bracmat | Bracmat | ( "Hello,How,Are,You,Today":?String
& :?ReverseList
& whl
' ( @(!String:?element "," ?String)
& !element !ReverseList:?ReverseList
)
& !String:?List
& whl
' ( !ReverseList:%?element ?ReverseList
& (!element.!List):?List
)
& out$!List
) |
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:
Me... | #C | C | #include<string.h>
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
char *a[5];
const char *s="Hello,How,Are,You,Today";
int n=0, nn;
char *ds=strdup(s);
a[n]=strtok(ds, ",");
while(a[n] && n<4) a[++n]=strtok(NULL, ",");
for(nn=0; nn<=n; ++nn) printf("%s.", a[nn]);
putchar('\n');
free(ds);
re... |
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 ... | #BASIC256 | BASIC256 | call cont(10000000)
print msec; " milliseconds"
t0 = msec
call cont(10000000)
print msec+t0; " milliseconds"
end
subroutine cont(n)
sum = 0
for i = 1 to n
sum += 1
next i
end subroutine |
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 ... | #Batch_File | Batch File |
@echo off
Setlocal EnableDelayedExpansion
call :clock
::timed function:fibonacci series.....................................
set /a a=0 ,b=1,c=1
:loop
if %c% lss 2000000000 echo %c% & set /a c=a+b,a=b, b=c & goto loop
::....................................................................
call :clock
echo Fun... |
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... | #D | D | import std.stdio, std.algorithm, std.conv, std.range;
struct Employee {
string name, id;
uint salary;
string department;
}
immutable Employee[] data = [
{"Tyler Bennett", "E10297", 32_000, "D101"},
{"John Rappl", "E21437", 47_000, "D050"},
{"George Woltman", "E00127", 53_500, "D101"},
... |
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.
Wikipedi... | #Bash | Bash |
#!/bin/bash
declare -a B=( e e e e e e e e e ) # Board
function show(){ # show B - underline first 2 rows; highlight position; number empty positoins
local -i p POS=${1:-9}; local UL BOLD="\e[1m" GREEN="\e[32m" DIM="\e[2m" OFF="\e[m" ULC="\e[4m"
for p in 0 1 2 3 4 5 6 7 8; do
[[ p%3 -eq 0 ]] && printf "... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #BASIC256 | BASIC256 | call move(4,1,2,3)
print "Towers of Hanoi puzzle completed!"
end
subroutine move (n, fromPeg, toPeg, viaPeg)
if n>0 then
call move(n-1, fromPeg, viaPeg, toPeg)
print "Move disk from "+fromPeg+" to "+toPeg
call move(n-1, viaPeg, toPeg, fromPeg)
end if
end subroutine |
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
| #Go | Go | // prints the first few members of the Thue-Morse sequence
package main
import (
"fmt"
"bytes"
)
// sets tmBuffer to the next member of the Thue-Morse sequence
// tmBuffer must contain a valid Thue-Morse sequence member before the call
func nextTMSequenceMember( tmBuffer * bytes.Buffer ) {
// "flip" t... |
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
| #Haskell | Haskell | thueMorsePxs :: [[Int]]
thueMorsePxs = iterate ((++) <*> map (1 -)) [0]
{-
= Control.Monad.ap (++) (map (1-)) `iterate` [0]
= iterate (\ xs -> (++) xs (map (1-) xs)) [0]
= iterate (\ xs -> xs ++ map (1-) xs) [0]
-}
main :: IO ()
main = print $ thueMorsePxs !! 5 |
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 algor... | #Racket | Racket | #lang racket
(require math/number-theory)
(define (Legendre a p)
(modexpt a (quotient (sub1 p) 2)))
(define (Tonelli n p (err (λ (n p) (error "not a square (mod p)" (list n p)))))
(with-modulus p
(unless (= 1 (Legendre n p)) (err n p))
(define-values (q s)
(let even?-q-loop ((q (sub1 p)) (s ... |
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 algor... | #Raku | Raku | # Legendre operator (𝑛│𝑝)
sub infix:<│> (Int \𝑛, Int \𝑝 where 𝑝.is-prime && (𝑝 != 2)) {
given 𝑛.expmod( (𝑝-1) div 2, 𝑝 ) {
when 0 { 0 }
when 1 { 1 }
default { -1 }
}
}
sub tonelli-shanks ( \𝑛, \𝑝 where (𝑛│𝑝) > 0 ) {
my $𝑄 = 𝑝 - 1;
my $𝑆 = 0;
$𝑄 +>= 1 a... |
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 s... | #J | J |
tokenize1=: tokenize =: '^|'&$: :(4 : 0)
'ESC SEP' =. x
STATE =. 0
RESULT =. 0 $ a:
TOKEN =. ''
for_C. y do.
if. STATE do.
TOKEN =. TOKEN , C
STATE =. 0
else.
if. C = ESC do.
STATE =. 1
elseif. C = SEP do.
RESULT =. RESULT , < TOKEN
TOKEN =. ''
elseif. do.
TOKEN =. TOKEN , C
... |
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 s... | #Java | Java | import java.util.*;
public class TokenizeStringWithEscaping {
public static void main(String[] args) {
String sample = "one^|uno||three^^^^|four^^^|^cuatro|";
char separator = '|';
char escape = '^';
System.out.println(sample);
try {
System.out.println(token... |
http://rosettacode.org/wiki/Total_circles_area | Total circles area | Total circles area
You are encouraged to solve this task according to the task description, using any language you may know.
Example circles
Example circles filtered
Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal dig... | #VBA | VBA | Public c As Variant
Public pi As Double
Dim arclists() As Variant
Public Enum circles_
xc = 0
yc
rc
End Enum
Public Enum arclists_
rho
x_
y_
i_
End Enum
Public Enum shoelace_axis
u = 0
v
End Enum
Private Sub give_a_list_of_circles()
c = Array(Array(1.6417233788, 1.6121789534, 0.0... |
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
... | #Go | Go | package main
import (
"fmt"
"strings"
)
var data = `
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 synops... |
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 ... | #Mercury | Mercury | :- module turing.
:- interface.
:- import_module list.
:- import_module set.
:- type config(State, Symbol)
---> config(initial_state :: State,
halting_states :: set(State),
blank :: Symbol ).
:- type action ---> left ; stay ; right.
:- func turing(config(State, Sy... |
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 positiv... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Do[
tmp = EulerPhi[i];
If[i - 1 == tmp,
Print["\[CurlyPhi](", i, ")=", tmp, ", is prime"]
,
Print["\[CurlyPhi](", i, ")=", tmp]
]
,
{i, 25}
]
Count[EulerPhi[Range[100]] - Range[100], -1]
Count[EulerPhi[Range[1000]] - Range[1000], -1]
Count[EulerPhi[Range[10000]] - Range[10000], -1]
Count[EulerPhi[Range[100... |
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 ... | #Rust | Rust |
use itertools::Itertools;
fn solve(deck: &[usize]) -> usize {
let mut counter = 0_usize;
let mut shuffle = deck.to_vec();
loop {
let p0 = shuffle[0];
if p0 == 1 {
break;
}
shuffle[..p0].reverse();
counter += 1;
}
counter
}
// this is a naiv... |
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 ... | #Scala | Scala | object Fannkuch extends App {
def fannkuchen(l: List[Int], n: Int, i: Int, acc: Int): Int = {
def flips(l: List[Int]): Int = (l: @unchecked) match {
case 1 :: ls => 0
case (n :: ls) =>
val splitted = l.splitAt(n)
flips(splitted._2.reverse_:::(splitted._1)) + 1
}
def rotateL... |
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 i... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Const pi As Double = 4 * Atn(1)
Dim As Double radians = pi / 4
Dim As Double degrees = 45.0 '' equivalent in degrees
Dim As Double temp
Print "Radians : "; radians, " ";
Print "Degrees : "; degrees
Print
Print "Sine : "; Sin(radians), Sin(degrees * pi / 180)
Print "Cosine : "; ... |
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... | #Picat | Picat | import util.
go =>
L = [I.parse_term() : I in split(read_line())],
S = [[I,cond(F<=400,F,'TOO LARGE')] : I in L.len..-1..1, F=f(L[I])],
println(S),
nl.
f(T) = sqrt(abs(T)) + 5*T**3. |
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... | #PicoLisp | PicoLisp | (de f (X)
(+ (sqrt (abs X)) (* 5 X X X)) )
(trace 'f)
(in NIL
(prin "Input 11 numbers: ")
(for X (reverse (make (do 11 (link (read)))))
(when (> (f X) 400)
(prinl "TOO LARGE") ) ) ) |
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 g... | #Wren | Wren | import "/dynamic" for Struct
import "/ioutil" for Input
import "/seq" for Stack
import "/str" for Str
var Variable = Struct.create("Variable", ["name", "value"])
// use integer constants as bools don't support bitwise operators
var FALSE = 0
var TRUE = 1
var expr = ""
var variables = []
var isOperator = Fn.new ... |
http://rosettacode.org/wiki/Ulam_spiral_(for_primes) | Ulam spiral (for primes) | An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1), constructed on a square grid, starting at the "center".
An Ulam spiral is also known as a prime spiral.
The first grid (green) is shown with sequential integers, ... | #zkl | zkl | var primes =Utils.Generator(Import("sieve.zkl").postponed_sieve); // lazy
var offsets=Utils.cycle( T(0,1),T(-1,0),T(0,-1),T(1,0) ); // (N,E,S,W), lazy
const BLACK=0, WHITE=0xff|ff|ff, GREEN=0x00|ff|00, EMPTY=0x080|80|80;
fcn uspiral(N){
if((M:=N).isEven) M+=1; // need odd width, height
img,p := PPM(M,M,EMPTY),... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.