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/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 ... | #Scala | Scala |
def time(f: => Unit)={
val s = System.currentTimeMillis
f
System.currentTimeMillis - 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... | #Oz | Oz | declare
%% Create a list of employee records.
Data = {Map
[['Tyler Bennett' e10297 32000 d101]
['John Rappl' e21437 47000 d050]
['George Woltman' e00127 53500 d101]
['Adam Smith' e63535 18000 d202]
['Claire Buckman' e39876 27800 d202]
['David McClella... |
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... | #.D0.9C.D0.9A-61.2F52 | МК-61/52 | 9 С/П ПП 28 пи * cos x<0 16 ИП2
ПП 28 1 - БП 51 ИП7 ПП 28 ИП7
ПП 28 КИП2 ИП2 ВП 4 4 С/П 1 -
x=0 33 8 П2 С/П П7 ИП2 4 - x#0
43 x<0 45 8 + П8 ИП7 - x#0 55
ИП8 ВП 6 6 С/П ИП2 В/О |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #F.23 | F# | #light
let rec hanoi num start finish =
match num with
| 0 -> [ ]
| _ -> let temp = (6 - start - finish)
(hanoi (num-1) start temp) @ [ start, finish ] @ (hanoi (num-1) temp finish)
[<EntryPoint>]
let main args =
(hanoi 4 1 2) |> List.iter (fun pair -> match pair with
... |
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
... | #Sidef | Sidef | func print_topo_sort (deps) {
var ba = Hash.new;
deps.each { |before, afters|
afters.each { |after|
if (before != after) {
ba{before}{after} = 1;
};
ba{after} \\= Hash.new;
}
};
loop {
var afters = ba.keys.grep {|k| ba{k}.valu... |
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... | #Oforth | Oforth | import: math
: testTrigo
| rad deg hyp z |
Pi 4 / ->rad
45.0 ->deg
0.5 ->hyp
System.Out rad sin << " - " << deg asRadian sin << cr
System.Out rad cos << " - " << deg asRadian cos << cr
System.Out rad tan << " - " << deg asRadian tan << cr
printcr
rad sin asin ->z
System.Ou... |
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
/ ... | #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
Null=(,)
Tree=((((Null,7,Null),4,Null),2,(Null,5,Null)),1,(((Null,8,Null),6,(Null,9,Null)),3,Null))
Module preorder (T) {
Print "preorder: ";
printtree(T)
Print
sub printtree(T)
Print T#val(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... | #MATLAB_.2F_Octave | MATLAB / Octave |
s=strsplit('Hello,How,Are,You,Today',',')
fprintf(1,'%s.',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... | #Maxima | Maxima | l: split("Hello,How,Are,You,Today", ",")$
printf(true, "~{~a~^.~}~%", l)$ |
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 ... | #Scheme | Scheme | (time (some-function)) |
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 ... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "time.s7i";
include "duration.s7i";
const func integer: identity (in integer: x) is
return x;
const func integer: sum (in integer: num) is func
result
var integer: result is 0;
local
var integer: number is 0;
begin
result := num;
for number range 1 to 10... |
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 ... | #Sidef | Sidef | var benchmark = frequire('Benchmark')
func fac_rec(n) {
n == 0 ? 1 : (n * __FUNC__(n - 1))
}
func fac_iter(n) {
var prod = 1
n.times { |i|
prod *= i
}
prod
}
var result = benchmark.timethese(-3, Hash(
'fac_rec' => { fac_rec(20) },
'fac_iter' => { fac_iter(20) },
))
benchmar... |
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... | #PARI.2FGP | PARI/GP | {V=[["Tyler Bennett","E10297",32000,"D101"],
["John Rappl","E21437",47000,"D050"],
["George Woltman","E00127",53500,"D101"],
["Adam Smith","E63535",18000,"D202"],
["Claire Buckman","E39876",27800,"D202"],
["David McClellan","E04242",41500,"D101"],
["Rich Holcomb","E01234",49500,"D202"],
["Nathan Adams","E41298",21900,"... |
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... | #Nim | Nim | import options, random, sequtils, strutils
type
Board = array[1..9, char]
Score = (char, array[3, int])
const NoChoice = 0
var board: Board = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
const Wins = [[1, 2, 3], [4, 5, 6], [7, 8, 9],
[1, 4, 7], [2, 5, 8], [3, 6, 9],
[1, 5, 9], [... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Factor | Factor | USING: formatting kernel locals math ;
IN: rosettacode.hanoi
: move ( from to -- )
"%d->%d\n" printf ;
:: hanoi ( n from to other -- )
n 0 > [
n 1 - from other to hanoi
from to move
n 1 - other to from hanoi
] when ; |
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
... | #Swift | Swift | let libs = [
("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"... |
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... | #ooRexx | ooRexx | rxm.cls 20 March 2014
The distribution of ooRexx contains a function package called rxMath
that provides the computation of trigonometric and some other functions.
Based on the underlying C-library the precision of the returned values
is limited to 16 digits. Close ob... |
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
/ ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | preorder[a_Integer] := a;
preorder[a_[b__]] := Flatten@{a, preorder /@ {b}};
inorder[a_Integer] := a;
inorder[a_[b_, c_]] := Flatten@{inorder@b, a, inorder@c};
inorder[a_[b_]] := Flatten@{inorder@b, a}; postorder[a_Integer] := a;
postorder[a_[b__]] := Flatten@{postorder /@ {b}, a};
levelorder[a_] :=
Flatten[Tab... |
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... | #MAXScript | MAXScript | output = ""
for word in (filterString "Hello,How,Are,You,Today" ",") do
(
output += (word + ".")
)
format "%\n" output |
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... | #Mercury | Mercury |
:- module string_tokenize.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module list, string.
main(!IO) :-
Tokens = string.split_at_char((','), "Hello,How,Are,You,Today"),
io.write_list(Tokens, ".", io.write_string, !IO),
io.nl(!IO). |
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 ... | #Slate | Slate |
[inform: 2000 factorial] timeToRun.
|
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 ... | #Smalltalk | Smalltalk | Time millisecondsToRun: [
Transcript show: 2000 factorial
]. |
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... | #Pascal | Pascal | program TopRankPerGroup(output);
uses
Classes, Math;
type
TData = record
name: string;
ID: string;
salary: longint;
dept: string
end;
PTData = ^TData;
const
data: array [1..13] of TData =
( (name: 'Tyler Bennett'; ID: 'E10297'; salary: 32000; dept: '... |
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... | #Objeck | Objeck | class TicTacToe {
@board : Char[,];
@cpu_opening : Bool;
enum Status {
INVALID_MOVE,
PLAYING,
QUIT,
TIE,
CPU_WIN,
PLAYER_WIN
}
consts Weights {
MIN := -1000,
MAX := 1000
}
function : Main(args : String[]) ~ Nil {
cpu_score := 0;
player_score := 0;
for(i ... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #FALSE | FALSE | ["Move disk from "$!\" to "$!\"
"]p: { to from }
[n;0>[n;1-n: @\ h;! @\ p;! \@ h;! \@ n;1+n:]?]h: { via to from }
4n:["right"]["middle"]["left"]h;!%%% |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Fermat | Fermat | Func Hanoi( n, f, t, v ) =
if n = 0 then
!'';
else
Hanoi(n - 1, f, v, t);
!f;!' -> ';!t;!', ';
Hanoi(n - 1, v, t, f)
fi. |
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
... | #Tailspin | Tailspin |
data node <'.+'>, from <node>, to <node>
templates topologicalSort
@: [];
{V: {|$.v..., $.e({node: §.to})...|} , E: {|$.e... -> \(<{from: <~=$.to>}> $! \)|}} -> #
when <{V: <?($::count <=0>)>}> $@!
otherwise
def independent: ($.V notMatching $.E({node: §.from}));
[$independent... -> $.node] -> ..|@:... |
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... | #Oz | Oz | declare
PI = 3.14159265
fun {FromDegrees Deg}
Deg * PI / 180.
end
fun {ToDegrees Rad}
Rad * 180. / PI
end
Radians = PI / 4.
Degrees = 45.
in
for F in [Sin Cos Tan] do
{System.showInfo {F Radians}#" "#{F {FromDegrees Degrees}}}
end
for I#F in [Asin#Sin Acos#Cos Atan#Tan] do
... |
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
/ ... | #Mercury | Mercury | :- module tree_traversal.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module list.
:- type tree(V)
---> empty
; node(V, tree(V), tree(V)).
:- pred preorder(pred(V, A, A), tree(V), A, A).
:- mode preorder(pred(in, di, uo) is det, in, d... |
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... | #min | min | "Hello,How,Are,You,Today" "," split "." join print |
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... | #MiniScript | MiniScript | tokens = "Hello,How,Are,You,Today".split(",")
print tokens.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 ... | #Standard_ML | Standard ML | fun time_it (action, arg) = let
val timer = Timer.startCPUTimer ()
val _ = action arg
val times = Timer.checkCPUTimer timer
in
Time.+ (#usr times, #sys times)
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 ... | #Stata | Stata | program timer_test
timer clear 1
timer on 1
sleep `0'
timer off 1
timer list 1
end
. timer_test 1000
1: 1.01 / 1 = 1.0140 |
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 ... | #Swift | Swift | import Foundation
public struct TimeResult {
public var seconds: Double
public var nanoSeconds: Double
public var duration: Double { seconds + (nanoSeconds / 1e9) }
@usableFromInline
init(seconds: Double, nanoSeconds: Double) {
self.seconds = seconds
self.nanoSeconds = nanoSeconds
}
}
extens... |
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... | #Perl | Perl | sub zip {
my @a = @{shift()};
my @b = @{shift()};
my @l;
push @l, shift @a, shift @b while @a and @b;
return @l;
}
sub uniq {
my %h;
grep {!$h{$_}++} @_;
}
my @data =
map {{ zip [qw(name id salary dept)], [split ','] }}
split "\n",
<<'EOF';
Tyler Bennett,E10297,32000,D101
Joh... |
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... | #Pascal | Pascal | program tic(Input, Output);
type
Contents = (Unassigned, Human, Computer);
var
best_i, best_j: Integer; { best solution a depth of zero in the search }
b: array[0..2, 0..2] of Contents; {zero based so modulus works later}
player: Contents;
procedure displayBoard;
var
i, j: Integer;
t: array... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #FOCAL | FOCAL | 01.10 S N=4;S S=1;S V=2;S T=3
01.20 D 2
01.30 Q
02.02 S N(D)=N(D)-1;I (N(D)),2.2,2.04
02.04 S D=D+1
02.06 S N(D)=N(D-1);S S(D)=S(D-1)
02.08 S T(D)=V(D-1);S V(D)=T(D-1)
02.10 D 2
02.12 S D=D-1
02.14 D 3
02.16 S A=S(D);S S(D)=V(D);S V(D)=A
02.18 G 2.02
02.20 D 3
03.10 T %1,"MOVE DISK FROM POLE",S(D)
03.20 T " TO POLE... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Forth | Forth | CREATE peg1 ," left "
CREATE peg2 ," middle "
CREATE peg3 ," right "
: .$ COUNT TYPE ;
: MOVE-DISK
LOCALS| via to from n |
n 1 =
IF CR ." Move disk from " from .$ ." to " to .$
ELSE n 1- from via to RECURSE
1 from to via RECURSE
n 1- via to from RECURSE
THEN ; |
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
... | #Tcl | Tcl | package require Tcl 8.5
proc topsort {data} {
# Clean the data
dict for {node depends} $data {
if {[set i [lsearch -exact $depends $node]] >= 0} {
set depends [lreplace $depends $i $i]
dict set data $node $depends
}
foreach node $depends {dict lappend data $node}
}
# Do the sort
set sor... |
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... | #PARI.2FGP | PARI/GP | cos(Pi/2)
sin(Pi/2)
tan(Pi/2)
acos(1)
asin(1)
atan(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
/ ... | #Nim | Nim | import deques
type
Node[T] = ref object
data: T
left, right: Node[T]
proc newNode[T](data: T; left, right: Node[T] = nil): Node[T] =
Node[T](data: data, left: left, right: right)
proc preorder[T](n: Node[T]): seq[T] =
if n.isNil: @[]
else: @[n.data] & preorder(n.left) & preorder(n.right)
proc in... |
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... | #MMIX | MMIX | sep IS ','
EOS IS 0
NL IS 10
// main registers
p IS $255
tp GREG
c GREG
t GREG
LOC Data_Segment
GREG @
Text BYTE "Hello,How,Are,You,Today",EOS
token BYTE 0
eot IS @+255
LOC #100 % main () {
Main LDA p,Text %
LDA tp,token % initialize pointers
2H LDBU c,p % DO get char
BZ c,5F % break if char == EOS
CMP ... |
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 ... | #Tcl | Tcl | proc sum_n {n} {
for {set i 1; set sum 0.0} {$i <= $n} {incr i} {set sum [expr {$sum + $i}]}
return [expr {wide($sum)}]
}
puts [time {sum_n 1e6} 100]
puts [time {} 100] |
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 ... | #TorqueScript | TorqueScript |
function benchmark(%times,%function,%a,%b,%c,%d,%e,%f,%g,%h,%i,%j,%k,%l,%m,%n,%o)
{
if(!isFunction(%function))
{
warn("BENCHMARKING RESULT FOR" SPC %function @ ":" NL "Function does not exist.");
return -1;
}
%start = getRealTime();
for(%i=0; %i < %times; %i++)
{
call(%function,%a,%b,%c,%d,%e,%f,%g,%h... |
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... | #Phix | Phix | with javascript_semantics
constant N=3
-- Employee Name,Employee ID,Salary,Department
enum /*NAME,*/ /*ID,*/ SAL=3, DEPT=4
constant employees = {{"Tyler Bennett", "E10297",32000,"D101"},
{"John Rappl", "E21437",47000,"D050"},
... |
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... | #Perl | Perl | use warnings;
use strict;
my $initial = join ",", qw(abc def ghi);
my %reverse = qw(X O O X);
# In list context, returns best move,
# In scalar context, returns the score of best move.
my %cache;
sub best_move {
my ($b, $me) = @_;
if( exists $cache{$b,$me,wantarray} ) {
return $cache{$b,$me,wantarray};
} elsif... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Fortran | Fortran | PROGRAM TOWER
CALL Move(4, 1, 2, 3)
CONTAINS
RECURSIVE SUBROUTINE Move(ndisks, from, to, via)
INTEGER, INTENT (IN) :: ndisks, from, to, via
IF (ndisks == 1) THEN
WRITE(*, "(A,I1,A,I1)") "Move disk from pole ", from, " to pole ", to
ELSE
CALL Move(ndisks-1, from, via, to)
CAL... |
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
... | #UNIX_Shell | UNIX Shell | $ awk '{ for (i = 1; i <= NF; i++) print $i, $1 }' <<! | tsort
> des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
> dw01 ieee dw01 dware gtech
> dw02 ieee dw02 dware
> dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
> dw04 dw04 ieee dw01 d... |
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... | #Pascal | Pascal | Program TrigonometricFuntions(output);
uses
math;
var
radians, degree: double;
begin
radians := pi / 4.0;
degree := 45;
// Pascal works in radians. Necessary degree-radian conversions are shown.
writeln (sin(radians),' ', sin(degree/180*pi));
writeln (cos(radians),' ', cos(degree/180*pi));
w... |
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
/ ... | #Objeck | Objeck |
use Collection;
class Test {
function : Main(args : String[]) ~ Nil {
one := Node->New(1);
two := Node->New(2);
three := Node->New(3);
four := Node->New(4);
five := Node->New(5);
six := Node->New(6);
seven := Node->New(7);
eight := Node->New(8);
nine := Node->New(9);
on... |
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... | #Modula-3 | Modula-3 | MODULE Tokenize EXPORTS Main;
IMPORT IO, TextConv;
TYPE Texts = REF ARRAY OF TEXT;
VAR tokens: Texts;
string := "Hello,How,Are,You,Today";
sep := SET OF CHAR {','};
BEGIN
tokens := NEW(Texts, TextConv.ExplodedSize(string, sep));
TextConv.Explode(string, tokens^, sep);
FOR i := FIRST(tokens^) TO LA... |
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... | #MUMPS | MUMPS | TOKENS
NEW I,J,INP
SET INP="Hello,how,are,you,today"
NEW I FOR I=1:1:$LENGTH(INP,",") SET INP(I)=$PIECE(INP,",",I)
NEW J FOR J=1:1:I WRITE INP(J) WRITE:J'=I "."
KILL I,J,INP // Kill is optional. "New" variables automatically are killed on "Quit"
QUIT |
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 ... | #True_BASIC | True BASIC | SUB cont (n)
LET sum = 0
FOR i = 1 TO n
LET sum = sum+1
NEXT i
END SUB
LET timestart = TIME
CALL cont (10000000)
LET timedone = TIME
!midnight check:
IF timedone < timestart THEN LET timedone = timedone+86400
LET timeelapsed = (timedone-timestart)*1000
PRINT timeelapsed; "miliseconds."
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 ... | #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
SECTION test
LOOP n=1,999999
rest=MOD (n,1000)
IF (rest==0) Print n
ENDLOOP
ENDSECTION
time_beg=TIME ()
DO test
time_end=TIME ()
interval=TIME_INTERVAL (seconds,time_beg,time_end)
PRINT "'test' start at ",time_beg
PRINT "'test' ends at ",time_end
PRINT "'test' takes ",interval," seconds"
|
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... | #PHP | PHP | $data = Array(
Array("Tyler Bennett","E10297",32000,"D101"),
Array("John Rappl","E21437",47000,"D050"),
Array("George Woltman","E00127",53500,"D101"),
Array("Adam Smith","E63535",18000,"D202"),
Array("Claire Buckman","E39876",27800,"D202"),
Array("... |
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... | #Phix | Phix | --
-- demo\rosetta\Tic_tac_toe.exw
--
with javascript_semantics
include pGUI.e
constant title = "Tic Tac Toe"
sequence board = repeat(' ',9) -- {' '/'X'/'O'}
bool human = false -- (flipped in new_game)
bool game_over = false
constant play_dumb = false
Ihandle dlg
-- saved in redraw_cb() for check_position():
integer... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Sub move(n As Integer, from As Integer, to_ As Integer, via As Integer)
If n > 0 Then
move(n - 1, from, via, to_)
Print "Move disk"; n; " from pole"; from; " to pole"; to_
move(n - 1, via, to_, from)
End If
End Sub
Print "Three disks" : Print
move 3, 1, 2, 3
Print
Print "Four dis... |
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
... | #Ursala | Ursala | tsort = ~&nmnNCjA*imSLs2nSjiNCSPT; @NiX ^=lxPrnSPX ^(~&rlPlT,~&rnPrmPljA*D@r)^|/~& ~&m!=rnSPlX |
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... | #Perl | Perl | use Math::Trig;
my $angle_degrees = 45;
my $angle_radians = pi / 4;
print sin($angle_radians), ' ', sin(deg2rad($angle_degrees)), "\n";
print cos($angle_radians), ' ', cos(deg2rad($angle_degrees)), "\n";
print tan($angle_radians), ' ', tan(deg2rad($angle_degrees)), "\n";
print cot($angle_radians), ' ', cot(deg2rad(... |
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
/ ... | #OCaml | OCaml | type 'a tree = Empty
| Node of 'a * 'a tree * 'a tree
let rec preorder f = function
Empty -> ()
| Node (v,l,r) -> f v;
preorder f l;
preorder f r
let rec inorder f = function
Empty -> ()
| Node (v,l,r) -> inorder f l;
... |
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... | #Nanoquery | Nanoquery | for word in "Hello,How,Are,You,Today".split(",")
print word + "."
end |
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... | #Nemerle | Nemerle | using System;
using System.Console;
using Nemerle.Utility.NString;
module Tokenize
{
Main() : void
{
def cswords = "Hello,How,Are,You,Today";
WriteLine(Concat(".", $[s | s in cswords.Split(',')]));
// Split() produces an array while Concat() consumes a list
// a quick in place ... |
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 ... | #UNIX_Shell | UNIX Shell | $ time sleep 1 |
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 ... | #VBA | VBA | Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
Private Function identity(x As Long) As Long
For j = 0 To 1000
identity = x
Next j
End Function
Private Function sum(ByVal num As Long) As Long
Dim t As Long
For j = 0 To 1000
t = num
For i = 0 To 10000
t = t + i
... |
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... | #Picat | Picat | go =>
Emp = [
% Employee Name,Employee ID,Salary,Department
["Tyler Bennett","E10297","32000","D101"],
["John Rappl","E21437","47000","D050"],
["George Woltman","E00127","53500","D101"],
["Adam Smith","E63535","18000","D202"],
["Claire Buckman","E39876","278... |
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... | #PHP | PHP |
<?php
const BOARD_NUM = 9;
const ROW_NUM = 3;
$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);
function isGameOver($board, $pin) {
$pat =
'/X{3}|' . //Horz
'X..X..X..|' . //Vert Left
'.X..X..X.|' . //Vert Middle
'..X..X..X|' . //Vert Right
'..X.X.X..|' . //Diag TL->BR
'X...X...X|' . //Diag TR->BL
'[^\... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Frink | Frink |
/** Set up the recursive call for n disks */
hanoi[n] := hanoi[n, 1, 3, 2]
/** The recursive call. */
hanoi[n, source, target, aux] :=
{
if n > 0
{
hanoi[n-1, source, aux, target]
println["Move from $source to $target"] ... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #FutureBasic | FutureBasic | window 1, @"Towers of Hanoi", ( 0, 0, 300, 300 )
void local fn Move( n as long, fromPeg as long, toPeg as long, viaPeg as long )
if n > 0
fn Move( n-1, fromPeg, viaPeg, toPeg )
print "Move disk from "; fromPeg; " to "; toPeg
fn Move( n-1, viaPeg, toPeg, fromPeg )
end if
end fn
fn Move( 4, 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
... | #VBScript | VBScript |
class topological
dim dictDependencies
dim dictReported
dim depth
sub class_initialize
set dictDependencies = createobject("Scripting.Dictionary")
set dictReported = createobject("Scripting.Dictionary")
depth = 0
end sub
sub reset
dictReported.removeall
end sub
property let dependencies( s )
'... |
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... | #Phix | Phix | ?sin(PI/2)
?sin(90*PI/180)
?cos(0)
?cos(0*PI/180)
?tan(PI/4)
?tan(45*PI/180)
?arcsin(1)*2
?arcsin(1)*180/PI
?arccos(0)*2
?arccos(0)*180/PI
?arctan(1)*4
?arctan(1)*180/PI
|
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
/ ... | #Oforth | Oforth | Object Class new: Tree(v, l, r)
Tree method: initialize(v, l, r) v := v l := l r := r ;
Tree method: v @v ;
Tree method: l @l ;
Tree method: r @r ;
Tree method: preOrder(f)
@v f perform
@l ifNotNull: [ @l preOrder(f) ]
@r ifNotNull: [ @r preOrder(f) ] ;
Tree method: inOrder(f)
@l ifNotNull: [ ... |
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... | #NetRexx | NetRexx | /*NetRexx program *****************************************************
* 20.08.2012 Walter Pachl derived from REXX Version 3
**********************************************************************/
sss='Hello,How,Are,You,Today'
Say 'input string='sss
Say ''
Say 'Words in the string:'
ss =sss.translate(' ',','... |
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... | #NewLISP | NewLISP | (print (join (parse "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 ... | #Wart | Wart | time 1+1
30000/1000000 # in microseconds
=> 2 |
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 ... | #Wren | Wren | import "./check" for Benchmark
Benchmark.run("a function", 100, true) {
for (i in 0..1e7) {}
} |
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... | #PicoLisp | PicoLisp | # Employee Name, ID, Salary, Department
(de *Employees
("Tyler Bennett" E10297 32000 D101)
("John Rappl" E21437 47000 D050)
("George Woltman" E00127 53500 D101)
("Adam Smith" E63535 18000 D202)
("Claire Buckman" E39876 27800 D202)
("David McClellan" E04242 41500 D101)
("Rich Holcomb" E01234 49500 D... |
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... | #PicoLisp | PicoLisp | (load "@lib/simul.l") # for 'game' function
(de display ()
(for Y (3 2 1)
(prinl " +---+---+---+")
(prin " " Y)
(for X (1 2 3)
(prin " | " (or (get *Board X Y) " ")) )
(prinl " |") )
(prinl " +---+---+---+")
(prinl " a b c") )
(de find3 (P)
(find
'((X ... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | Hanoi := function(n)
local move;
move := function(n, a, b, c) # from, through, to
if n = 1 then
Print(a, " -> ", c, "\n");
else
move(n - 1, a, c, b);
move(1, a, b, c);
move(n - 1, b, a, c);
fi;
end;
move(n, "A", "B", "C");
end;
Hanoi(1);
# A -> C
Hanoi(2);
# A -> B
# A -> C
# B -> C
Hanoi(3)... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #GAP | GAP | Hanoi := function(n)
local move;
move := function(n, a, b, c) # from, through, to
if n = 1 then
Print(a, " -> ", c, "\n");
else
move(n - 1, a, c, b);
move(1, a, b, c);
move(n - 1, b, a, c);
fi;
end;
move(n, "A", "B", "C");
end;
Hanoi(1);
# A -> C
Hanoi(2);
# A -> B
# A -> C
# B -> C
Hanoi(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
... | #Visual_Basic_.NET | Visual Basic .NET | ' Adapted from:
' http://tawani.blogspot.com/2009/02/topological-sorting-and-cyclic.html
' added/changed:
' - conversion to VB.Net (.Net 2 framework)
' - added Rosetta Code dependency format parsing
' - check & removal of self-dependencies before sorting
Module Program
Sub Main()
Dim Fields As New List(Of Field)()
... |
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... | #PHP | PHP | $radians = M_PI / 4;
$degrees = 45 * M_PI / 180;
echo sin($radians) . " " . sin($degrees);
echo cos($radians) . " " . cos($degrees);
echo tan($radians) . " " . tan($degrees);
echo asin(sin($radians)) . " " . asin(sin($radians)) * 180 / M_PI;
echo acos(cos($radians)) . " " . acos(cos($radians)) * 180 / M_PI;
echo atan(t... |
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
/ ... | #ooRexx | ooRexx |
one = .Node~new(1);
two = .Node~new(2);
three = .Node~new(3);
four = .Node~new(4);
five = .Node~new(5);
six = .Node~new(6);
seven = .Node~new(7);
eight = .Node~new(8);
nine = .Node~new(9);
one~left = two
one~right = three
two~left = four
two~right = five
three~left = six
four~left = 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... | #Nial | Nial | s := 'Hello,How,Are,You,Today'
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|H|e|l|l|o|,|H|o|w|,|A|r|e|,|Y|o|u|,|T|o|d|a|y|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
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... | #Nim | Nim | import strutils
let text = "Hello,How,Are,You,Today"
let tokens = text.split(',')
echo tokens.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 ... | #XPL0 | XPL0 | include c:\cxpl\codes;
int T0, T1, I;
[T0:= GetTime;
for I:= 1, 1_000_000 do [];
T1:= GetTime;
IntOut(0, T1-T0); Text(0, " microseconds^M^J");
] |
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 ... | #Yabasic | Yabasic | sub count(n)
local i
for i = 1 to n
next i
end sub
count(1000000)
print peek("millisrunning"), " milliseconds"
t0 = peek("millisrunning")
count(10000000)
print peek("millisrunning")-t0, " milliseconds" |
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 ... | #zkl | zkl | t:=Time.Clock.time; Atomic.sleep(3); (Time.Clock.time - t).println(); |
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... | #PL.2FI | PL/I | (subrg, stringrange, stringsize):
rank: procedure options (main); /* 10 November 2013 */
declare 1 employee (13),
2 name char (15) varying,
2 ID char (6),
2 salary fixed (5),
2 department char (4);
declare done(hbound(employee)) bit (1);
declare ptr(hbo... |
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... | #Prolog | Prolog | :- use_module('min-max.pl').
:-dynamic box/2.
:- dynamic tic_tac_toe_window/1.
% Computer begins.
tic-tac-toe(computer) :-
V is random(9),
TTT = [_,_,_,_,_,_ ,_,_,_],
nth0(V, TTT, o),
display_tic_tac_toe(TTT).
% Player begins
tic-tac-toe(me) :-
TTT = [_,_,_,_,_,_ ,_,_,_],
display_tic_tac_toe(TTT).
displ... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Go | Go | package main
import "fmt"
// a towers of hanoi solver just has one method, play
type solver interface {
play(int)
}
func main() {
var t solver // declare variable of solver type
t = new(towers) // type towers must satisfy solver interface
t.play(4)
}
// towers is example of type satisfying so... |
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
... | #Wren | Wren | class Graph {
construct new(s, edges) {
_vertices = s.split(", ")
var n = _vertices.count
_adjacency = List.filled(n, null)
for (i in 0...n) _adjacency[i] = List.filled(n, false)
for (edge in edges) _adjacency[edge[0]][edge[1]] = true
}
hasDependency(r, todo) {
... |
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... | #PicoLisp | PicoLisp | (load "@lib/math.l")
(de dtor (Deg)
(*/ Deg pi 180.0) )
(de rtod (Rad)
(*/ Rad 180.0 pi) )
(prinl
(format (sin (/ pi 4)) *Scl) " " (format (sin (dtor 45.0)) *Scl) )
(prinl
(format (cos (/ pi 4)) *Scl) " " (format (cos (dtor 45.0)) *Scl) )
(prinl
(format (tan (/ pi 4)) *Scl) " " (format (tan (dtor 4... |
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... | #PL.2FI | PL/I |
declare (x, xd, y, v) float;
x = 0.5; xd = 45;
/* angle in radians: */
v = sin(x); y = asin(v); put skip list (y);
v = cos(x); y = acos(v); put skip list (y);
v = tan(x); y = atan(v); put skip list (y);
/* angle in degrees: */
v = sind(xd); put skip list (v);
v = cosd(xd); put skip list (v);
v = tand(xd); y = a... |
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
/ ... | #Oz | Oz | declare
Tree = n(1
n(2
n(4 n(7 e e) e)
n(5 e e))
n(3
n(6 n(8 e e) n(9 e e))
e))
fun {Concat Xs}
{FoldR Xs Append nil}
end
fun {Preorder T}
case T of e then nil
[] n(V L R) then
{Concat [[V]
{Pre... |
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... | #Objeck | Objeck |
class Parse {
function : Main(args : String[]) ~ Nil {
tokens := "Hello,How,Are,You,Today"->Split(",");
each(i : tokens) {
tokens[i]->PrintLine();
};
}
} |
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... | #Objective-C | Objective-C | NSString *text = @"Hello,How,Are,You,Today";
NSArray *tokens = [text componentsSeparatedByString:@","];
NSString *result = [tokens componentsJoinedByString:@"."];
NSLog(result); |
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... | #PL.2FSQL | PL/SQL | CREATE OR REPLACE PROCEDURE "Top rank per group"(TOP_N IN PLS_INTEGER DEFAULT 3) AS
CURSOR CSR_EMP(TOP_N PLS_INTEGER) IS
SELECT CASE LINE
WHEN 10 THEN
'Tot.' || LPAD(POPULATION, 2) || ' Employees in ' || TIE_COUNT ||
' deps.Avg salary:' || TO_CHAR(SALARY, '99990.99')
... |
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... | #Python | Python |
'''
Tic-tac-toe game player.
Input the index of where you wish to place your mark at your turn.
'''
import random
board = list('123456789')
wins = ((0,1,2), (3,4,5), (6,7,8),
(0,3,6), (1,4,7), (2,5,8),
(0,4,8), (2,4,6))
def printboard():
print('\n'.join(' '.join(board[x:x+3]) for x i... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Groovy | Groovy | def tail = { list, n -> def m = list.size(); list.subList([m - n, 0].max(),m) }
final STACK = [A:[],B:[],C:[]].asImmutable()
def report = { it -> }
def check = { it -> }
def moveRing = { from, to -> to << from.pop(); report(); check(to) }
def moveStack
moveStack = { from, to, using = STACK.values().find { !(i... |
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
... | #zkl | zkl | fcn topoSort(data){ // data is L( L(root,L(leaves)),...)
allDs:=data.pump(List,fcn(rds){ T(Void.Write,Void.Write,rds[1]) }).copy();
roots:=Dictionary(data); // dictionary of root:leaves
L:=List();
S:=data.pump(List,'wrap([(r,_)]){ if(allDs.holds(r)) Void.Skip else r }).copy();
while(S){ //while S ... |
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.