task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Tokenize_a_string_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... | #Tcl | Tcl | oo::class create tokens {
constructor {s} {
puts [coroutine Next my Iter $s]
oo::objdefine [self] forward next Next
}
method Iter {s} {
yield [info coroutine]
for {set i 0} {$i < [string length $s]} {incr i} {
yield [string index $s $i]
}
return -c... |
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
... | #OxygenBasic | OxygenBasic |
'TOPOLOGICAL SORT
uses parseutil 'getword() lenw
uses console
string dat="
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 ... |
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 ... | #Scheme | Scheme | ;----------------------------------------------------------------------------------------------
; The tape is a doubly-linked list of "cells". Each cell is a pair in which the cdr points
; to the cell on its right, and the car is a vector containing: 0: the value of the cell;
; 1: pointer to the cell on this cell's ... |
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... | #Sidef | Sidef | func 𝜑(n) {
n.factor_exp.prod {|p|
(p[0]-1) * p[0]**(p[1]-1)
}
} |
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... | #Liberty_BASIC | Liberty BASIC | pi = ACS(-1)
radians = pi / 4.0
rtod = 180 / pi
degrees = radians * rtod
dtor = pi / 180
'LB works in radians, so degrees require conversion
print "Sin: ";SIN(radians);" "; SIN(degrees*dtor)
print "Cos: ";COS(radians);" "; COS(degrees*dtor)
print "Tan: ";TAN(radians);" ";TAN(degrees*dtor)
p... |
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... | #XPL0 | XPL0 | code CrLf=9, IntOut=11;
func Prime(P); \Return true if P is a prime number
int P; \(1 is not prime, but 2 is, etc.)
int I;
[if P<=1 then return false; \negative numbers are not prime
for I:= 2 to sqrt(P) do
if rem(P/I) = 0 then return false;
return true;
];
func RightTrunc(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... | #zkl | zkl | const million=0d1_000_000;
var pTable=Data(million+1,Int).fill(0); // actually bytes, all zero
primes:=Utils.Generator(Import("sieve").postponed_sieve);
while((p:=primes.next())<million){ pTable[p]=1; }
fcn rightTrunc(n){
while(n){ if(not pTable[n]) return(False); n/=10; }
True
}
fcn leftTrunc(n){ // 999,907... |
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
/ ... | #GFA_Basic | GFA Basic |
maxnodes%=100 ! set a limit to size of tree
content%=0 ! index of content field
left%=1 ! index of left tree
right%=2 ! index of right tree
DIM tree%(maxnodes%,3) ! create space for tree
'
OPENW 1
CLEARW 1
'
@create_tree
PRINT "Preorder: ";
@preorder_traversal(1)
PRINT ""
PRINT "Inorder: ";
@inorder_traversal(1)... |
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... | #GAP | GAP | SplitString("Hello,How,Are,You,Today", ",");
# [ "Hello", "How", "Are", "You", "Today" ]
JoinStringsWithSeparator(last, ".");
# "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:
Me... | #Genie | Genie | [indent=4]
init
str:string = "Hello,How,Are,You,Today"
words:array of string[] = str.split(",")
joined:string = string.joinv(".", words)
print joined |
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 ... | #Kotlin | Kotlin | // version 1.1.2
// need to enable runtime assertions with JVM -ea option
import java.lang.management.ManagementFactory
import java.lang.management.ThreadMXBean
fun countTo(x: Int) {
println("Counting...");
(1..x).forEach {}
println("Done!")
}
fun main(args: Array<String>) {
val counts = intArrayO... |
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 ... | #Lasso | Lasso | local(start = micros)
loop(100000) => {
'nothing is outout because no autocollect'
}
'time for 100,000 loop repititions: '+(micros - #start)+' microseconds' |
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... | #Icon_and_Unicon | Icon and Unicon | record Employee(name,id,salary,dept)
procedure getEmployees ()
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","... |
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... | #Go | Go | package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"strings"
)
var b []byte
func printBoard() {
fmt.Printf("%s\n%s\n%s\n", b[0:3], b[3:6], b[6:9])
}
var pScore, cScore int
var pMark, cMark byte = 'X', 'O'
var in = bufio.NewReader(os.Stdin)
func main() {
b = make([]byte, 9)
fm... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Dart | Dart | main() {
moveit(from,to) {
print("move ${from} ---> ${to}");
}
hanoi(height,toPole,fromPole,usePole) {
if (height>0) {
hanoi(height-1,usePole,fromPole,toPole);
moveit(fromPole,toPole);
hanoi(height-1,toPole,usePole,fromPole);
}
}
hanoi(3,3,1,2);
} |
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
| #SQL | SQL | WITH recursive a(a) AS (SELECT '0' UNION ALL SELECT REPLACE(REPLACE(hex(a),'30','01'),'31','10') FROM a) SELECT * FROM a; |
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
| #Tcl | Tcl | proc tm_expand {s} {string map {0 01 1 10} $s}
# this could also be written as:
# interp alias {} tm_expand {} string map {0 01 1 10}
proc tm {k} {
set s 0
while {[incr k -1] >= 0} {
set s [tm_expand $s]
}
return $s
} |
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
| #uBasic.2F4tH | uBasic/4tH | For x = 0 to 6 ' sequence loop
Print Using "_#";x;": "; ' print sequence
For y = 0 To (2^x)-1 ' element loop
Print AND(FUNC(_Parity(y)),1); ' print element
Next ' next element
Print ' termi... |
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... | #TMG | TMG | prog: char(sep) *
char(esc) *
str: smark
token: forw/outp
( [ch==esc?] char(ch) any(!<<>>) token
| [ch==sep?] char(ch) outp str
| any(!<<>>) token );
outp: parse(( scopy = { <"> 1 <"> * } ));
forw: peek/chkeof;
peek: [ch=0] char(ch) fail;
chkeof: ( [ch?] succ | fail );
ch: ... |
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... | #VBA | VBA | Private Function tokenize(s As String, sep As String, esc As String) As Collection
Dim ret As New Collection
Dim this As String
Dim skip As Boolean
If Len(s) <> 0 Then
For i = 1 To Len(s)
si = Mid(s, i, 1)
If skip Then
this = this & si
sk... |
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
... | #Oz | Oz | declare
Deps = unit(
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 dw0... |
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 ... | #SequenceL | SequenceL | //region Imports
import <Utilities/Conversion.sl>;
import <Utilities/Sequence.sl>;
//endregion
//region Types
MCONFIG ::= (Label: char(1), Symbols: char(2), Operations: char(2), FinalConfig: char(1));
STATE ::= (CurrentConfig: char(1), CurrentPosition: int(0), Tape: char(1));
INPUT_DATA ::= (Iterations: int(0),... |
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... | #Tiny_BASIC | Tiny BASIC | REM PRINT THE DATA FOR N=1 TO 25
LET N = 0
10 LET N = N + 1
IF N = 26 THEN GOTO 100
GOSUB 1000
IF T = N - 1 THEN LET P = 1
IF T <> N - 1 THEN LET P = 0
PRINT N," ", T," ",P
GOTO 10
100 REM COUNT PRIMES BELOW 10000
LET C = 0
LET N = 2
110 GOSUB 1000
IF T = N - 1... |
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... | #Logo | Logo | print sin 45
print cos 45
print arctan 1
make "pi (radarctan 0 1) * 2 ; based on quadrant if uses two parameters
print radsin :pi / 4
print radcos :pi / 4
print 4 * radarctan 1 |
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
/ ... | #Go | Go | package main
import "fmt"
type node struct {
value int
left, right *node
}
func (n *node) iterPreorder(visit func(int)) {
if n == nil {
return
}
visit(n.value)
n.left.iterPreorder(visit)
n.right.iterPreorder(visit)
}
func (n *node) iterInorder(visit func(int)) {
if ... |
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... | #Go | Go | package main
import (
"fmt"
"strings"
)
func main() {
s := "Hello,How,Are,You,Today"
fmt.Println(strings.Join(strings.Split(s, ","), "."))
} |
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... | #Groovy | Groovy | println 'Hello,How,Are,You,Today'.split(',').join('.') |
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 ... | #Lingo | Lingo | on testFunc ()
repeat with i = 1 to 1000000
x = sqrt(log(i))
end repeat
end |
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 ... | #Logo | Logo | to time
output first first shell "|date +%s|
end
to elapsed :block
localmake "start time
run :block
(print time - :start [seconds elapsed])
end
elapsed [wait 300] ; 5 seconds elapsed |
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... | #IS-BASIC | IS-BASIC | 100 PROGRAM "Employee.bas"(N)
110 LET NR=100:LET X=0
120 STRING NAME$(1 TO NR)*20,ID$(1 TO NR)*6,DEPT$(1 TO NR)*4
130 NUMERIC SALARY(1 TO NR)
140 DO UNTIL N>0 AND N<=NR
150 INPUT PROMPT "Enter the number of ranks: ":N$
160 LET N=VAL(N$)
170 LOOP
180 CALL READDATA
190 CALL SORT
200 CALL LST
210 END
220 DEF READDATA
... |
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... | #Groovy | Groovy | class Main {
def input = new Scanner(System.in)
static main(args) {
Main main = new Main();
main.play();
}
public void play() {
TicTackToe game = new TicTackToe();
game.init()
def gameOver = false
def player = game.player1
println "Players take turns marking a square. Only squares \n"+
... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Dc | Dc | [ # move(from, to)
n # print from
[ --> ]n # print " --> "
p # print to\n
sw # p doesn't pop, so get rid of the value
]sm
[ # init(n)
sw # tuck n away temporarily
9 # sentinel as bottom of stack
lw # bring n back
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
| #VBA | VBA | Option Explicit
Sub Main()
Dim i&, t$
For i = 1 To 8
t = Thue_Morse(t)
Debug.Print i & ":=> " & t
Next
End Sub
Private Function Thue_Morse(s As String) As String
Dim k$
If s = "" Then
k = "0"
Else
k = s
k = Replace(k, "1", "2")
k = Replace(k, "0", "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
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Text
Module Module1
Sub Sequence(steps As Integer)
Dim sb1 As New StringBuilder("0")
Dim sb2 As New StringBuilder("1")
For index = 1 To steps
Dim tmp = sb1.ToString
sb1.Append(sb2)
sb2.Append(tmp)
Next
Console.WriteLine(s... |
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... | #Vlang | Vlang | fn tokenize_string(s string, sep u8, escape u8) ?[]string {
mut tokens := []string{}
mut runes := []u8{}
mut in_escape := false
for r in s {
if in_escape {
in_escape = false
runes << r
} else if r == escape {
in_escape = true
} else if r == sep {
tokens << runes.bytestr()
rune... |
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
... | #Pascal | Pascal | sub print_topo_sort {
my %deps = @_;
my %ba;
while ( my ( $before, $afters_aref ) = each %deps ) {
for my $after ( @{ $afters_aref } ) {
$ba{$before}{$after} = 1 if $before ne $after;
$ba{$after} ||= {};
}
}
while ( my @afters = sort grep { ! %{ $ba{$_} } ... |
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 ... | #Sidef | Sidef | func run_utm(state="", blank="", rules=[], tape=[blank], halt="", pos=0) {
if (pos < 0) {
pos += tape.len;
}
if (pos !~ tape.range) {
die "Bad initial position";
}
loop {
print "#{state}\t";
tape.range.each { |i|
var v = tape[i];
print (i... |
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... | #VBA | VBA | Private Function totient(ByVal n As Long) As Long
Dim tot As Long: tot = n
Dim i As Long: i = 2
Do While i * i <= n
If n Mod i = 0 Then
Do While True
n = n \ i
If n Mod i <> 0 Then Exit Do
Loop
tot = tot - tot \ i
End If
... |
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... | #Logtalk | Logtalk |
:- object(trignomeric_functions).
:- public(show/0).
show :-
% standard trignomeric functions work with radians
write('sin(pi/4.0) = '), SIN is sin(pi/4.0), write(SIN), nl,
write('cos(pi/4.0) = '), COS is cos(pi/4.0), write(COS), nl,
write('tan(pi/4.0) = '), TAN is tan(pi/4.0... |
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
/ ... | #Groovy | Groovy | def preorder;
preorder = { Node node ->
([node] + node.children().collect { preorder(it) }).flatten()
}
def postorder;
postorder = { Node node ->
(node.children().collect { postorder(it) } + [node]).flatten()
}
def inorder;
inorder = { Node node ->
def kids = node.children()
if (kids.empty) [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... | #Haskell | Haskell | {-# OPTIONS_GHC -XOverloadedStrings #-}
import Data.Text (splitOn,intercalate)
import qualified Data.Text.IO as T (putStrLn)
main = T.putStrLn . intercalate "." $ splitOn "," "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:
Me... | #HicEst | HicEst | CHARACTER string="Hello,How,Are,You,Today", list
nWords = INDEX(string, ',', 256) + 1
maxWordLength = LEN(string) - 2*nWords
ALLOCATE(list, nWords*maxWordLength)
DO i = 1, nWords
EDIT(Text=string, SePaRators=',', item=i, WordEnd, CoPyto=CHAR(i, maxWordLength, list))
ENDDO
DO i = 1, nWords
WRITE(APPend) TRIM(C... |
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 ... | #Lua | Lua | function Test_Function()
for i = 1, 10000000 do
local s = math.log( i )
s = math.sqrt( s )
end
end
t1 = os.clock()
Test_Function()
t2 = os.clock()
print( os.difftime( t2, t1 ) ) |
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 ... | #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
Module sumtolimit (limit) {
sum=limit-limit
n=sum
n++
while limit {sum+=limit*n:limit--:n-!}
}
Cls ' clear screen
Profiler
sumtolimit 10000%
Print TimeCount
Profiler
sumtolimit 10000&
Print TimeCount
... |
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... | #J | J | NB. Dynamically generate convenience functions
('`',,;:^:_1: N=:{.Employees) =:, (_&{"1)`'' ([^:(_ -: ])L:0)"0 _~ i.# E =: {: Employees
NB. Show top six ranked employees in each dept
N , (<@:>"1@:|:@:((6 <. #) {. ] \: SALARY)/.~ DEPT) |: <"1&> 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.
Wikipedi... | #Haskell | Haskell |
module Main where
import System.Random
import Data.List (intercalate, find, minimumBy)
import System.Environment (getArgs)
import Data.Char (digitToInt)
import Data.Maybe (listToMaybe, mapMaybe)
import Control.Monad (guard)
import Data.Ord (comparing)
-- check if there is a horizontal, vertical or diagonal line o... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Delphi | Delphi | proc move(byte n, src, via, dest) void:
if n>0 then
move(n-1, src, dest, via);
writeln("Move disk from pole ",src," to pole ",dest);
move(n-1, via, src, dest)
fi
corp
proc nonrec main() void:
move(4, 1, 2, 3)
corp |
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
| #Wren | Wren | var thueMorse = Fn.new { |n|
var sb0 = "0"
var sb1 = "1"
(0...n).each { |i|
var tmp = sb0
sb0 = sb0 + sb1
sb1 = sb1 + tmp
}
return sb0
}
for (i in 0..6) System.print("%(i) : %(thueMorse.call(i))") |
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
| #XLISP | XLISP | (defun thue-morse (n)
(defun flip-bits (s)
(defun flip (l)
(if (not (null l))
(cons
(if (equal (car l) #\1)
#\0
#\1)
(flip (cdr l)))))
(list->string (flip (string->list s))))
(if (... |
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... | #Wren | Wren | var SPE = "\ufffe" // unused unicode character in Specials block
var SPF = "\uffff" // ditto
var tokenize = Fn.new { |str, sep, esc|
str = str.replace(esc + esc, SPE).replace(esc + sep, SPF)
str = (str[-1] == esc) ? str[0...-1].replace(esc, "") + esc : str.replace(esc, "")
return str.split(sep).map { |... |
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
... | #Perl | Perl | sub print_topo_sort {
my %deps = @_;
my %ba;
while ( my ( $before, $afters_aref ) = each %deps ) {
for my $after ( @{ $afters_aref } ) {
$ba{$before}{$after} = 1 if $before ne $after;
$ba{$after} ||= {};
}
}
while ( my @afters = sort grep { ! %{ $ba{$_} } ... |
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 ... | #Standard_ML | Standard ML | (*** Signatures ***)
signature TAPE = sig
datatype move = Left | Right | Stay
type ''a tape
val empty : ''a tape
val moveLeft : ''a tape -> ''a tape
val moveRight : ''a tape -> ''a tape
val move : ''a tape -> move -> ''a tape
val getSymbol : ''a tape -> ''a option
val write : ''a option -> ''a tap... |
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... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.Linq.Enumerable
Module Module1
Sub Main()
For i = 1 To 25
Dim t = Totient(i)
Console.WriteLine("{0}{1}{2}{3}", i, vbTab, t, If(t = i - 1, vbTab & "prime", ""))
Next
Console.WriteLine()
Dim j = 100
While j <= 100000
Cons... |
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... | #Lua | Lua | print(math.cos(1), math.sin(1), math.tan(1), math.atan(1), math.atan2(3, 4)) |
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
/ ... | #Haskell | Haskell | ---------------------- TREE TRAVERSAL --------------------
data Tree a
= Empty
| Node
{ value :: a,
left :: Tree a,
right :: Tree a
}
preorder, inorder, postorder, levelorder :: Tree a -> [a]
preorder Empty = []
preorder (Node v l r) = v : preorder l <> preorder r
inorder Empty = [... |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main()
A := []
"Hello,How,Are,You,Today" ? {
while put(A, 1(tab(upto(',')),=","))
put(A,tab(0))
}
every writes(!A,".")
write()
end |
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 ... | #Maple | Maple | CodeTools:-Usage(ifactor(32!+1), output = realtime, quiet); |
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 ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | AbsoluteTiming[x]; |
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... | #Java | Java | import java.io.File;
import java.util.*;
public class TopRankPerGroup {
private static class Employee {
final String name;
final String id;
final String department;
final int salary;
Employee(String[] rec) {
name = rec[0];
id = rec[1];
... |
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... | #Icon_and_Unicon | Icon and Unicon |
# Play TicTacToe
$define E " " # empty square
$define X "X" # X piece
$define O "O" # O piece
# -- define a board
record Board(a, b, c, d, e, f, g, h, i)
procedure display_board (board, player)
write ("\n===============")
write (board.a || " | " || board.b || " | " || board.c)
write ("---------")
write... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Draco | Draco | proc move(byte n, src, via, dest) void:
if n>0 then
move(n-1, src, dest, via);
writeln("Move disk from pole ",src," to pole ",dest);
move(n-1, via, src, dest)
fi
corp
proc nonrec main() void:
move(4, 1, 2, 3)
corp |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Dyalect | Dyalect | func hanoi(n, a, b, c) {
if n > 0 {
hanoi(n - 1, a, c, b)
print("Move disk from \(a) to \(c)")
hanoi(n - 1, b, a, c)
}
}
hanoi(4, "A", "B", "C") |
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
| #XPL0 | XPL0 | string 0; \use zero-terminated strings
char Thue;
int N, I, J;
[Thue:= Reserve(Free); \reserve all available memory
Thue(0):= ^0;
J:= 1; \set index to terminator
for N:= 0 to 6 do
[Thue(J):= 0; \terminate string
Text(0, Thue); \show result
CrLf(0);
I:=... |
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
| #Yabasic | Yabasic | tm$ = "0"
for i=1 to 8
? tm$
tm$ = tm$ + inverte$(tm$)
next
sub inverte$(tm$)
local i
for i = 1 to len(tm$)
mid$(tm$, i, 1) = str$(not val(mid$(tm$, i, 1)))
next
return tm$
end sub |
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
| #zkl | zkl | fcn nextTM(str){ str.pump(str,'-.fp("10")) } // == fcn(c){ "10" - 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... | #zkl | zkl | fcn tokenize(str,sep,esc){
sink:=Sink(String);
foreach c in (str){
switch(c){
case(esc){ sink.write(__cWalker.next()); } // error if ^EoS
case(sep){ sink.write("\xff"); }
else { sink.write(c) }
}
}
sink.close().split("\xff");
} |
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
... | #Phix | Phix | sequence names
enum RANK, NAME, DEP -- content of names
-- rank is 1 for items to compile first, then 2, etc,
-- or 0 if cyclic dependencies prevent compilation.
-- name is handy, and makes the result order alphabetic!
-- dep is a list of dependencies (indexes to other names)
function add_dependency(string na... |
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 ... | #Tcl | Tcl | proc turing {states initial terminating symbols blank tape rules {doTrace 1}} {
set state $initial
set idx 0
set tape [split $tape ""]
if {[llength $tape] == 0} {
set tape [list $blank]
}
foreach rule $rules {
lassign $rule state0 sym0 sym1 move state1
set R($state0,$sym0) [list $sym1 $move $... |
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... | #Wren | Wren | import "/fmt" for Fmt
var totient = Fn.new { |n|
var tot = n
var i = 2
while (i*i <= n) {
if (n%i == 0) {
while(n%i == 0) n = (n/i).floor
tot = tot - (tot/i).floor
}
if (i == 2) i = 1
i = i + 2
}
if (n > 1) tot = tot - (tot/n).floor
retur... |
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... | #Maple | Maple | sin(Pi/3);
cos(Pi/3);
tan(Pi/3); |
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
/ ... | #Icon_and_Unicon | Icon and Unicon | procedure main()
bTree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]]
showTree(bTree, preorder|inorder|postorder|levelorder)
end
procedure showTree(tree, f)
writes(image(f),":\t")
every writes(" ",f(tree)[1])
write()
end
procedure preorder(L)
if \L then suspend L | preorder(L[2|3])
end
pro... |
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... | #Io | Io | "Hello,How,Are,You,Today" split(",") join(".") 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:
Me... | #J | J | s=: 'Hello,How,Are,You,Today'
] t=: <;._1 ',',s
+-----+---+---+---+-----+
|Hello|How|Are|You|Today|
+-----+---+---+---+-----+
; t,&.>'.'
Hello.How.Are.You.Today.
'.' (I.','=s)}s NB. two steps combined
Hello.How.Are.You.Today |
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 ... | #Maxima | Maxima | f(n) := if n < 2 then n else f(n - 1) + f(n - 2)$
/* First solution, call the time function with an output line number, it gives the time taken to compute that line.
Here it's assumed to be %o2 */
f(24);
46368
time(%o2);
[0.99]
/* Second solution, change a system flag to print timings for all following lines *... |
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 ... | #MiniScript | MiniScript | start = time
for i in range(1,100000)
end for
duration = time - start
print "Process took " + duration + " seconds" |
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 ... | #Nim | Nim | import times, strutils
proc doWork(x: int) =
var n = x
for i in 0..10000000:
n += i
template time(statement: untyped): float =
let t0 = cpuTime()
statement
cpuTime() - t0
echo "Time = ", time(doWork(100)).formatFloat(ffDecimal, precision = 3), " s" |
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... | #JavaScript | JavaScript | var data = [
{name: "Tyler Bennett", id: "E10297", salary: 32000, dept: "D101"},
{name: "John Rappl", id: "E21437", salary: 47000, dept: "D050"},
{name: "George Woltman", id: "E00127", salary: 53500, dept: "D101"},
{name: "Adam Smith", id: "E63535", salary: 18000, dept: "D202"},
{name: ... |
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... | #J | J |
Note 'ttt adjudicates or plays'
use: markers ttt characters
characters represent the cell names.
markers is a length 3 character vector of the
characters to use for first and second player
followed by the opponent's mark.
'XOX' means X plays 1st, O is the other mark,
and the first strategy... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #E | E | def move(out, n, fromPeg, toPeg, viaPeg) {
if (n.aboveZero()) {
move(out, n.previous(), fromPeg, viaPeg, toPeg)
out.println(`Move disk $n from $fromPeg to $toPeg.`)
move(out, n.previous(), viaPeg, toPeg, fromPeg)
}
}
move(stdout, 4, def left {}, def right {}, def middle {}) |
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
... | #Picat | Picat | topological_sort(Precedences, Sorted) =>
Edges = [K=V : [K,V] in Precedences],
Nodes = (domain(Edges) ++ range(Edges)).remove_dups(),
Sorted1 = [],
while (member(X,Nodes), not membchk(X,range(Edges)))
Sorted1 := Sorted1 ++ [X],
Nodes := Nodes.delete(X),
Edges := Edges.delete_key(X)
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 ... | #UNIX_Shell | UNIX Shell | #!/usr/bin/env bash
main() {
printf 'Simple Incrementer\n'
printf '1 1 1' | run_utm q0 qf B q0,1,1,R,q0 q0,B,1,S,qf
printf '\nThree-state busy beaver\n'
run_utm a halt 0 \
a,0,1,R,b a,1,1,L,c b,0,1,L,a b,1,1,R,b c,0,1,L,b c,1,1,S,halt \
</dev/null
}
run_utm() {
local initial=$1 final=$2 blank=$3
... |
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... | #XPL0 | XPL0 | func GCD(N, D); \Return the greatest common divisor of N and D
int N, D; \numerator and denominator
int R;
[if D > N then
[R:= D; D:= N; N:= R]; \swap D and N
while D > 0 do
[R:= rem(N/D);
N:= D;
D:= R;
];
return N;
]; \GCD
func Totient(N); \Return the totie... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Sin[1]
Cos[1]
Tan[1]
ArcSin[1]
ArcCos[1]
ArcTan[1]
Sin[90 Degree]
Cos[90 Degree]
Tan[90 Degree] |
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
/ ... | #Isabelle | Isabelle | theory Tree
imports Main
begin
datatype 'a tree = Leaf | Node "'a tree" 'a "'a tree"
definition example :: "int tree" where
"example ≡
Node
(Node
(Node
(Node Leaf 7 Leaf)
4
Leaf
)
2
(Node Leaf 5 Leaf)
)
1
(Node
(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... | #Java | Java | String toTokenize = "Hello,How,Are,You,Today";
System.out.println(String.join(".", toTokenize.split(","))); |
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... | #JavaScript | JavaScript | alert( "Hello,How,Are,You,Today".split(",").join(".") ); |
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 ... | #OCaml | OCaml | let time_it action arg =
let start_time = Sys.time () in
ignore (action arg);
let finish_time = Sys.time () in
finish_time -. start_time |
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 ... | #Oforth | Oforth | >#[ 0 1000 seq apply(#+) ] bench .
267
500500 ok
|
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... | #jq | jq | {
"Employee Name": "Tyler Bennett",
"Employee ID": "E10297",
"Salary": "32000",
"Department": "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... | #Java | Java |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Hashtable;
public class TicTacToe
{
public static void main(String[] args)
{
TicTacToe now=new TicTacToe();
now.startMatch();
}
private int[][] marks;
private int[][] wins;
private int[] weights;
private char[][] grid;
p... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #EasyLang | EasyLang | func hanoi n src dst aux . .
if n >= 1
call hanoi n - 1 src aux dst
print "Move " & src & " to " & dst
call hanoi n - 1 aux dst src
.
.
call hanoi 5 1 2 3 |
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
... | #PicoLisp | PicoLisp | (de sortDependencies (Lst)
(setq Lst # Build a flat list
(uniq
(mapcan
'((L)
(put (car L) 'dep (cdr L)) # Store dependencies in 'dep' properties
(copy L) )
(mapcar uniq Lst) ) ) ) # without self-dependencies
(m... |
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 ... | #VBA | VBA | Option Base 1
Public Enum sett
name_ = 1
initState
endState
blank
rules
End Enum
Public incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant
'-- Machine definitions
Private Sub init()
incrementer = Array("Simple incrementer", _
"q0", _
"qf", _
"B", _
... |
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... | #zkl | zkl | fcn totient(n){ [1..n].reduce('wrap(p,k){ p + (n.gcd(k)==1) }) }
fcn isPrime(n){ totient(n)==(n - 1) } |
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... | #MATLAB | MATLAB | function trigExample(angleDegrees)
angleRadians = angleDegrees * (pi/180);
disp(sprintf('sin(%f)= %f\nasin(%f)= %f',[angleRadians sin(angleRadians) sin(angleRadians) asin(sin(angleRadians))]));
disp(sprintf('sind(%f)= %f\narcsind(%f)= %f',[angleDegrees sind(angleDegrees) sind(angleDegrees) asind(sind(an... |
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
/ ... | #J | J | preorder=: ]S:0
postorder=: ([:; postorder&.>@}.) , >@{.
levelorder=: ;@({::L:1 _~ [: (/: #@>) <S:1@{::)
inorder=: ([:; inorder&.>@(''"_`(1&{)@.(1<#))) , >@{. , [:; inorder&.>@}.@}. |
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... | #jq | jq | split(",") | 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:
Me... | #Jsish | Jsish | puts('Hello,How,Are,You,Today'.split(',').join('.')) |
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 ... | #Oz | Oz | declare
%% returns milliseconds
fun {TimeIt Proc}
Before = {Now}
in
{Proc}
{Now} - Before
end
fun {Now}
{Property.get 'time.total'}
end
in
{Show
{TimeIt
proc {$}
{FoldL {List.number 1 1000000 1} Number.'+' 4 _}
end}
} |
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 ... | #PARI.2FGP | PARI/GP | time(foo)={
foo();
gettime();
} |
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.