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/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...
#Jsish
Jsish
#!/usr/bin/env jsish /* Top rank per group, in Jsish */ function top_rank(n) { var by_dept = group_by_dept(data); for (var dept in by_dept) { puts(dept); for (var i = 0; i < n && i < by_dept[dept].length; i++) { var emp = by_dept[dept][i]; puts(emp.name + ", id=" + emp.id...
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...
#JavaScript
JavaScript
  <!DOCTYPE html>   <html>   <head> <meta charset="utf-8" /> <title>TicTacToe</title> </head>   <body> <canvas id="canvas" width="400" height="400"></canvas>   <script> //All helper functions isBetween = (num, a, b) => { return num >= a && num <= b; }   randIn...
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#EDSAC_order_code
EDSAC order code
  [Towers of Hanoi task for Rosetta Code.] [EDSAC program, Initial Orders 2.]   T100K [load program at location 100 (arbitrary)] GK [Number of discs, in the address field] [0] P3F [<--- edit here, value 1..9] [Letters to represent the rods] [1] LF [left] [2] CF...
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 ...
#PowerShell
PowerShell
#Input Data $a=@" des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee dw01 ieee dw01 dware gtech dw02 ieee dw02 dware dw03 std synopsys dware dw03 dw02 dw01 ieee gtech dw04 dw04 ieee dw01 dware gtech dw05 dw05 ieee dware dw06 ...
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 ...
#Wren
Wren
import "/dynamic" for Enum, Tuple, Struct import "/fmt" for Fmt   var Dir = Enum.create("Dir", ["LEFT", "RIGHT", "STAY"])   var Rule = Tuple.create("Rule", ["state1", "symbol1", "symbol2", "dir", "state2"])   var Tape = Struct.create("Tape", ["symbol", "left", "right"])   class Turing { construct new(states, finalS...
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...
#Maxima
Maxima
a: %pi / 3; [sin(a), cos(a), tan(a), sec(a), csc(a), cot(a)];   b: 1 / 2; [asin(b), acos(b), atan(b), asec(1 / b), acsc(1 / b), acot(b)];   /* Hyperbolic functions are also available */ a: 1 / 2; [sinh(a), cosh(a), tanh(a), sech(a), csch(a), coth(a)], numer; [asinh(a), acosh(1 / a), atanh(a), asech(a), acsch(a), acoth(...
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 / ...
#Java
Java
import java.util.*;   public class TreeTraversal {   static class Node<T> { T value; Node<T> left; Node<T> right;   Node(T value) { this.value = value; }   void visit() { System.out.print(this.value + " "); } }   static enum ORDER { PREORDER, INORDER, POSTORDER, LEVEL }   static...
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...
#Julia
Julia
  s = "Hello,How,Are,You,Today" a = split(s, ",") t = join(a, ".")   println("The string \"", s, "\"") println("Splits into ", a) println("Reconstitutes to \"", t, "\"")  
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...
#K
K
words: "," \: "Hello,How,Are,You,Today" "." /: words
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 ...
#Perl
Perl
use Benchmark; use Memoize;   sub fac1 { my $n = shift; return $n == 0 ? 1 : $n * fac1($n - 1); } sub fac2 { my $n = shift; return $n == 0 ? 1 : $n * fac2($n - 1); } memoize('fac2');   my $result = timethese(100000, { 'fac1' => sub { fac1(50) }, 'fac2' => sub { fac2(50) }, }); Benchmark::cmpthes...
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...
#Julia
Julia
# v0.6.0   using DataFrames   df = DataFrame( EmployeeName=["Tyler Bennett", "John Rappl", "George Woltman", "Adam Smith", "Claire Buckman", "David McClellan", "Rich Holcomb", "Nathan Adams", "Richard Potter", "David Motsinger", "Tim Sampair", "Kim Arlich", "Timothy Grove"], EmployeeID = ["E10297", "E21437", "E00127", ...
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...
#Julia
Julia
const winningpositions = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9],[1, 5, 9], [7, 5, 3]]   function haswon(brd, xoro) marked = findall(x -> x == xoro, brd) for pos in winningpositions if length(pos) <= length(marked) && pos == sort(marked)[1:3] return true ...
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Eiffel
Eiffel
class APPLICATION   create make   feature {NONE} -- Initialization   make do move (4, "A", "B", "C") end   feature -- Towers of Hanoi   move (n: INTEGER; frm, to, via: STRING) require n > 0 do if n = 1 then print ("Move disk from pole " + frm + " to pole " + to + "%N") else m...
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 ...
#PureBasic
PureBasic
#EndOfDataMarker$ = "::EndOfData::" DataSection ;"LIBRARY: [LIBRARY_DEPENDENCY_1 LIBRARY_DEPENDENCY_2 ... LIBRARY_DEPENDENCY_N] Data.s "des_system_lib: [std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee]" Data.s "dw01: [ieee dw01 dware gtech]" ;Data.s "dw01: [ieee dw01 dware gtech dw04]" ;comment t...
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 ...
#Yabasic
Yabasic
// Machine definitions   name = 1 : initState = 2 : endState = 3 : blank = 4 : countOnly = true   incrementer$ = "Simple incrementer,q0,qf,B" incrementer$ = incrementer$ + ",q0,1,1,right,q0,q0,B,1,stay,qf"   threeStateBB$ = "Three-state busy beaver,a,halt,0" data "a,0,1,right,b" data "a,1,1,left,c" data "b,0,1,left,a" ...
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...
#MAXScript
MAXScript
local radians = pi / 4 local degrees = 45.0   --sine print (sin (radToDeg radians)) print (sin degrees) --cosine print (cos (radToDeg radians)) print (cos degrees) --tangent print (tan (radToDeg radians)) print (tan degrees) --arcsine print (asin (sin (radToDeg radians))) print (asin (sin degrees)) --arccosine print (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 / ...
#JavaScript
JavaScript
function BinaryTree(value, left, right) { this.value = value; this.left = left; this.right = right; } BinaryTree.prototype.preorder = function(f) {this.walk(f,['this','left','right'])} BinaryTree.prototype.inorder = function(f) {this.walk(f,['left','this','right'])} BinaryTree.prototype.postorder = funct...
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...
#Klingphix
Klingphix
( "Hello,How,Are,You,Today" "," ) split len [ get print "." print ] for   nl "End " input
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...
#Kotlin
Kotlin
fun main(args: Array<String>) { val input = "Hello,How,Are,You,Today" println(input.split(',').joinToString(".")) }
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 ...
#Phix
Phix
with javascript_semantics function identity(integer x) return x end function function total(integer num) for i=1 to 100_000_000 do num += odd(i) end for return num end function procedure time_it(integer fn) atom t0 = time() integer res = fn(4) string funcname = get_routine_info(fn...
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 ...
#Phixmonti
Phixmonti
def count for drop endfor enddef   1000000 count msec dup var t0 print " seconds" print nl   10000000 count msec t0 - print " seconds" print
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...
#Kotlin
Kotlin
// version 1.1.2   data class Employee(val name: String, val id: String, val salary: Int, val dept: String)   const val N = 2 //say   fun main(args: Array<String>) { val employees = listOf( Employee("Tyler Bennett", "E10297", 32000, "D101"), Employee("John Rappl", "E21437", 47000, "D050"), 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...
#Kotlin
Kotlin
// version 1.1.51   import java.util.Random   val r = Random() val b = Array(3) { IntArray(3) } // board -> 0: blank; -1: computer; 1: human   var bestI = 0 var bestJ = 0   fun checkWinner(): Int { for (i in 0..2) { if (b[i][0] != 0 && b[i][1] == b[i][0] && b[i][2] == b[i][0]) return b[i][0] if (b[...
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Ela
Ela
open monad io :::IO   //Functional approach hanoi 0 _ _ _ = [] hanoi n a b c = hanoi (n - 1) a c b ++ [(a,b)] ++ hanoi (n - 1) c b a   hanoiIO n = mapM_ f $ hanoi n 1 2 3 where f (x,y) = putStrLn $ "Move " ++ show x ++ " to " ++ show y   //Imperative approach using IO monad hanoiM n = hanoiM' n 1 2 3 where hanoiM' ...
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 ...
#Python
Python
try: from functools import reduce except: pass   data = { 'des_system_lib': set('std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee'.split()), 'dw01': set('ieee dw01 dware gtech'.split()), 'dw02': set('ieee dw02 dware'.split()), 'dw03': set('std ...
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 ...
#zkl
zkl
var [const] D=Dictionary; // short cut // blank symbol and terminating state(s) are Void var Lt=-1, Sy=0, Rt=1; // Left, Stay, Right   fcn printTape(tape,pos){ tape.keys.apply("toInt").sort() .pump(String,'wrap(i){ ((pos==i) and "(%s)" or " %s ").fmt(tape[i]) }) .println(); } fcn turing(state,[D]tape,[I...
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#Metafont
Metafont
Pi := 3.14159; vardef torad expr x = Pi*x/180 enddef;  % conversions vardef todeg expr x = 180x/Pi enddef; vardef sin expr x = sind(todeg(x)) enddef;  % radians version of sind vardef cos expr x = cosd(todeg(x)) enddef;  % and cosd   vardef sign expr x = if x>=0: 1 else: -1 fi enddef; % commodity   vardef tand e...
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 / ...
#jq
jq
def preorder: if length == 0 then empty else .[0], (.[1]|preorder), (.[2]|preorder) end;   def inorder: if length == 0 then empty else (.[1]|inorder), .[0] , (.[2]|inorder) end;   def postorder: if length == 0 then empty else (.[1] | postorder), (.[2]|postorder), .[0] end;   # Helper functions for lev...
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...
#Ksh
Ksh
  #!/bin/ksh   # Tokenize a string   # # Variables: # string="Hello,How,Are,You,Today" inputdelim=\, # a comma outputdelim=\. # a period   # # Functions: # # # Function _tokenize(str, indelim, outdelim) # function _tokenize { typeset _str ; _str="$1" typeset _ind ; _ind="$2" typeset _outd ; _outd="$3"   while [[ ...
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...
#LabVIEW
LabVIEW
  {S.replace , by . in Hello,How,Are,You,Today}. -> 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 ...
#Picat
Picat
import cp.   go => println("time/1 for 201 queens:"), time2(once(queens(201,_Q))), nl,    % time1b/1 is a used defined function (using statistics/2) Time = time1b($once(queens(28,Q2))), println(Q2), printf("28-queens took %dms\n", Time), nl.   % N-queens problem. % N: number of queens to place % Q: the s...
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 ...
#PicoLisp
PicoLisp
: (bench (do 1000000 (* 3 4))) 0.080 sec -> 12
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...
#Ksh
Ksh
  #!/bin/ksh exec 2> /tmp/Top_rank_per_group.err   # Top rank per group   # # Variables: # integer TOP_NUM=2   typeset -T Empsal_t=( typeset -h 'Employee Name' ename='' typeset -h 'Employee ID' eid='' typeset -i -h 'Employee Salary' esalary typeset -h 'Emplyee Department' edept=''   function init_employee ...
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...
#Lasso
Lasso
[ session_start('user') session_addvar('user', 'matrix') session_addvar('user', 'winrecord') session_addvar('user', 'turn') var(matrix)->isNotA(::array) ? var(matrix = array('-','-','-','-','-','-','-','-','-')) var(winrecord)->isNotA(::array) ? var(winrecord = array) var(turn)->isNotA(::string) ? var(turn = 'x')   if(...
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Elena
Elena
move = (n,from,to,via) { if (n == 1) { console.printLine("Move disk from pole ",from," to pole ",to) } else { move(n-1,from,via,to); move(1,from,to,via); move(n-1,via,to,from) } };
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 ...
#R
R
  deps <- list( "des_system_lib" = c("std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee"), "dw01" = c("ieee", "dw01", "dware", "gtech", "dw04"), "dw02" = c("ieee", "dw02", "dware"), "dw03" = c("std", "synopsys", "dware", "dw03", "dw02", "dw01", "ieee", "gtech"), "dw04" = c("dw04", "iee...
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...
#MiniScript
MiniScript
pi3 = pi/3 degToRad = pi/180 print "sin PI/3 radians = " + sin(pi3) print "sin 60 degrees = " + sin(60*degToRad) print "arcsin 0.5 in radians = " + asin(0.5) print "arcsin 0.5 in degrees = " + asin(0.5)/degToRad print "cos PI/3 radians = " + cos(pi3) print "cos 60 degrees = " + cos(60*degToRad) print "arccos 0.5 in rad...
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 / ...
#Julia
Julia
tree = Any[1, Any[2, Any[4, Any[7, Any[], Any[]], Any[]], Any[5, Any[], Any[]]], Any[3, Any[6, Any[8, Any[], Any[]], ...
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...
#Lambdatalk
Lambdatalk
  {S.replace , by . in Hello,How,Are,You,Today}. -> 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 ...
#Pike
Pike
  void get_some_primes() { int i; while(i < 10000) i = i->next_prime(); }   void main() { float time_wasted = gauge( get_some_primes() ); write("Wasted %f CPU seconds calculating primes\n", time_wasted); }  
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 ...
#PL.2FI
PL/I
declare (start_time, finish_time) float (18);   start_time = secs();   do i = 1 to 10000000; /* something to be repeated goes here. */ end; finish_time = secs();   put skip edit ('elapsed time=', finish_time - start_time, ' seconds') (A, F(10,3), A); /* gives the result to thousandths of a second. */   /* Note...
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...
#Lua
Lua
N = 2   lst = { { "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...
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...
#Lingo
Lingo
global $ -- object representing simple framework global gBoard -- current board image global gBoardTemplate -- empty board image global gHumanChip -- cross image global gComputerChip -- circle image global gM -- 3x3 matrix storing game state: 0=free cell, 1=human cell, -1=computer cell global gStep -- index of current ...
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Elixir
Elixir
defmodule RC do def hanoi(n) when 0<n and n<10, do: hanoi(n, 1, 2, 3)   defp hanoi(1, f, _, t), do: move(f, t) defp hanoi(n, f, u, t) do hanoi(n-1, f, t, u) move(f, t) hanoi(n-1, u, f, t) end   defp move(f, t), do: IO.puts "Move disk from #{f} to #{t}" end   RC.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 ...
#Racket
Racket
  #lang racket   (define G (make-hash '((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)) ...
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...
#.D0.9C.D0.9A-61.2F52
МК-61/52
sin С/П Вx cos С/П Вx tg С/П Вx arcsin С/П Вx arccos С/П Вx arctg С/П
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 / ...
#Kotlin
Kotlin
data class Node(val v: Int, var left: Node? = null, var right: Node? = null) { override fun toString() = "$v" }   fun preOrder(n: Node?) { n?.let { print("$n ") preOrder(n.left) preOrder(n.right) } }   fun inorder(n: Node?) { n?.let { inorder(n.left) print("$n ") ...
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...
#Lang5
Lang5
'Hello,How,Are,You,Today ', 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...
#LDPL
LDPL
  DATA: explode/words is text vector explode/index is number explode/string is text explode/length is number explode/stringlength is number explode/current-token is text explode/char is text explode/separator is text i is number   PROCEDURE: # Ask for a sentence display "Enter a sentence: " accept explode/string   # De...
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 ...
#PowerShell
PowerShell
  function fun($n){ $res = 0 if($n -gt 0) { 1..$n | foreach{ $a, $b = $_, ($n+$_) $res += $a + $b }   } $res } "$((Measure-Command {fun 10000}).TotalSeconds) 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 ...
#PureBasic
PureBasic
Procedure Foo(Limit) Protected i, palindromic, String$ For i=0 To Limit String$=Str(i) If String$=ReverseString(String$) palindromic+1 EndIf Next ProcedureReturn palindromic EndProcedure   If OpenConsole() Define Start, Stop, cnt PrintN("Starting timing of a calculation,") PrintN("for th...
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...
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { ' erase stack of values, so we can add data Flush Input "N=",N Enum Departments {D050,D101,D190,D202}   \\ Inventory Department need unique keys Inventory Department \\ each item in this inventory should be an inventory too Class Empl { 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...
#Lua
Lua
#!/usr/bin/env luajit ffi=require"ffi" local function printf(fmt,...) io.write(string.format(fmt, ...)) end local board="123456789" -- board local pval={1, -1} -- player 1=1 2=-1 for negamax local pnum={} for k,v in ipairs(pval) do pnum[v]=k end local symbol={'X','O'} -- default symbols X and O local isymbol={} f...
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Emacs_Lisp
Emacs Lisp
(defun move (n from to via) (if (= n 1) (message "Move from %S to %S" from to) (move (- n 1) from via to) (message "Move from %S to %S" from to) (move (- n 1) via to from)))
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 ...
#Raku
Raku
sub print_topo_sort ( %deps ) { my %ba; for %deps.kv -> $before, @afters { for @afters -> $after { %ba{$before}{$after} = 1 if $before ne $after; %ba{$after} //= {}; } }   while %ba.grep( not *.value )».key -> @afters { say ~@afters.sort; %ba{@afte...
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...
#Modula-2
Modula-2
MODULE Trig; FROM RealMath IMPORT pi,sin,cos,tan,arctan,arccos,arcsin; FROM RealStr IMPORT RealToStr; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE WriteReal(v : REAL); VAR buf : ARRAY[0..31] OF CHAR; BEGIN RealToStr(v, buf); WriteString(buf) END WriteReal;   VAR theta : REAL; BEGIN theta :...
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 / ...
#Lambdatalk
Lambdatalk
- {W.equal? word1 word2} returns true or false - {S.replace rex by exp1 in exp2} replaces a regular expression by some expression in another one - {S.sort comp words} sorts the sequence of words according to comp - {A.new words} creates a new array from the sequence of wor...
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...
#LFE
LFE
  > (set split (string:tokens "Hello,How,Are,You,Today" ",")) ("Hello" "How" "Are" "You" "Today") > (string:join split ".") "Hello.How.Are.You.Today"  
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Lingo
Lingo
input = "Hello,How,Are,You,Today" _player.itemDelimiter = "," output = "" repeat with i = 1 to input.item.count put input.item[i]&"." after output end repeat delete the last char of output put output -- "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 ...
#Python
Python
import sys, timeit def usec(function, arguments): modname, funcname = __name__, function.__name__ timer = timeit.Timer(stmt='%(funcname)s(*args)' % vars(), setup='from %(modname)s import %(funcname)s; args=%(arguments)r' % vars()) try: t, N = 0, 1 while t < 0.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 ...
#R
R
# A task foo <- function() { for(i in 1:10) { mat <- matrix(rnorm(1e6), nrow=1e3) mat^-0.5 } } # Time the task timer <- system.time(foo()) # Extract the processing time timer["user.self"]
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
InitialList ={{"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",...
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...
#M2000_Interpreter
M2000 Interpreter
  Module Tic.Tac.Toe { Dim Board$(1 to 3, 1 to 3)=" " WinGame=False p=Board$() RandomPosition=lambda -> { =(random(1,3), random(1,3)) }   BoardItemEmpty=Lambda p (x, y) -> { =Array$(p, x, y)=" " } BoardSetItem=Lambda p (x, y, w$) -> { l...
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Erlang
Erlang
move(1, F, T, _V) -> io:format("Move from ~p to ~p~n", [F, T]); move(N, F, T, V) -> move(N-1, F, V, T), move(1 , F, T, V), move(N-1, V, T, F).
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 ...
#REXX
REXX
/*REXX pgm does a topological sort (orders such that no item precedes a dependent item).*/ iDep.= 0; iPos.= 0; iOrd.= 0 /*initialize some stemmed arrays to 0.*/ nL= 15; nd= 44; nc= 69 /* " " "parms" and indices.*/ label= 'DES_SYSTEM_LIB DW01 DW02 DW03 ...
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...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary utf8   numeric digits 30   parse 'Radians Degrees angle' RADIANS DEGREES ANGLE .; parse 'sine cosine tangent arcsine arccosine arctangent' SINE COSINE TANGENT ARCSINE ARCCOSINE ARCTANGENT .   trigVals = '' trigVals[RADIANS, ANGLE ] = (Rexx...
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 / ...
#Lingo
Lingo
-- parent script "BinaryTreeNode"   property _val, _left, _right   on new (me, val) me._val = val return me end   on getValue (me) return me._val end   on setLeft (me, node) me._left = node end   on setRight (me, node) me._right = node end   on getLeft (me) return me._left end   on getRight (me) return me...
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...
#Logo
Logo
to split :str :sep output parse map [ifelse ? = :sep ["| |] [?]] :str 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...
#Logtalk
Logtalk
  :- object(spliting).   :- public(convert/2). :- mode(convert(+atom, -atom), one).   convert(StringIn, StringOut) :- atom_chars(StringIn, CharactersIn), phrase(split(',', Tokens), CharactersIn), phrase(split('.', Tokens), CharactersOut), atom_chars(StringOut, CharactersOut)....
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 ...
#Racket
Racket
  #lang racket (define (fact n) (if (zero? n) 1 (* n (fact (sub1 n))))) (time (fact 5000))  
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 ...
#Raku
Raku
my $start = now; (^100000).pick(1000); say now - $start;
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...
#Nim
Nim
import algorithm   type Record = tuple[name, id: string; salary: int; department: string]   var people = [("Tyler Bennett", "E10297", 32000, "D101"), ("John Rappl", "E21437", 47000, "D050"), ("George Woltman", "E00127", 53500, "D101"), ("Adam Smith", "E63535", 18000, "D202"), ...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
DynamicModule[{board = ConstantArray[0, {3, 3}], text = "Playing...", first, rows = Join[#, Transpose@#, {Diagonal@#, Diagonal@Reverse@#}] &}, Column@{Graphics[{Thickness[.02], Table[With[{i = i, j = j}, Button[{White, Rectangle[{i, j} - 1, {i, j}], Black, Dynamic[Switch[board[[i, j]], ...
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#ERRE
ERRE
  !----------------------------------------------------------- ! HANOI.R : solve tower of Hanoi puzzle using a recursive ! modified algorithm. !-----------------------------------------------------------   PROGRAM HANOI   !$INTEGER   !VAR I,J,MOSSE,NUMBER   PROCEDURE PRINTMOVE LOCAL SOURCE$,DEST$ MOSSE=MOSSE+1 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 ...
#Ruby
Ruby
require 'tsort' class Hash include TSort alias tsort_each_node each_key def tsort_each_child(node, &block) fetch(node).each(&block) end end   depends = {} DATA.each do |line| key, *libs = line.split depends[key] = libs libs.each {|lib| depends[lib] ||= []} end   begin p depends.tsort depends["dw01...
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...
#Nim
Nim
import math, strformat   let rad = Pi/4 let deg = 45.0   echo &"Sine: {sin(rad):.10f} {sin(degToRad(deg)):13.10f}" echo &"Cosine : {cos(rad):.10f} {cos(degToRad(deg)):13.10f}" echo &"Tangent: {tan(rad):.10f} {tan(degToRad(deg)):13.10f}" echo &"Arcsine: {arcsin(sin(rad)):.10f} {radToDeg(arcsin(sin(degToRa...
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 / ...
#Logo
Logo
; nodes are [data left right], use "first" to get data   to node.left :node if empty? butfirst :node [output []] output first butfirst :node end to node.right :node if empty? butfirst :node [output []] if empty? butfirst butfirst :node [output []] output first butfirst butfirst :node end to max :a :b 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...
#Lua
Lua
function string:split (sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end   local str = "Hello,How,Are,You,Today" print(table.concat(str: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...
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Function Tokenize$(s){ \\ letter$ pop a string from stack of values \\ shift 2 swap top two values on stack of values fold1=lambda m=1 ->{ shift 2 :if m=1 then m=0:drop: push letter$ else push letter$+"."+letter$ } =s#fold$(fold1) } Print Tokenize$(piece$("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 ...
#Raven
Raven
define doId use $x $x dup * $x /   define doPower use $v, $p $v $p pow   define doSort group 20000 each choose list sort reverse   define timeFunc use $fName time as $t1 $fName "" prefer call time as $t2 $fName $t2 $t1 -"%.4g secs for %s\n" print   "NULL" timeFunc 42 "doId" timeFunc 12 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 ...
#Retro
Retro
: .runtime ( a- ) time [ do time ] dip - "\n%d\n" puts ;   : test 20000 [ putn space ] iterd ; &test .runtime
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 ...
#REXX
REXX
/*REXX program displays the elapsed time for a REXX function (or subroutine). */ arg reps . /*obtain an optional argument from C.L.*/ if reps=='' then reps=100000 /*Not specified? No, then use default.*/ call time 'Reset' /*only the 1st character is examined. ...
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...
#OCaml
OCaml
open StdLabels   let to_string (name,_,s,_) = (Printf.sprintf "%s (%d)" name s)   let take n li = let rec aux i acc = function | _ when i >= n -> (List.rev acc) | [] -> (List.rev acc) | x::xs -> aux (succ i) (x::acc) xs in aux 0 [] li ;;   let toprank data n = let len = List.length data in let h = Hasht...
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...
#MATLAB
MATLAB
function TicTacToe   % Set up the board (one for each player) boards = false(3, 3, 2); % Players' pieces rep = [' 1 | 4 | 7' ; ' 2 | 5 | 8' ; ' 3 | 6 | 9'];   % Prompt user with options fprintf('Welcome to Tic-Tac-Toe!\n') nHumans = str2double(input('Enter the number of human players: '...
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Excel
Excel
SHOWHANOI =LAMBDA(n, FILTERP( LAMBDA(x, "" <> x) )( HANOI(n)("left")("right")("mid") ) )     HANOI =LAMBDA(n, LAMBDA(l, LAMBDA(r, LAMBDA(m, IF(0 = n, "", LET( next, n - 1, ...
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 ...
#Rust
Rust
use std::boxed::Box; use std::collections::{HashMap, HashSet};   #[derive(Debug, PartialEq, Eq, Hash)] struct Library<'a> { name: &'a str, children: Vec<&'a str>, num_parents: usize, }   fn build_libraries(input: Vec<&str>) -> HashMap<&str, Box<Library>> { let mut libraries: HashMap<&str, Box<Library>> ...
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...
#OCaml
OCaml
let pi = 4. *. atan 1.   let radians = pi /. 4. let degrees = 45.;;   Printf.printf "%f %f\n" (sin radians) (sin (degrees *. pi /. 180.));; Printf.printf "%f %f\n" (cos radians) (cos (degrees *. pi /. 180.));; Printf.printf "%f %f\n" (tan radians) (tan (degrees *. pi /. 180.));; let arcsin = asin (sin radians);; Printf...
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 / ...
#Logtalk
Logtalk
  :- object(tree_traversal).   :- public(orders/1). orders(Tree) :- write('Pre-order: '), pre_order(Tree), nl, write('In-order: '), in_order(Tree), nl, write('Post-order: '), post_order(Tree), nl, write('Level-order: '), level_order(Tree).   :- public(orders/0). ord...
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...
#M4
M4
define(`s',`Hello,How,Are,You,Today') define(`set',`define(`$1[$2]',`$3')') define(`get',`defn($1[$2])') define(`n',0) define(`fill', `set(a,n,$1)`'define(`n',incr(n))`'ifelse(eval($#>1),1,`fill(shift($@))')') fill(s) define(`j',0) define(`show', `ifelse(eval(j<n),1,`get(a,j).`'define(`j',incr(j))`'show')') show
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...
#Maple
Maple
StringTools:-Join(StringTools:-Split("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 ...
#Ring
Ring
  beginTime = TimeList()[13] for n = 1 to 10000000 n = n + 1 next endTime = TimeList()[13] elapsedTime = endTime - beginTime see "Elapsed time = " + elapsedTime + nl  
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 ...
#Ruby
Ruby
require 'benchmark'   Benchmark.bm(8) do |x| x.report("nothing:") { } x.report("sum:") { (1..1_000_000).inject(4) {|sum, x| sum + x} } end
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...
#Oforth
Oforth
Object Class new: Employee(name, id, salary, dep)   Employee method: initialize  := dep  := salary := id := name ; Employee method: salary @salary ; Employee method: dep @dep ; Employee method: << "[" << @dep << "," << @name << "," << @salary << "]" << ;   : topRank(n) | employees | ListBuffer new ->employ...
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...
#mIRC_Scripting_Language
mIRC Scripting Language
alias ttt { if ($2 isin %ttt) || (!%ttt) { var %ttt~ = $remove($iif(%ttt,%ttt,1 2 3 4 5 6 7 8 9),$2,X,O) var %ttt~~ = $replace($iif(%ttt,%ttt,1 2 3 4 5 6 7 8 9),$2,X) set %ttt $replace(%ttt~~,$iif(($regex(%ttt~~,/(?:O . . (?:(?:. O .|O) . . (\d)|(?:. (\d) .|(\d)) . . O)|(\d) . . (?:. O .|O) . . O|. . (?:O...
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Ezhil
Ezhil
  # (C) 2013 Ezhil Language Project # Tower of Hanoi – recursive solution   நிரல்பாகம் ஹோனாய்(வட்டுகள், முதல்அச்சு, இறுதிஅச்சு,வட்டு)   @(வட்டுகள் == 1 ) ஆனால் பதிப்பி “வட்டு ” + str(வட்டு) + “ஐ \t (” + str(முதல்அச்சு) + “ —> ” + str(இறுதிஅச்சு)+ “) அச்சிற்கு நகர்த்துக.” இல்லை   @( ["இ", "அ", "ஆ"] இல் ...
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 ...
#Scheme
Scheme
  (import (chezscheme)) (import (srfi srfi-1))     (define (remove-self-dependency pair) (let ((key (car pair)) (value (cdr pair))) (cons key (remq key value))))w   (define (remove-self-dependencies alist) (map remove-self-dependency alist))   (define (add-missing-items dependencies) (let loop ((items...
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...
#Octave
Octave
function d = degree(rad) d = 180*rad/pi; endfunction   r = pi/3; rd = degree(r);   funcs = { "sin", "cos", "tan", "sec", "cot", "csc" }; ifuncs = { "asin", "acos", "atan", "asec", "acot", "acsc" };   for i = 1 : numel(funcs) v = arrayfun(funcs{i}, r); vd = arrayfun(strcat(funcs{i}, "d"), rd); iv = arrayfun(ifun...
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 / ...
#Lua
Lua
-- Utility local function append(t1, t2) for _, v in ipairs(t2) do table.insert(t1, v) end end   -- Node class local Node = {} Node.__index = Node   function Node:order(order) local r = {} append(r, type(self[order[1]]) == "table" and self[order[1]]:order(order) or {self[order[1]]}) append(r...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
StringJoin@StringSplit["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 ...
#Rust
Rust
// 20210224 Rust programming solution   use rand::Rng; use std::time::{Instant};   fn custom_function() {   let mut i = 0; let mut rng = rand::thread_rng(); let n1: f32 = rng.gen();   while i < ( 1000000 + 1000000 * ( n1.log10() as i32 ) ) { i = i + 1; } }   fn main() {   let start = Instant::no...