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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190
#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 McClellan' e04242 41500 d101] ['Rich Holcomb' e01234 49500 d202] ['Nathan Adams' e41298 21900 d050] ['Richard Potter' e43128 15900 d101] ['David Motsinger' e27002 19250 d202] ['Tim Sampair' e03033 27000 d101] ['Kim Arlich' e10001 57000 d190] ['Timothy Grove' e16398 29900 d190]]   fun {$ [Name Id Salary Department]} employee(name:Name id:Id salary:Salary department:Department) end}   fun {TopEarners Employees N} {Record.map {GroupBy Employees department} fun {$ Employees} {List.take {Sort Employees CompareSalary} N} end} end   fun {CompareSalary E1 E2} E1.salary > E2.salary end   %% Groups the records Xs by the value of feature F and returns %% the result as a record that maps values of F to list of records. fun {GroupBy Xs F} Groups = {Dictionary.new} in for X in Xs do Groups.(X.F) := X|{CondSelect Groups X.F nil} end {Dictionary.toRecord unit Groups} end in {Inspect {TopEarners Data 3}}
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedia tic-tac-toe.
#.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 | a, b -> printf "Move disc from %A to %A\n" a b) 0
http://rosettacode.org/wiki/Topological_sort
Topological sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon. The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on. A tool exists that extracts library dependencies. Task Write a function that will return a valid compile order of VHDL libraries from their dependencies. Assume library names are single words. Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given. Any self dependencies should be ignored. Any un-orderable dependencies should be flagged. Use the following data as an example: LIBRARY LIBRARY DEPENDENCIES ======= ==================== des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee dw01 ieee dw01 dware gtech dw02 ieee dw02 dware dw03 std synopsys dware dw03 dw02 dw01 ieee gtech dw04 dw04 ieee dw01 dware gtech dw05 dw05 ieee dware dw06 dw06 ieee dware dw07 ieee dware dware ieee dware gtech ieee gtech ramlib std ieee std_cell_lib ieee std_cell_lib synopsys Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01. C.f.   Topological sort/Extracted top item. There are two popular algorithms for topological sorting:   Kahn's 1962 topological sort [1]   depth-first search [2] [3]
#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}.values.len == 0 }.sort; afters.len || break; say afters.join(" "); ba.delete(afters...); ba.values.each { |v| v.delete(afters...) }; };   say (ba.len ? "Cicle found! #{ba.keys.sort}" : "---"); }   var deps = Hash.new( des_system_lib => < std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee >, dw01 => < ieee dw01 dware gtech >, dw02 => < ieee dw02 dware >, dw03 => < std synopsys dware dw03 dw02 dw01 ieee gtech >, dw04 => < dw04 ieee dw01 dware gtech >, dw05 => < dw05 ieee dware >, dw06 => < dw06 ieee dware >, dw07 => < ieee dware >, dware => < ieee dware >, gtech => < ieee gtech >, ramlib => < std ieee >, std_cell_lib => < ieee std_cell_lib >, synopsys => < > );   print_topo_sort(deps); deps{:dw01}.append('dw04'); # Add unresolvable dependency print_topo_sort(deps);
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle). For the inverse functions,   use the same number and convert its answer to radians and degrees. If your language does not have trigonometric functions available or only has some available,   write functions to calculate the functions based on any   known approximation or identity.
#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.Out z << " - " << z asDegree << cr   rad cos acos ->z System.Out z << " - " << z asDegree << cr   rad tan atan ->z System.Out z << " - " << z asDegree << cr   printcr   System.Out hyp sinh << " - " << hyp sinh asinh << cr System.Out hyp cosh << " - " << hyp cosh acosh << cr System.Out hyp tanh << " - " << hyp tanh atanh << cr ;
http://rosettacode.org/wiki/Tree_traversal
Tree traversal
Task Implement a binary tree where each node carries an integer,   and implement:   pre-order,   in-order,   post-order,     and   level-order   traversal. Use those traversals to output the following tree: 1 / \ / \ / \ 2 3 / \ / 4 5 6 / / \ 7 8 9 The correct output should look like this: preorder: 1 2 4 7 5 3 6 8 9 inorder: 7 4 2 5 1 8 6 9 3 postorder: 7 4 5 2 8 9 6 3 1 level-order: 1 2 3 4 5 6 7 8 9 See also   Wikipedia article:   Tree traversal.
#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);" "; If len(T#val(0))>0 then printtree(T#val(0)) If len(T#val(2))>0 then printtree(T#val(2)) end sub } preorder Tree   Module inorder (T) { Print "inorder: "; printtree(T) Print sub printtree(T) If len(T#val(0))>0 then printtree(T#val(0)) Print T#val(1);" "; If len(T#val(2))>0 then printtree(T#val(2)) end sub } inorder Tree   Module postorder (T) { Print "postorder: "; printtree(T) Print sub printtree(T) If len(T#val(0))>0 then printtree(T#val(0)) If len(T#val(2))>0 then printtree(T#val(2)) Print T#val(1);" "; end sub } postorder Tree   Module level_order (T) { Print "level-order: "; Stack New { printtree(T) if empty then exit Read T Loop } Print sub printtree(T) If Len(T)>0 then Print T#val(1);" "; Data T#val(0), T#val(2) end if end sub } level_order Tree } CheckIt  
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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 1000000 do result +:= number; end for; end func;   const func duration: timeIt (ref func integer: aFunction) is func result var duration: result is duration.value; local var time: before is time.value; begin before := time(NOW); ignore(aFunction); result := time(NOW) - before; end func;   const proc: main is func begin writeln("Identity(4) takes " <& timeIt(identity(4))); writeln("Sum(4) takes " <& timeIt(sum(4))); end func;
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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) }, ))   benchmark.cmpthese(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,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190
#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,"D050"], ["Richard Potter","E43128",15900,"D101"], ["David Motsinger","E27002",19250,"D202"], ["Tim Sampair","E03033",27000,"D101"], ["Kim Arlich","E10001",57000,"D190"], ["Timothy Grove","E16398",29900,"D190"]]};   top(n,V)={ my(dept=vecsort(vector(#V,i,V[i][4]),,8),d,v); for(i=1,#dept, d=dept[i]; print(d); v=select(u->u[4]==d,V); v=vecsort(v,3,4); \\ Sort by salary (#3) descending (flag 0x4) for(j=1,min(n,#v), print("\t",v[j][1],"\t",v[j][2],"\t",v[j][3]) ) ); };   top(2,V)
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedia tic-tac-toe.
#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], [3, 5, 7]]   template toIndex(ch: char): int = ## Convert a character to an index in board. ord(ch) - ord('0')   proc print(board: Board) = for i in [1, 4, 7]: echo board[i..(i + 2)].join(" ")   proc score(board: Board): Option[Score] = for w in Wins: let b = board[w[0]] if b in "XO" and w.allIt(board[it] == b): return some (b, w) result = none(Score)   proc finished(board: Board): bool = board.allIt(it in "XO")   proc space(board: Board): seq[char] = for b in board: if b notin "XO": result.add b   proc myTurn(board: var Board; xo: char): char = let options = board.space() result = options.sample() board[result.toIndex] = xo   proc myBetterTurn(board: var Board; xo: char): int = let ox = if xo == 'X': 'O' else: 'X' var oneBlock = NoChoice let options = board.space.mapIt(it.toIndex) block search: for choice in options: var brd = board brd[choice] = xo if brd.score.isSome: result = choice break search if oneBlock == NoChoice: brd[choice] = ox if brd.score.isSome: oneBlock = choice result = if oneBlock != NoChoice: oneBlock else: options.sample() board[result] = xo   proc yourTurn(board: var Board; xo: char): int = let options = board.space() var choice: char while true: stdout.write "\nPut your $# in any of these positions: $# ".format(xo, options.join()) let input = stdin.readLine().strip() if input.len == 1 and input[0] in options: choice = input[0] break echo "Whoops I don't understand the input" result = choice.toIndex board[result] = xo   proc me(board: var Board; xo: char): Option[Score] = board.print() echo "\nI go at ", board.myBetterTurn(xo) result = board.score()   proc you(board: var Board; xo: char): Option[Score] = board.print() echo "\nYou went at ", board.yourTurn(xo) result = board.score()   proc play() = while not board.finished(): let score = board.me('X') if score.isSome: board.print() let (winner, line) = score.get() echo "\n$# wins along ($#).".format(winner, line.join(", ")) return if not board.finished(): let score = board.you('O') if score.isSome: board.print() let (winner, line) = score.get() echo "\n$# wins along ($#).".format(winner, line.join(", ")) return echo "\nA draw."   echo "Tic-tac-toe game player." echo "Input the index of where you wish to place your mark at your turn." randomize() play()
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon. The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on. A tool exists that extracts library dependencies. Task Write a function that will return a valid compile order of VHDL libraries from their dependencies. Assume library names are single words. Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given. Any self dependencies should be ignored. Any un-orderable dependencies should be flagged. Use the following data as an example: LIBRARY LIBRARY DEPENDENCIES ======= ==================== des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee dw01 ieee dw01 dware gtech dw02 ieee dw02 dware dw03 std synopsys dware dw03 dw02 dw01 ieee gtech dw04 dw04 ieee dw01 dware gtech dw05 dw05 ieee dware dw06 dw06 ieee dware dw07 ieee dware dware ieee dware gtech ieee gtech ramlib std ieee std_cell_lib ieee std_cell_lib synopsys Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01. C.f.   Topological sort/Extracted top item. There are two popular algorithms for topological sorting:   Kahn's 1962 topological sort [1]   depth-first search [2] [3]
#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", "dw01", "dware", "gtech"]), ("dw05", ["dw05", "ieee", "dware"]), ("dw06", ["dw06", "ieee", "dware"]), ("dw07", ["ieee", "dware"]), ("dware", ["ieee", "dware"]), ("gtech", ["ieee", "gtech"]), ("ramlib", ["std", "ieee"]), ("std_cell_lib", ["ieee", "std_cell_lib"]), ("synopsys", []) ]   struct Library { var name: String var children: [String] var numParents: Int }   func buildLibraries(_ input: [(String, [String])]) -> [String: Library] { var libraries = [String: Library]()   for (name, parents) in input { var numParents = 0   for parent in parents where parent != name { numParents += 1   libraries[parent, default: Library(name: parent, children: [], numParents: 0)].children.append(name) }   libraries[name, default: Library(name: name, children: [], numParents: numParents)].numParents = numParents }   return libraries }   func topologicalSort(libs: [String: Library]) -> [String]? { var libs = libs var needsProcessing = Set(libs.keys) var options = libs.compactMap({ $0.value.numParents == 0 ? $0.key : nil }) var sorted = [String]()   while let cur = options.popLast() { for children in libs[cur]?.children ?? [] { libs[children]?.numParents -= 1   if libs[children]?.numParents == 0 { options.append(libs[children]!.name) } }   libs[cur]?.children.removeAll()   sorted.append(cur) needsProcessing.remove(cur) }   guard needsProcessing.isEmpty else { return nil }   return sorted }   print(topologicalSort(libs: buildLibraries(libs))!)
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle). For the inverse functions,   use the same number and convert its answer to radians and degrees. If your language does not have trigonometric functions available or only has some available,   write functions to calculate the functions based on any   known approximation or identity.
#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 observation show that sometimes the last one to three digits of the returned values are not correct. Many years ago I experimented with implementing these functions in Rexx with its virtually unlimited precision. The rxm class is intended to provide the same functionality as rxMath with no limit on the specified or implied precision. Functions in class rxm and invocation syntax are the same as in the rxMath library. They are implemented as routines which perform the checking of argument values and invoke the corresponding methods. Here is a list of the supported functions and a concise syntax specification. The arguments are represented by these letters: x is the value for which the respective function must be evaluated. b and c for RxCalcPower are base and exponent, respectively. p if specified is the desired precision (number of digits) in the result. It can be any integer from 1 to 999999. See below for the default used. u if specified, is the unit of x given to the trigonometric functions or the unit of the value returned by the Arcus functions. It can be 'R', 'D', or 'G' for radians, degrees, or grades, respectively. See below for the default used. Trigonometric functions: • rxmCos(x[,[p][,u]]) • rxmCotan(x[,[p][,u]]) • rxmSin(x[,[p][,u]]) • rxmTan(x[,[p][,u]]) Arcus functions: • rxmArcCos(x[,[p][,u]]) • rxmArcSin(x[,[p][,u]]) • rxmArcTan(x[,[p][,u]]) Hyperbolic functions: • rxmCosH(x[,p]) • rxmSinH(x[,p]) • rxmTanH(x[,p]) • rxmExp(x[,p]) e**x • rxmLog(x[,p]) Natural logarithm of x • rxmLog10(x[,p]) Brigg's logarithm of x • rxmSqrt(x[,p]) Square root of x • rxmPower(b,c[,p]) b**c • rxmPi([p]) pi to the specified or default precision Values used for p and u if these are omitted in the invocation ============================================================== The directive ::REQUIRES rxm.cls creates an instance of the class .local~my.rxm=.rxm~new(16,"D") which sets the defaults for p=16 and u='D'. These are used when p or u are omitted in a function invocation. They can be changed by changing the respective class attributes as follows: .locaL~my.rxm~precision=50 .locaL~my.rxm~type='R' The current setting of these attributes can be retrieved as follows: .locaL~my.rxm~precision() .locaL~my.rxm~type() While I tried to get full compatibility there remain a few (actually very few) differences: rxCalcTan(90) raises the Syntax condition (will be fixed in the next ooRexx release) rxCalcexp(x) limits x to 709. or so and returns '+infinity' for larger exponents
http://rosettacode.org/wiki/Tree_traversal
Tree traversal
Task Implement a binary tree where each node carries an integer,   and implement:   pre-order,   in-order,   post-order,     and   level-order   traversal. Use those traversals to output the following tree: 1 / \ / \ / \ 2 3 / \ / 4 5 6 / / \ 7 8 9 The correct output should look like this: preorder: 1 2 4 7 5 3 6 8 9 inorder: 7 4 2 5 1 8 6 9 3 postorder: 7 4 5 2 8 9 6 3 1 level-order: 1 2 3 4 5 6 7 8 9 See also   Wikipedia article:   Tree traversal.
#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[Table[Level[a, {n}], {n, 0, Depth@a}]] /. {b_Integer[__] :> b};
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190
#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: 'D101'), (name: 'John Rappl'; ID: 'E21437'; salary: 47000; dept: 'D050'), (name: 'George Woltman'; ID: 'E00127'; salary: 53500; dept: 'D101'), (name: 'Adam Smith'; ID: 'E63535'; salary: 18000; dept: 'D202'), (name: 'Claire Buckman'; ID: 'E39876'; salary: 27800; dept: 'D202'), (name: 'David McClellan'; ID: 'E04242'; salary: 41500; dept: 'D101'), (name: 'Rich Holcomb'; ID: 'E01234'; salary: 49500; dept: 'D202'), (name: 'Nathan Adams'; ID: 'E41298'; salary: 21900; dept: 'D050'), (name: 'Richard Potter'; ID: 'E43128'; salary: 15900; dept: 'D101'), (name: 'David Motsinger'; ID: 'E27002'; salary: 19250; dept: 'D202'), (name: 'Tim Sampair'; ID: 'E03033'; salary: 27000; dept: 'D101'), (name: 'Kim Arlich'; ID: 'E10001'; salary: 57000; dept: 'D190'), (name: 'Timothy Grove'; ID: 'E16398'; salary: 29900; dept: 'D190') );   function CompareSalary(Item1, Item2: PTData): longint; begin CompareSalary := Item2^.salary - Item1^.salary; end;   var depts : TStringList; deptList: Tlist; number, i, j: integer;   begin write ('Enter the number of ranks: '); readln (number); depts := TStringList.Create; depts.Sorted := true; depts.Duplicates := dupIgnore; for i := low(data) to high(data) do depts.Add(data[i].dept);   for i := 0 to depts.Count - 1 do begin writeln; writeln('Department: ', depts.Strings[i]); deptList := TList.Create; for j := low(data) to high(data) do if data[j].dept = depts.Strings[i] then deptList.Add(@data[j]); deptList.Sort(TListSortCompare(@CompareSalary)); for j := 0 to min(deptList.count, number) - 1 do begin write (PTData(deptList.Items[j])^.name, ', '); write ('ID: ', PTData(deptList.Items[j])^.ID, ', '); write ('Salary: ', PTData(deptList.Items[j])^.Salary); writeln; end; deptList.Destroy; end; end.  
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedia tic-tac-toe.
#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 :=0; i < 5; i += 1;) { game := TicTacToe->New(); result := game->Play();   if(result = Status->PLAYER_WIN) { player_score += 1; "\n=> Player Wins!"->PrintLine(); } else if(result = Status->CPU_WIN) { cpu_score += 1; "\n=> CPU Wins!"->PrintLine(); } else if(result = Status->TIE) { "\n=> Tie."->PrintLine(); } else { break; }; };   "\nHuman={$player_score}, CPU={$cpu_score}"->PrintLine(); }   New() { @board := Char->New[3, 3]; for(index := 0; index < 9; index += 1;) { j := index / 3; i := index % 3; @board[i, j] := '1' + index; };   @cpu_opening := true; }   method : Play() ~ Status { players_turn := Int->Random(1) = 1 ? true : false;   if(players_turn) { @cpu_opening := false; "\n*** NEW (Player) ***\n"->PrintLine(); Draw(); } else { "\n*** NEW (CPU) ***\n"->PrintLine(); };   playing := true; do { status : Status;   if(players_turn) { status := PlayerMove(); players_turn := false; } else { status := CpuMove(); players_turn := true; };   if(players_turn) { Draw(); };   select(status) { label Status->INVALID_MOVE: { "\n=> Invalid Move"->PrintLine(); }   label Status->PLAYER_WIN: { return Status->PLAYER_WIN; }   label Status->CPU_WIN: { return Status->CPU_WIN; }   label Status->TIE: { return Status->TIE; }   label Status->QUIT: { playing := false; } }; } while(playing);   return Status->QUIT; }   method : PlayerMove() ~ Status { move := System.IO.Console->ReadString(); if(move->Size() = 0) { return Status->INVALID_MOVE; };   option := move->Get(0); if(option = 'q') { return Status->QUIT; };   if(LegalMove(option, 'X')) { if(IsWinner(@board, 'X')) { return Status->PLAYER_WIN; } else if(IsTied()) { return Status->TIE; } else { return Status->PLAYING; }; } else { return Status->INVALID_MOVE; }; }   method : CpuMove() ~ Status { if(@cpu_opening) { select(Int->Random(2)) { label 0: { @board[0, 0] := 'O'; }   label 1: { @board[1, 1] := 'O'; }   label 2: { @board[2, 2] := 'O'; } }; @cpu_opening := false; } else { BestCpuMove(CopyBoard()); };   if(IsWinner(@board, 'O')) { return Status->CPU_WIN; } else if(IsTied()) { return Status->TIE; } else { return Status->PLAYING; }; }   method : Minimax(board : Char[,], depth : Int, is_max : Bool, alpha : Int, beta : Int) ~ Int { score := EvaluateMove(board); if(score = 10 | score = -10) { return score; };   if(IsTied()) { return 0; };   if(is_max) { best := Weights->MIN; for(i := 0; i < 3; i += 1;) { for(j := 0; j < 3; j += 1;) { if(board[i,j] <> 'X' & board[i,j] <>'O') { test := board[i,j]; board[i,j] := 'O'; best := Int->Max(best, Minimax(board, depth + 1, false, alpha, beta)); alpha := Int->Max(alpha, best); board[i,j] := test;   if(beta <= alpha) { return best; }; }; }; };   return best; } else { best := Weights->MAX; for(i := 0; i < 3; i += 1;) { for(j := 0; j < 3; j += 1;) { if(board[i,j] <> 'X' & board[i,j] <>'O') { test := board[i,j]; board[i,j] := 'X'; best := Int->Min(best, Minimax(board, depth + 1, true, alpha, beta)); beta := Int->Min(beta, best); board[i,j] := test;   if(beta <= alpha) { return best; }; }; }; };   return best; }; }   method : BestCpuMove(board : Char[,]) ~ Nil { best := Weights->MIN; # empty best_i := -1; best_j := -1;   for(i := 0; i < 3; i += 1;) { for(j := 0; j < 3; j += 1;) { if(board[i,j] <> 'X' & board[i,j] <> 'O') { test := board[i,j]; board[i,j] := 'O'; move := Int->Max(best, Minimax(board, 0, false, Weights->MIN, Weights->MAX)); board[i,j] := test;   if(move > best) { best_i := i; best_j := j; best := move; }; }; }; };   @board[best_i, best_j] := 'O'; }   method : EvaluateMove(board : Char[,]) ~ Int { if(IsWinner(board, 'O')) { return 10; } else if(IsWinner(board, 'X')) { return -10; } else { return 0; }; }   method : CopyBoard() ~ Char[,] { board := Char->New[3, 3];   for(i := 0; i < 3; i += 1;) { for(j := 0; j < 3; j += 1;) { board[i,j] := @board[i,j]; }; };   return board; }   method : LegalMove(move : Char, player: Char) ~ Bool { if(move >= '1' & move <= '9') { index := (move - '1')->As(Int); j := index / 3; i := index % 3;   if(@board[i, j] = 'X' | @board[i, j] = 'O') { return false; };   @board[i, j] := player; return true; } else { return false; }; }   method : IsWinner(board : Char[,], player : Char) ~ Bool { # --- diagonal --- check := 0; for(i := 0; i < 3; i += 1;) { if(board[i, i] = player) { check += 1; }; };   if(check = 3) { return true; };   check := 0; j := 2; for(i := 0; i < 3; i += 1;) { if(board[i, j] = player) { check += 1; }; j -= 1; };   if(check = 3) { return true; };   # --- vertical --- for(i := 0; i < 3; i += 1;) { check := 0; for(j := 0; j < 3; j += 1;) { if(board[i, j] = player) { check += 1; }; };   if(check = 3) { return true; }; };   # --- horizontal --- for(j := 0; j < 3; j += 1;) { check := 0; for(i := 0; i < 3; i += 1;) { if(board[i, j] = player) { check += 1; }; };   if(check = 3) { return true; }; };   return false; }   method : IsTied() ~ Bool { for(i := 0; i < 3; i += 1;) { for(j := 0; j < 3; j += 1;) { if(@board[i, j] <> 'X' & @board[i, j] <> 'O') { return false; }; }; };   return true; }   method : Draw() ~ Nil { a1 := @board[0, 0]; a2 := @board[1, 0]; a3 := @board[2, 0]; b1 := @board[0, 1]; b2 := @board[1, 1]; b3 := @board[2, 1]; c1 := @board[0, 2]; c2 := @board[1, 2]; c3 := @board[2, 2];   "==========="->PrintLine(); " {$a1} | {$a2} | {$a3} "->PrintLine(); "---|---|---"->PrintLine(); " {$b1} | {$b2} | {$b3} "->PrintLine(); "---|---|---"->PrintLine(); " {$c1} | {$c2} | {$c3} "->PrintLine(); "===========\n"->PrintLine(); } }
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon. The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on. A tool exists that extracts library dependencies. Task Write a function that will return a valid compile order of VHDL libraries from their dependencies. Assume library names are single words. Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given. Any self dependencies should be ignored. Any un-orderable dependencies should be flagged. Use the following data as an example: LIBRARY LIBRARY DEPENDENCIES ======= ==================== des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee dw01 ieee dw01 dware gtech dw02 ieee dw02 dware dw03 std synopsys dware dw03 dw02 dw01 ieee gtech dw04 dw04 ieee dw01 dware gtech dw05 dw05 ieee dware dw06 dw06 ieee dware dw07 ieee dware dware ieee dware gtech ieee gtech ramlib std ieee std_cell_lib ieee std_cell_lib synopsys Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01. C.f.   Topological sort/Extracted top item. There are two popular algorithms for topological sorting:   Kahn's 1962 topological sort [1]   depth-first search [2] [3]
#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] -> ..|@: $; {V: ($.V notMatching $independent), E: ($.E notMatching $independent({to: §.node}))} -> \(<?($independent::count <1..>)> $! \) -> # end topologicalSort   composer lines [<line>+] rule line: <'[^\n]*'> (<'\n'>) end lines   templates collectDeps @: { v: [], e: []}; composer depRecord (<WS>? def node: <~WS>; <WS>? <dep>* <WS>? $node -> ..|@collectDeps.v: {node: $};) rule dep: (<~WS> -> ..|@collectDeps.e: {from: $node, to: $}; <WS>?) end depRecord $(3..last)... -> !depRecord $@! end collectDeps   'LIBRARY LIBRARY DEPENDENCIES ======= ==================== des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee dw01 ieee dw01 dware gtech dw02 ieee dw02 dware dw03 std synopsys dware dw03 dw02 dw01 ieee gtech dw04 dw04 ieee dw01 dware gtech dw05 dw05 ieee dware dw06 dw06 ieee dware dw07 ieee dware dware ieee dware gtech ieee gtech ramlib std ieee std_cell_lib ieee std_cell_lib synopsys ' -> lines -> collectDeps -> topologicalSort -> !OUT::write  
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle). For the inverse functions,   use the same number and convert its answer to radians and degrees. If your language does not have trigonometric functions available or only has some available,   write functions to calculate the functions based on any   known approximation or identity.
#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 {System.showInfo {I {F Radians}}#" "#{ToDegrees {I {F Radians}}}} end
http://rosettacode.org/wiki/Tree_traversal
Tree traversal
Task Implement a binary tree where each node carries an integer,   and implement:   pre-order,   in-order,   post-order,     and   level-order   traversal. Use those traversals to output the following tree: 1 / \ / \ / \ 2 3 / \ / 4 5 6 / / \ 7 8 9 The correct output should look like this: preorder: 1 2 4 7 5 3 6 8 9 inorder: 7 4 2 5 1 8 6 9 3 postorder: 7 4 5 2 8 9 6 3 1 level-order: 1 2 3 4 5 6 7 8 9 See also   Wikipedia article:   Tree traversal.
#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, di, uo) is det.   preorder(_, empty, !Acc). preorder(P, node(Value, Left, Right), !Acc) :- P(Value, !Acc), preorder(P, Left, !Acc), preorder(P, Right, !Acc).   :- pred inorder(pred(V, A, A), tree(V), A, A). :- mode inorder(pred(in, di, uo) is det, in, di, uo) is det.   inorder(_, empty, !Acc). inorder(P, node(Value, Left, Right), !Acc) :- inorder(P, Left, !Acc), P(Value, !Acc), inorder(P, Right, !Acc).   :- pred postorder(pred(V, A, A), tree(V), A, A). :- mode postorder(pred(in, di, uo) is det, in, di, uo) is det.   postorder(_, empty, !Acc). postorder(P, node(Value, Left, Right), !Acc) :- postorder(P, Left, !Acc), postorder(P, Right, !Acc), P(Value, !Acc).   :- pred levelorder(pred(V, A, A), tree(V), A, A). :- mode levelorder(pred(in, di, uo) is det, in, di, uo) is det.   levelorder(P, Tree, !Acc) :- do_levelorder(P, [Tree], !Acc).   :- pred do_levelorder(pred(V, A, A), list(tree(V)), A, A). :- mode do_levelorder(pred(in, di, uo) is det, in, di, uo) is det.   do_levelorder(_, [], !Acc). do_levelorder(P, [empty | Xs], !Acc) :- do_levelorder(P, Xs, !Acc). do_levelorder(P, [node(Value, Left, Right) | Xs], !Acc) :- P(Value, !Acc), do_levelorder(P, Xs ++ [Left, Right], !Acc).   :- func tree = tree(int).   tree = node(1, node(2, node(4, node(7, empty, empty), empty ), node(5, empty, empty) ), node(3, node(6, node(8, empty, empty), node(9, empty, empty) ), empty ) ).   main(!IO) :- io.write_string("preorder: " ,!IO), preorder(print_value, tree, !IO), io.nl(!IO), io.write_string("inorder: " ,!IO), inorder(print_value, tree, !IO), io.nl(!IO), io.write_string("postorder: " ,!IO), postorder(print_value, tree, !IO), io.nl(!IO), io.write_string("levelorder: " ,!IO), levelorder(print_value, tree, !IO), io.nl(!IO).   :- pred print_value(V::in, io::di, io::uo) is det.   print_value(V, !IO) :- io.print(V, !IO), io.write_string(" ", !IO).
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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 } }   extension TimeResult: CustomStringConvertible { public var description: String { return "TimeResult(seconds: \(seconds); nanoSeconds: \(nanoSeconds); duration: \(duration)s)" } }   public struct ClockTimer { @inlinable @inline(__always) public static func time<T>(_ f: () throws -> T) rethrows -> (T, TimeResult) { var tsi = timespec() var tsf = timespec()   clock_gettime(CLOCK_MONOTONIC_RAW, &tsi) let res = try f() clock_gettime(CLOCK_MONOTONIC_RAW, &tsf)   let secondsElapsed = difftime(tsf.tv_sec, tsi.tv_sec) let nanoSecondsElapsed = Double(tsf.tv_nsec - tsi.tv_nsec)   return (res, TimeResult(seconds: secondsElapsed, nanoSeconds: nanoSecondsElapsed)) } }   func ackermann(m: Int, n: Int) -> Int { switch (m, n) { case (0, _): return n + 1 case (_, 0): return ackermann(m: m - 1, n: 1) case (_, _): return ackermann(m: m - 1, n: ackermann(m: m, n: n - 1)) } }   let (n, t) = ClockTimer.time { ackermann(m: 3, n: 11) }   print("Took \(t.duration)s to calculate ackermann(m: 3, n: 11) = \(n)")   let (n2, t2) = ClockTimer.time { ackermann(m: 4, n: 1) }   print("Took \(t2.duration)s to calculate ackermann(m: 4, n: 1) = \(n2)")
http://rosettacode.org/wiki/Top_rank_per_group
Top rank per group
Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190
#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 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190 EOF   my $N = shift || 3;   foreach my $d (uniq sort map {$_->{dept}} @data) { print "$d\n"; my @es = sort {$b->{salary} <=> $a->{salary}} grep {$_->{dept} eq $d} @data; foreach (1 .. $N) { @es or last; my $e = shift @es; printf "%-15s | %-6s | %5d\n", @{$e}{qw(name id salary)}; } print "\n"; }
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedia tic-tac-toe.
#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 [Contents] of char; begin t[Unassigned] := ' '; t[Human] := 'O'; t[Computer] := 'X'; for i := 0 to 2 do begin for j := 0 to 2 do begin write(t[b[i][j]]); if j <> 2 then write(' | '); end; writeln(); if i < 2 then writeln('---------'); end; writeln(); writeln(); end;   function swapPlayer (Player: Contents): Contents; begin if Player = Computer then swapPlayer := Human else swapPlayer := Computer; end;   function checkWinner: Contents; var i: Integer; begin checkWinner := Unassigned; (* no winner yet *) for i := 0 to 2 do begin (* first horizontal solution *) if ((checkWinner = Unassigned) and (b[i][0] <> Unassigned)) and ((b[i][1] = b[i][0]) and (b[i][2] = b[i][0])) then checkWinner := b[i][0] else (* now vertical solution *) if ((checkWinner = Unassigned) and (b[0][i] <> Unassigned)) and ((b[1][i] = b[0][i]) and (b[2][i] = b[0][i])) then checkWinner := b[0][i]; end; (* now check the paths of the two cross line slants that share the middle position *) if (checkWinner = Unassigned) and (b[1][1] <> Unassigned) then begin if ((b[1][1] = b[0][0]) and (b[2][2] = b[0][0])) then checkWinner := b[0][0] else if ((b[1][1] = b[2][0]) and (b[0][2] = b[1][1])) then checkWinner := b[1][1]; end; end;   { Basic strategy test - is this te best solution we have seen } function saveBest(CurScore, CurBest: Contents) : boolean; begin if CurScore = CurBest then saveBest := false else if (Curscore = Unassigned) and (CurBest = Human) then saveBest := false else if (Curscore = Computer) and ((CurBest = Unassigned) or (CurBest = Human)) then saveBest := false else saveBest := true; end;     { Basic strategy - recursive depth first serach of possible moves if computer can win save it, otherwise block if need be, else do deeper. At each level modify the board for the next call, but clean up as go back up, by remembering the modified position on the call stack. } function test_move (val: Contents; depth: Integer): Contents; var i, j: Integer; score, best, changed: Contents; begin best := Computer; changed := Unassigned; score := checkWinner(); if score <> Unassigned then begin if score = val then test_move := Human else test_move := Computer; end else begin for i := 0 to 2 do for j := 0 to 2 do begin if b[i][j] = Unassigned then begin changed := val; b[i][j] := val; (* the value for now and try wioth the other player *) score := test_move(swapPlayer(val), depth + 1); if (score <> Unassigned) then score := swapPlayer(score); b[i][j] := Unassigned; if saveBest(score, best) then begin if depth = 0 then begin { top level, so remember actual position } best_i := i; best_j := j; end; best := score; end; end; end; if (changed <> Unassigned) then test_move := best else test_move := Unassigned; end; end;   function playGame(whom:Contents): string; var i, j, k, move: Integer; win: Contents; begin win := Unassigned; for i := 0 to 2 do for j := 0 to 2 do b[i][j] := Unassigned;   writeln('The board positions are numbered as follows:'); writeln('1 | 2 | 3'); writeln('---------'); writeln('4 | 5 | 6'); writeln('---------'); writeln('7 | 8 | 9'); writeln('You have O, I have X.'); writeln();   k := 1; repeat {rather a for loop but can not have two actions or early termination in Pascal} begin if whom = Human then begin repeat begin write('Your move: '); readln(move); if (move < 1) or (move > 9) then writeln('Opps: enter a number between 1 - 9') else move := pred(move); {humans do 1 -9, but the computer wants 0-8 for modulus to work} end until ((move >= 0) and (move <= 8)); i := move div 3; { convert from range to corridinated of the array } j := move mod 3; if b[i][j] = Unassigned then b[i][j] := Human; end; if whom = Computer then begin (* randomize if computer opens, so its not always the same game *) if k = 1 then begin best_i := random(3); {Pascal random returns positive integers from 0 to func arg} best_j := random(3); end else win := test_move(Computer, 0); b[best_i][best_j] := Computer; writeln('My move: ', best_i * 3 + best_j + 1); end;   displayBoard(); win := checkWinner(); if win <> Unassigned then begin if win = Human then playGame := 'You win.' else playGame := 'I win.'; end else begin k := succ(k); { "for" loop counter actions } whom := swapPlayer(whom); end; end; until (win <> Unassigned) or (k > 9); if win = Unassigned then playGame := 'A draw.'; end;   begin randomize(); player := Human; while (true) do begin writeln(playGame(player)); writeln(); player := swapPlayer(player); end end.
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",T(D),!
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon. The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on. A tool exists that extracts library dependencies. Task Write a function that will return a valid compile order of VHDL libraries from their dependencies. Assume library names are single words. Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given. Any self dependencies should be ignored. Any un-orderable dependencies should be flagged. Use the following data as an example: LIBRARY LIBRARY DEPENDENCIES ======= ==================== des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee dw01 ieee dw01 dware gtech dw02 ieee dw02 dware dw03 std synopsys dware dw03 dw02 dw01 ieee gtech dw04 dw04 ieee dw01 dware gtech dw05 dw05 ieee dware dw06 dw06 ieee dware dw07 ieee dware dware ieee dware gtech ieee gtech ramlib std ieee std_cell_lib ieee std_cell_lib synopsys Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01. C.f.   Topological sort/Extracted top item. There are two popular algorithms for topological sorting:   Kahn's 1962 topological sort [1]   depth-first search [2] [3]
#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 sorted {} while 1 { # Find available nodes set avail [dict keys [dict filter $data value {}]] if {![llength $avail]} { if {[dict size $data]} { error "graph is cyclic, possibly involving nodes \"[dict keys $data]\"" } return $sorted } # Note that the lsort is only necessary for making the results more like other langs lappend sorted {*}[lsort $avail] # Remove from working copy of graph dict for {node depends} $data { foreach n $avail { if {[set i [lsearch -exact $depends $n]] >= 0} { set depends [lreplace $depends $i $i] dict set data $node $depends } } } foreach node $avail { dict unset data $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 is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle). For the inverse functions,   use the same number and convert its answer to radians and degrees. If your language does not have trigonometric functions available or only has some available,   write functions to calculate the functions based on any   known approximation or identity.
#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 / / \ 7 8 9 The correct output should look like this: preorder: 1 2 4 7 5 3 6 8 9 inorder: 7 4 2 5 1 8 6 9 3 postorder: 7 4 5 2 8 9 6 3 1 level-order: 1 2 3 4 5 6 7 8 9 See also   Wikipedia article:   Tree traversal.
#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 inorder[T](n: Node[T]): seq[T] = if n.isNil: @[] else: inorder(n.left) & @[n.data] & inorder(n.right)   proc postorder[T](n: Node[T]): seq[T] = if n.isNil: @[] else: postorder(n.left) & postorder(n.right) & @[n.data]   proc levelorder[T](n: Node[T]): seq[T] = var queue: Deque[Node[T]] queue.addLast(n) while queue.len > 0: let next = queue.popFirst() result.add next.data if not next.left.isNil: queue.addLast(next.left) if not next.right.isNil: queue.addLast(next.right)   let tree = 1.newNode( 2.newNode( 4.newNode( 7.newNode), 5.newNode), 3.newNode( 6.newNode( 8.newNode, 9.newNode)))   echo preorder tree echo inorder tree echo postorder tree echo levelorder tree
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 t,c,sep % if char != sep then PBNZ t,3F % store char SET t,NL % terminate token with NL,EOS STBU t,tp SET t,EOS INCL tp,1 STBU t,tp JMP 4F % continue   3H STBU c,tp % store char 4H INCL tp,1 % update pointers INCL p,1 JMP 2B % LOOP   5H SET t,NL % terminate last token and buffer STBU t,tp SET t,EOS INCL tp,1 STBU t,tp % next part is not really necessary % program runs only once % INCL tp,1 % terminate buffer % STBU t,tp   LDA tp,token % reset token pointer % REPEAT 2H ADD p,tp,0 % start of token TRAP 0,Fputs,StdOut % output token ADD tp,tp,p INCL tp,1 % step to next token LDBU t,tp PBNZ t,2B % UNTIL EOB(uffer) TRAP 0,Halt,0
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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,%i,%j,%k,%l,%m,%n,%o); }   %end = getRealTime();   %result = (%end-%start) / %times;   warn("BENCHMARKING RESULT FOR" SPC %function @ ":" NL %result);   return %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,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190
#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"}, {"George Woltman", "E00127",53500,"D101"}, {"Adam Smith", "E63535",18000,"D202"}, {"Claire Buckman", "E39876",27800,"D202"}, {"David McClellan","E04242",41500,"D101"}, {"Rich Holcomb", "E01234",49500,"D202"}, {"Nathan Adams", "E41298",21900,"D050"}, {"Richard Potter", "E43128",15900,"D101"}, {"David Motsinger","E27002",19250,"D202"}, {"Tim Sampair", "E03033",27000,"D101"}, {"Kim Arlich", "E10001",57000,"D190"}, {"Timothy Grove", "E16398",29900,"D190"}} function by_dept_sal(integer i, j) return compare(employees[i][DEPT]&-employees[i][SAL], employees[j][DEPT]&-employees[j][SAL]) end function sequence tags = custom_sort(by_dept_sal,tagset(length(employees))) string lastdep = "" integer dcount = 0 printf(1,"Top %d salaries by department\n",{N}) for i=1 to length(employees) do object emp = employees[tags[i]] if emp[DEPT]!=lastdep then lastdep = emp[DEPT] dcount = 1 printf(1,"\n") else dcount += 1 end if if dcount<=N then ?emp end if end for
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedia tic-tac-toe.
#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( my $s = score( $b, $me ) ) { return $cache{$b,$me,wantarray} = (wantarray ? undef : $s); } my $him = $reverse{$me}; my ($best, @best) = (-999); for my $m (moves($b)) { (my $with_m = $b) =~ s/$m/$me/ or die; # The || operator supplies scalar context to best_move(...) my $s = -(score($with_m, $him) || best_move($with_m, $him)); if( $s > $best ) { ($best, @best) = ($s, $m); } elsif( $s == $best ) { push @best, $m; } } $cache{$b,$me,wantarray} = wantarray ? $best[rand @best] : $best; }   my $winner = q[([XOxo])(?:\1\1|...\1...\1|..\1..\1|....\1....\1)]; sub score { my ($b, $me) = @_; $b =~ m/$winner/o or return 0; return $1 eq $me ? +1 : -1; }   sub moves { my ($b) = @_; $b =~ /([^xoXO,\n])/g; }   sub print_board { my ($b) = @_; $b =~ s/\B/|/g; $b =~ s/,/\n-+-+-\n/g; print $b, "\n"; }   sub prompt { my ($b, $color) = @_; my @moves = moves($b); unless( @moves ) { return; } while( 1 ) { print "Place your $color on one of [@moves]: "; defined(my $m = <>) or return; chomp($m); return $m if grep $m eq $_, @moves; } }   my @players = ( { whose => "your", name => "You", verb => "You place", get_move => \&prompt }, { whose => "the computer's", name => "Computer", verb => "The computer places", get_move => \&best_move }, ); my $whose_turn = int rand 2;   my $color = "X"; my $b = $initial;   while( 1 ) { my $p = $players[$whose_turn]; print_board($b); print "It is $p->{whose} turn.\n"; # The parens around $m supply list context to the right side # or the = operator, which causes sub best_move to return the # best move, rather than the score of the best move. my ( $m ) = $p->{get_move}->($b, $color); if( $m ) { print "$p->{verb} an $color at $m\n"; $b =~ s/$m/$color/; my $s = score($b, $color) or next; print_board($b); print "$p->{name} ", $s > 0 ? "won!\n" : "lost!\n"; } else { print "$p->{name} cannot move.\n"; } print "Game over.\nNew Game...\n"; ($b, $color, $whose_turn) = ($initial, "X", int rand 2); redo; } continue { $color = $reverse{$color}; $whose_turn = !$whose_turn; }  
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) CALL Move(1, from, to, via) CALL Move(ndisks-1, via, to, from) END IF END SUBROUTINE Move   END PROGRAM TOWER
http://rosettacode.org/wiki/Topological_sort
Topological sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon. The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on. A tool exists that extracts library dependencies. Task Write a function that will return a valid compile order of VHDL libraries from their dependencies. Assume library names are single words. Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given. Any self dependencies should be ignored. Any un-orderable dependencies should be flagged. Use the following data as an example: LIBRARY LIBRARY DEPENDENCIES ======= ==================== des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee dw01 ieee dw01 dware gtech dw02 ieee dw02 dware dw03 std synopsys dware dw03 dw02 dw01 ieee gtech dw04 dw04 ieee dw01 dware gtech dw05 dw05 ieee dware dw06 dw06 ieee dware dw07 ieee dware dware ieee dware gtech ieee gtech ramlib std ieee std_cell_lib ieee std_cell_lib synopsys Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01. C.f.   Topological sort/Extracted top item. There are two popular algorithms for topological sorting:   Kahn's 1962 topological sort [1]   depth-first search [2] [3]
#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 dware gtech > dw05 dw05 ieee dware > dw06 dw06 ieee dware > dw07 ieee dware > dware ieee dware > gtech ieee gtech > ramlib std ieee > std_cell_lib ieee std_cell_lib > synopsys > ! ieee dware dw02 dw05 dw06 dw07 gtech dw01 dw04 std_cell_lib synopsys std dw03 ramlib des_system_lib
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle). For the inverse functions,   use the same number and convert its answer to radians and degrees. If your language does not have trigonometric functions available or only has some available,   write functions to calculate the functions based on any   known approximation or identity.
#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)); writeln (tan(radians),' ', tan(degree/180*pi)); writeln (); writeln (arcsin(sin(radians)),' Rad., or ', arcsin(sin(degree/180*pi))/pi*180,' Deg.'); writeln (arccos(cos(radians)),' Rad., or ', arccos(cos(degree/180*pi))/pi*180,' Deg.'); writeln (arctan(tan(radians)),' Rad., or ', arctan(tan(degree/180*pi))/pi*180,' Deg.'); // ( radians ) / pi * 180 = deg. end.
http://rosettacode.org/wiki/Tree_traversal
Tree traversal
Task Implement a binary tree where each node carries an integer,   and implement:   pre-order,   in-order,   post-order,     and   level-order   traversal. Use those traversals to output the following tree: 1 / \ / \ / \ 2 3 / \ / 4 5 6 / / \ 7 8 9 The correct output should look like this: preorder: 1 2 4 7 5 3 6 8 9 inorder: 7 4 2 5 1 8 6 9 3 postorder: 7 4 5 2 8 9 6 3 1 level-order: 1 2 3 4 5 6 7 8 9 See also   Wikipedia article:   Tree traversal.
#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);   one->SetLeft(two); one->SetRight(three); two->SetLeft(four); two->SetRight(five); three->SetLeft(six); four->SetLeft(seven); six->SetLeft(eight); six->SetRight(nine);   "Preorder: "->Print(); Preorder(one); "\nInorder: "->Print(); Inorder(one); "\nPostorder: "->Print(); Postorder(one); "\nLevelorder: "->Print(); Levelorder(one); "\n"->Print(); }   function : Preorder(node : Node) ~ Nil { if(node <> Nil) { System.IO.Console->Print(node->GetData())->Print(", "); Preorder(node->GetLeft()); Preorder(node->GetRight()); }; }   function : Inorder(node : Node) ~ Nil { if(node <> Nil) { Inorder(node->GetLeft()); System.IO.Console->Print(node->GetData())->Print(", "); Inorder(node->GetRight()); }; }   function : Postorder(node : Node) ~ Nil { if(node <> Nil) { Postorder(node->GetLeft()); Postorder(node->GetRight()); System.IO.Console->Print(node->GetData())->Print(", "); }; }   function : Levelorder(node : Node) ~ Nil { nodequeue := Collection.Queue->New(); if(node <> Nil) { nodequeue->Add(node); };   while(nodequeue->IsEmpty() = false) { next := nodequeue->Remove()->As(Node); System.IO.Console->Print(next->GetData())->Print(", "); if(next->GetLeft() <> Nil) { nodequeue->Add(next->GetLeft()); };   if(next->GetRight() <> Nil) { nodequeue->Add(next->GetRight()); }; }; } }   class Node from BasicCompare { @left : Node; @right : Node; @data : Int;   New(data : Int) { Parent(); @data := data; }   method : public : GetData() ~ Int { return @data; }   method : public : SetLeft(left : Node) ~ Nil { @left := left; }   method : public : GetLeft() ~ Node { return @left; }   method : public : SetRight(right : Node) ~ Nil { @right := right; }   method : public : GetRight() ~ Node { return @right; }   method : public : Compare(rhs : Compare) ~ Int { right : Node := rhs->As(Node); if(@data = right->GetData()) { return 0; } else if(@data < right->GetData()) { return -1; };   return 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: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 LAST(tokens^) DO IO.Put(tokens[i] & "."); END; IO.Put("\n"); END Tokenize.
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190
#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("David McClellan","E04242",41500,"D101"), Array("Rich Holcomb","E01234",49500,"D202"), Array("Nathan Adams","E41298",21900,"D050"), Array("Richard Potter","E43128",15900,"D101"), Array("David Motsinger","E27002",19250,"D202"), Array("Tim Sampair","E03033",27000,"D101"), Array("Kim Arlich","E10001",57000,"D190"), Array("Timothy Grove","E16398",29900,"D190") ); function top_sal($num){ global $data; $depts = Array(); foreach($data as $key => $arr){ if(!isset($depts[$arr[3]])) $depts[$arr[3]] = Array(); $depts[$arr[3]][] = $key; } function topsalsort($a,$b){ global $data; if ($data[$a][2] == $data[$b][2]) { return 0; } return ($data[$a][2] < $data[$b][2]) ? 1 : -1; } foreach ($depts as $key => $val){ usort($depts[$key],"topsalsort"); } ksort($depts); echo '<pre>'; foreach ($depts as $key => $val){ echo $key . '<br>'; echo 'Name ID Salary<br>'; $count = 0; foreach($val as $value){ echo $data[$value][0] . ' ' . $data[$value][1] . ' ' . $data[$value][2] . '<br>'; $count++; if($count>=$num) break; } echo '<br>'; } echo '</pre>'; } top_sal(3);
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedia tic-tac-toe.
#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 cw,ch, -- board centre d, -- tile spacing h -- tile size/radius function redraw_cb(Ihandle ih, integer /*posx*/, /*posy*/) {cw,ch} = IupGetIntInt(ih, "DRAWSIZE") d = floor(min(cw,ch)/8) h = floor(d*2/3) cw = floor(cw/2) ch = floor(ch/2) IupGLMakeCurrent(ih) cdCanvas cddbuffer = IupGetAttributePtr(ih,"DBUFFER") cdCanvasActivate(cddbuffer) cdCanvasClear(cddbuffer) cdCanvasSetForeground(cddbuffer,CD_BLUE) cdCanvasSetLineWidth(cddbuffer,10) integer d3 = 3*d cdCanvasLine(cddbuffer,cw-d,ch-d3,cw-d,ch+d3) cdCanvasLine(cddbuffer,cw+d,ch-d3,cw+d,ch+d3) cdCanvasLine(cddbuffer,cw-d3,ch-d,cw+d3,ch-d) cdCanvasLine(cddbuffer,cw-d3,ch+d,cw+d3,ch+d) integer pdx = 1 for y=+1 to -1 by -1 do integer my = ch+y*2*d for x=-1 to +1 do integer mx = cw+x*2*d integer mark = board[pdx] if mark='X' then cdCanvasLine(cddbuffer,mx-h,my-h,mx+h,my+h) cdCanvasLine(cddbuffer,mx-h,my+h,mx+h,my-h) elsif mark='O' then cdCanvasCircle(cddbuffer,mx,my,2*h) end if pdx += 1 end for end for cdCanvasFlush(cddbuffer) return IUP_DEFAULT end function function map_cb(Ihandle canvas) IupGLMakeCurrent(canvas) cdCanvas cddbuffer if platform()=JS then cddbuffer = cdCreateCanvas(CD_IUP, canvas) else atom res = IupGetDouble(NULL, "SCREENDPI")/25.4 cddbuffer = cdCreateCanvas(CD_GL, "10x10 %g", {res}) end if IupSetAttributePtr(canvas,"DBUFFER",cddbuffer) cdCanvasSetBackground(cddbuffer, CD_PARCHMENT) return IUP_DEFAULT end function function canvas_resize_cb(Ihandle canvas) cdCanvas cddbuffer = IupGetAttributePtr(canvas,"DBUFFER") integer {canvas_width, canvas_height} = IupGetIntInt(canvas, "DRAWSIZE") atom res = IupGetDouble(NULL, "SCREENDPI")/25.4 cdCanvasSetAttribute(cddbuffer, "SIZE", "%dx%d %g", {canvas_width, canvas_height, res}) return IUP_DEFAULT end function constant wins = {{1,2,3},{4,5,6},{7,8,9},{1,4,7},{2,5,8},{3,6,9},{1,5,9},{3,5,7}} function check_winner() for w=1 to length(wins) do integer {i,j,k} = wins[w], mark = board[i] if mark!=' ' and mark=board[j] and mark=board[k] then return mark end if end for return 0 end function integer best_i function test_move(integer mark, depth) integer score = check_winner(), best = -1, changed = 0 if score!=0 then return iff(score=mark?1:-1) end if for i=1 to 9 do if board[i]=' ' then changed = mark board[i] = mark score = -test_move('O'+'X'-mark, depth + 1) board[i] = ' ' if score>best then if depth=0 then best_i = i; end if best = score; end if end if end for return iff(changed!=0?best:0) end function procedure check_game_over() integer win = check_winner() if win or not find(' ',board) then string winner = iff(win='O'?"You win!", iff(win='X'?"Computer wins" :"Draw")) IupSetStrAttribute(dlg,"TITLE","%s - %s",{title,winner}) game_over = true end if end procedure procedure play_move(integer move) if move then assert(board[move]=' ') board[move] = 'O' check_game_over() if not game_over then human = false if play_dumb then sequence s = find_all(' ',board) best_i = s[rand(length(s))] else {} = test_move('X', 0) assert(board[best_i]=' ') end if board[best_i] = 'X' check_game_over() human = not game_over end if end if end procedure procedure new_game() board = repeat(' ',9) human = not human if not human then board[rand(9)] = 'X' human = true end if end procedure function check_position(integer px, py) -- -- check if x,y is on a legal move. -- uses ch,cw,d,h as saved by redraw_cb(). -- integer pdx = 1 for y=-1 to +1 do integer my = ch+y*2*d for x=-1 to +1 do integer mx = cw+x*2*d if px>=mx-h and px<=mx+h and py>=my-h and py<=my+h then integer mark = board[pdx] return iff(mark==' '?pdx:0) end if pdx += 1 end for end for return 0 end function function button_cb(Ihandle /*canvas*/, integer button, pressed, x, y, atom /*pStatus*/) if button=IUP_BUTTON1 and not pressed then -- (left button released) if game_over then game_over = false new_game() else play_move(check_position(x,y)) end if IupRedraw(dlg) end if return IUP_CONTINUE end function function exit_cb(Ihandle /*ih*/) return IUP_CLOSE end function constant help_text = """ Tic Tac Toe, also known as Noughts and Crosses. The aim is to get three Os (or Xs) in a row. Human(O) plays first, as does loser. After a draw first player alternates. Computer(X) plays a random move first, to make it more interesting. Setting the constant play_dumb to true disables the internal AI. Once a game is over click anywhere on the board to start a new game. """ function help_cb(Ihandln /*ih*/) IupMessage(title,help_text) return IUP_DEFAULT end function -- Other possible keys: -- Q - quit (end program) [==X?] -- C - concede (start new game) function key_cb(Ihandle /*dlg*/, atom c) if c=K_ESC then return IUP_CLOSE end if if c=K_F1 then return help_cb(NULL) end if return IUP_CONTINUE end function procedure main() IupOpen() Ihandle canvas = IupGLCanvas("RASTERSIZE=800x800") dlg = IupDialog(canvas,`TITLE="%s",MINSIZE=245x180`,{title}) IupSetCallbacks(canvas,{"MAP_CB",Icallback("map_cb"), "ACTION",Icallback("redraw_cb"), "RESIZE_CB", Icallback("canvas_resize_cb"), "BUTTON_CB", Icallback("button_cb")}) IupSetCallback(dlg, "KEY_CB", Icallback("key_cb")) IupSetAttributeHandle(NULL,"PARENTDIALOG",dlg) new_game() IupShow(dlg) IupSetAttribute(canvas,"RASTERSIZE",NULL) if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
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 disks" : Print move 4, 1, 2, 3 Print "Press any key to quit" Sleep
http://rosettacode.org/wiki/Topological_sort
Topological sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon. The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on. A tool exists that extracts library dependencies. Task Write a function that will return a valid compile order of VHDL libraries from their dependencies. Assume library names are single words. Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given. Any self dependencies should be ignored. Any un-orderable dependencies should be flagged. Use the following data as an example: LIBRARY LIBRARY DEPENDENCIES ======= ==================== des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee dw01 ieee dw01 dware gtech dw02 ieee dw02 dware dw03 std synopsys dware dw03 dw02 dw01 ieee gtech dw04 dw04 ieee dw01 dware gtech dw05 dw05 ieee dware dw06 dw06 ieee dware dw07 ieee dware dware ieee dware gtech ieee gtech ramlib std ieee std_cell_lib ieee std_cell_lib synopsys Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01. C.f.   Topological sort/Extracted top item. There are two popular algorithms for topological sorting:   Kahn's 1962 topological sort [1]   depth-first search [2] [3]
#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 is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle). For the inverse functions,   use the same number and convert its answer to radians and degrees. If your language does not have trigonometric functions available or only has some available,   write functions to calculate the functions based on any   known approximation or identity.
#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($angle_degrees)), "\n"; my $asin = asin(sin($angle_radians)); print $asin, ' ', rad2deg($asin), "\n"; my $acos = acos(cos($angle_radians)); print $acos, ' ', rad2deg($acos), "\n"; my $atan = atan(tan($angle_radians)); print $atan, ' ', rad2deg($atan), "\n"; my $acot = acot(cot($angle_radians)); print $acot, ' ', rad2deg($acot), "\n";
http://rosettacode.org/wiki/Tree_traversal
Tree traversal
Task Implement a binary tree where each node carries an integer,   and implement:   pre-order,   in-order,   post-order,     and   level-order   traversal. Use those traversals to output the following tree: 1 / \ / \ / \ 2 3 / \ / 4 5 6 / / \ 7 8 9 The correct output should look like this: preorder: 1 2 4 7 5 3 6 8 9 inorder: 7 4 2 5 1 8 6 9 3 postorder: 7 4 5 2 8 9 6 3 1 level-order: 1 2 3 4 5 6 7 8 9 See also   Wikipedia article:   Tree traversal.
#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; f v; inorder f r   let rec postorder f = function Empty -> () | Node (v,l,r) -> postorder f l; postorder f r; f v   let levelorder f x = let queue = Queue.create () in Queue.add x queue; while not (Queue.is_empty queue) do match Queue.take queue with Empty -> () | Node (v,l,r) -> f v; Queue.add l queue; Queue.add r queue done   let tree = Node (1, Node (2, Node (4, Node (7, Empty, Empty), Empty), Node (5, Empty, Empty)), Node (3, Node (6, Node (8, Empty, Empty), Node (9, Empty, Empty)), Empty))   let () = preorder (Printf.printf "%d ") tree; print_newline (); inorder (Printf.printf "%d ") tree; print_newline (); postorder (Printf.printf "%d ") tree; print_newline (); levelorder (Printf.printf "%d ") tree; print_newline ()
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 list comprehension takes care of that } }
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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 Next i Next j sum = t End Function Private Sub time_it() Dim start_time As Long, finis_time As Long start_time = GetTickCount identity 1 finis_time = GetTickCount Debug.Print "1000 times Identity(1) takes "; (finis_time - start_time); " milliseconds" start_time = GetTickCount sum 1 finis_time = GetTickCount Debug.Print "1000 times Sum(1) takes "; (finis_time - start_time); " milliseconds" End Sub
http://rosettacode.org/wiki/Top_rank_per_group
Top rank per group
Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190
#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","27800","D202"], ["David McClellan","E04242","41500","D101"], ["Rich Holcomb","E01234","49500","D202"], ["Nathan Adams","E41298","21900","D050"], ["Richard Potter","E43128","15900","D101"], ["David Motsinger","E27002","19250","D202"], ["Tim Sampair","E03033","27000","D101"], ["Kim Arlich","E10001","57000","D190"], ["Timothy Grove","E16398","29900","D190"] ], print_top_ranks(Emp,3), nl.   print_top_ranks(Emp,N) => printf("Top %d ranks per department:\n", N), foreach(Dept in [Dept : [_,_,_,Dept] in Emp].sort_remove_dups()) printf("Department %s\n", Dept), Emp2 = sort_down([[Salary,Name] : [Name,_,Salary,D] in Emp, D = Dept]), foreach({[Salary,Name],E} in zip(Emp2,1..Emp2.length), E <= N) printf("%-20s %-10s\n", Name, Salary) end, nl end.
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedia tic-tac-toe.
#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 '[^\.]{9}/i'; //Cat's game if ($pin == 'O') $pat = str_replace('X', 'O', $pat); return preg_match($pat, $board); }   //Start $boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR; $turn = substr_count($boardStr, '.')%2==0? 'O' : 'X'; $oppTurn = $turn == 'X'? 'O' : 'X'; $gameOver = isGameOver($boardStr, $oppTurn);   //Display board echo '<style>'; echo 'td {width: 200px; height: 200px; text-align: center; }'; echo '.pin {font-size:72pt; text-decoration:none; color: black}'; echo '.pin.X {color:red}'; echo '.pin.O {color:blue}'; echo '</style>'; echo '<table border="1">'; $p = 0; for ($r = 0; $r < ROW_NUM; $r++) { echo '<tr>'; for ($c = 0; $c < ROW_NUM; $c++) { $pin = $boardStr[$p];   echo '<td>'; if ($gameOver || $pin != '.') echo '<span class="pin ', $pin, '">', $pin, '</span>'; //Occupied else { //Available $boardDelta = $boardStr; $boardDelta[$p] = $turn; echo '<a class="pin ', $pin, '" href="?b=', $boardDelta, '">'; echo $boardStr[$p]; echo '</a>'; }   echo '</td>'; $p++; } echo '</tr>'; echo '<input type="hidden" name="b" value="', $boardStr, '"/>'; } echo '</table>'; echo '<a href="?b=', $EMPTY_BOARD_STR, '">Reset</a>'; if ($gameOver) echo '<h1>Game Over!</h1>';  
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"] hanoi[n-1, aux, target, source] } }   hanoi[7]  
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 ) print print "Towers of Hanoi puzzle solved."   HandleEvents
http://rosettacode.org/wiki/Topological_sort
Topological sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon. The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on. A tool exists that extracts library dependencies. Task Write a function that will return a valid compile order of VHDL libraries from their dependencies. Assume library names are single words. Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given. Any self dependencies should be ignored. Any un-orderable dependencies should be flagged. Use the following data as an example: LIBRARY LIBRARY DEPENDENCIES ======= ==================== des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee dw01 ieee dw01 dware gtech dw02 ieee dw02 dware dw03 std synopsys dware dw03 dw02 dw01 ieee gtech dw04 dw04 ieee dw01 dware gtech dw05 dw05 ieee dware dw06 dw06 ieee dware dw07 ieee dware dware ieee dware gtech ieee gtech ramlib std ieee std_cell_lib ieee std_cell_lib synopsys Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01. C.f.   Topological sort/Extracted top item. There are two popular algorithms for topological sorting:   Kahn's 1962 topological sort [1]   depth-first search [2] [3]
#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 ) 'assuming token tab token-list newline dim i, j ,k dim aList dim dep dim a1 aList = Split( s, vbNewLine ) '~ remove empty lines at end do while aList( UBound( aList ) ) = vbnullstring redim preserve aList( UBound( aList ) - 1 ) loop   for i = lbound( aList ) to ubound( aList ) aList( i ) = Split( aList( i ), vbTab, 2 ) a1 = Split( aList( i )( 1 ), " " ) k = 0 for j = lbound( a1) to ubound(a1) if a1(j) <> aList(i)(0) then a1(k) = a1(j) k = k + 1 end if next redim preserve a1(k-1) aList(i)(1) = a1 next for i = lbound( aList ) to ubound( aList ) dep = aList(i)(0) if not dictDependencies.Exists( dep ) then dictDependencies.add dep, aList(i)(1) end if next   end property   sub resolve( s ) dim i dim deps '~ wscript.echo string(depth,"!"),s depth = depth + 1 if dictDependencies.Exists(s) then deps = dictDependencies(s) for i = lbound(deps) to ubound(deps) resolve deps(i) next end if if not seen(s) then wscript.echo s see s end if depth = depth - 1 end sub   function seen( key ) seen = dictReported.Exists( key ) end function   sub see( key ) dictReported.add key, "" end sub   property get keys keys = dictDependencies.keys end property end class  
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle). For the inverse functions,   use the same number and convert its answer to radians and degrees. If your language does not have trigonometric functions available or only has some available,   write functions to calculate the functions based on any   known approximation or identity.
#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 / / \ 7 8 9 The correct output should look like this: preorder: 1 2 4 7 5 3 6 8 9 inorder: 7 4 2 5 1 8 6 9 3 postorder: 7 4 5 2 8 9 6 3 1 level-order: 1 2 3 4 5 6 7 8 9 See also   Wikipedia article:   Tree traversal.
#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: [ @l inOrder(f) ] @v f perform @r ifNotNull: [ @r inOrder(f) ] ;   Tree method: postOrder(f) @l ifNotNull: [ @l postOrder(f) ] @r ifNotNull: [ @r postOrder(f) ] @v f perform ;   Tree method: levelOrder(f) | c n | Channel new self over send drop ->c while(c notEmpty) [ c receive ->n n v f perform n l dup ifNotNull: [ c send ] drop n r dup ifNotNull: [ c send ] drop ] ;
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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(' ',',') Loop i=1 To ss.words() Say ss.word(i)'.' End Say 'End-of-list.'
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190
#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 D202) ("Nathan Adams" E41298 21900 D050) ("Richard Potter" E43128 15900 D101) ("David Motsinger" E27002 19250 D202) ("Tim Sampair" E03033 27000 D101) ("Kim Arlich" E10001 57000 D190) ("Timothy Grove" E16398 29900 D190) )   (de topEmployees (N) (let Fmt (4 -16 -7 7) (for Dept (by cadddr group *Employees) (prinl "Department " (cadddr (car Dept)) ":") (tab Fmt NIL "Name" "ID" "Salary") (for (I . D) (flip (by caddr sort Dept)) (tab Fmt (pack I ". ") (car D) (cadr D) (caddr D)) (T (= I N)) ) (prinl) ) ) )   (topEmployees 3)
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedia tic-tac-toe.
#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 Y DX DY) (do 3 (NIL (= P (get *Board X Y))) (inc 'X DX) (inc 'Y DY) T ) ) (1 1 1 1 2 3 1 1) (1 2 3 1 1 1 1 3) (1 1 1 0 0 0 1 1) (0 0 0 1 1 1 1 -1) ) )   (de myMove () (when (game NIL 8 '((Flg) # Moves (unless (find3 (or (not Flg) 0)) (make (for (X . L) *Board (for (Y . P) L (unless P (link (cons (cons X Y (or Flg 0)) (list X Y) ) ) ) ) ) ) ) ) '((Mov) # Move (set (nth *Board (car Mov) (cadr Mov)) (cddr Mov)) ) '((Flg) # Cost (if (find3 (or Flg 0)) -100 0) ) ) (let Mov (caadr @) (set (nth *Board (car Mov) (cadr Mov)) 0) ) (display) ) )   (de yourMove (X Y) (and (sym? X) (>= 3 (setq X (- (char X) 96)) 1) (num? Y) (>= 3 Y 1) (not (get *Board X Y)) (set (nth *Board X Y) T) (display) ) )   (de main () (setq *Board (make (do 3 (link (need 3))))) (display) )   (de go Args (cond ((not (yourMove (car Args) (cadr Args))) "Illegal move!" ) ((find3 T) "Congratulation, you won!") ((not (myMove)) "No moves") ((find3 0) "Sorry, you lost!") ) )
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); # A -> C # A -> B # C -> B # A -> C # B -> A # B -> C # A -> C
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); # A -> C # A -> B # C -> B # A -> C # B -> A # B -> C # A -> 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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon. The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on. A tool exists that extracts library dependencies. Task Write a function that will return a valid compile order of VHDL libraries from their dependencies. Assume library names are single words. Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given. Any self dependencies should be ignored. Any un-orderable dependencies should be flagged. Use the following data as an example: LIBRARY LIBRARY DEPENDENCIES ======= ==================== des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee dw01 ieee dw01 dware gtech dw02 ieee dw02 dware dw03 std synopsys dware dw03 dw02 dw01 ieee gtech dw04 dw04 ieee dw01 dware gtech dw05 dw05 ieee dware dw06 dw06 ieee dware dw07 ieee dware dware ieee dware gtech ieee gtech ramlib std ieee std_cell_lib ieee std_cell_lib synopsys Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01. C.f.   Topological sort/Extracted top item. There are two popular algorithms for topological sorting:   Kahn's 1962 topological sort [1]   depth-first search [2] [3]
#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)() ' You can also add Dependson using code like: ' .DependsOn = New String() {"ieee", "dw01", "dware"} _   fields.Add(New Field() With { _ .Name = "des_system_lib", _ .DependsOn = Split("std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee", " ") _ }) fields.Add(New Field() With { _ .Name = "dw01", _ .DependsOn = Split("ieee dw01 dware gtech", " ") _ }) fields.Add(New Field() With { _ .Name = "dw02", _ .DependsOn = Split("ieee dw02 dware", " ") _ }) fields.Add(New Field() With { _ .Name = "dw03", _ .DependsOn = Split("std synopsys dware dw03 dw02 dw01 ieee gtech", " ") _ }) fields.Add(New Field() With { _ .Name = "dw04", _ .DependsOn = Split("dw04 ieee dw01 dware gtech", " ") _ }) fields.Add(New Field() With { _ .Name = "dw05", _ .DependsOn = Split("dw05 ieee dware", " ") _ }) fields.Add(New Field() With { _ .Name = "dw06", _ .DependsOn = Split("dw06 ieee dware", " ") _ }) fields.Add(New Field() With { _ .Name = "dw07", _ .DependsOn = Split("ieee dware", " ") _ }) fields.Add(New Field() With { _ .Name = "dware", _ .DependsOn = Split("ieee dware", " ") _ }) fields.Add(New Field() With { _ .Name = "gtech", _ .DependsOn = Split("ieee gtech", " ") _ }) fields.Add(New Field() With { _ .Name = "ramlib", _ .DependsOn = Split("std ieee", " ") _ }) fields.Add(New Field() With { _ .Name = "std_cell_lib", _ .DependsOn = Split("ieee std_cell_lib", " ") _ }) fields.Add(New Field() With { _ .Name = "synopsys" _ }) Console.WriteLine("Input:") For Each ThisField As field In fields Console.WriteLine(ThisField.Name) If ThisField.DependsOn IsNot Nothing Then For Each item As String In ThisField.DependsOn Console.WriteLine(" -{0}", item) Next End If Next   Console.WriteLine(vbLf & "...Sorting..." & vbLf)   Dim sortOrder As Integer() = getTopologicalSortOrder(fields)   For i As Integer = 0 To sortOrder.Length - 1 Dim field = fields(sortOrder(i)) Console.WriteLine(field.Name) ' Write up dependencies, too: 'If field.DependsOn IsNot Nothing Then ' For Each item As String In field.DependsOn ' Console.WriteLine(" -{0}", item) ' Next 'End If Next Console.Write("Press any key to continue . . . ") Console.ReadKey(True) End Sub   Private Sub CheckDependencies (ByRef Fields As List(Of Field)) ' Make sure all objects we depend on are part of the field list ' themselves, as there may be dependencies that are not specified as fields themselves. ' Remove dependencies on fields themselves.Y Dim AField As Field, ADependency As String   For i As Integer = Fields.Count - 1 To 0 Step -1 AField=fields(i) If AField.DependsOn IsNot Nothing then For j As Integer = 0 To Ubound(AField.DependsOn) ADependency = Afield.DependsOn(j) ' We ignore fields that depends on themselves: If AField.Name <> ADependency then If ListContainsVertex(fields, ADependency) = False Then ' Add the dependent object to the field list, as it ' needs to be there, without any dependencies Fields.Add(New Field() With { _ .Name = ADependency _ }) End If End If Next j End If Next i End Sub   Private Sub RemoveSelfDependencies (ByRef Fields As List(Of Field)) ' Make sure our fields don't depend on themselves. ' If they do, remove the dependency. Dim InitialUbound as Integer For Each AField As Field In Fields If AField.DependsOn IsNot Nothing Then InitialUbound = Ubound(AField.DependsOn) For i As Integer = InitialUbound to 0 Step - 1 If Afield.DependsOn(i) = Afield.Name Then ' This field depends on itself, so remove For j as Integer = i To UBound(AField.DependsOn)-1 Afield.DependsOn(j)=Afield.DependsOn(j+1) Next ReDim Preserve Afield.DependsOn(UBound(Afield.DependsOn)-1) End If Next End If Next End Sub   Private Function ListContainsVertex(Fields As List(Of Field), VertexName As String) As Boolean ' Check to see if the list of Fields already contains a vertext called VertexName Dim Found As Boolean = False For i As Integer = 0 To fields.Count - 1 If Fields(i).Name = VertexName Then Found = True Exit For End If Next Return Found End Function   Private Function getTopologicalSortOrder(ByRef Fields As List(Of Field)) As Integer() ' Gets sort order. Will also add required dependencies to ' Fields.   ' Make sure we don't have dependencies on ourselves. ' We'll just get rid of them. RemoveSelfDependencies(Fields)   'First check depencies, add them to Fields if required: CheckDependencies(Fields) ' Now we have the correct Fields list, so we can proceed: Dim g As New TopologicalSorter(fields.Count) Dim _indexes As New Dictionary(Of String, Integer)(fields.count)   'add vertex names to our lookup dictionaey For i As Integer = 0 To fields.Count - 1 _indexes(fields(i).Name.ToLower()) = g.AddVertex(i) Next   'add edges For i As Integer = 0 To fields.Count - 1 If fields(i).DependsOn IsNot Nothing Then For j As Integer = 0 To fields(i).DependsOn.Length - 1 g.AddEdge(i, _indexes(fields(i).DependsOn(j).ToLower())) Next End If Next   Dim result As Integer() = g.Sort() Return result End Function   Private Class Field Public Property Name() As String Get Return m_Name End Get Set m_Name = Value End Set End Property Private m_Name As String Public Property DependsOn() As String() Get Return m_DependsOn End Get Set m_DependsOn = Value End Set End Property Private m_DependsOn As String() End Class End Module Class TopologicalSorter ''source adapted from: ''http://tawani.blogspot.com/2009/02/topological-sorting-and-cyclic.html ''which was adapted from: ''http://www.java2s.com/Code/Java/Collections-Data-Structure/Topologicalsorting.htm #Region "- Private Members -"   Private ReadOnly _vertices As Integer() ' list of vertices Private ReadOnly _matrix As Integer(,) ' adjacency matrix Private _numVerts As Integer ' current number of vertices Private ReadOnly _sortedArray As Integer() ' Sorted vertex labels   #End Region   #Region "- CTors -"   Public Sub New(size As Integer) _vertices = New Integer(size - 1) {} _matrix = New Integer(size - 1, size - 1) {} _numVerts = 0 For i As Integer = 0 To size - 1 For j As Integer = 0 To size - 1 _matrix(i, j) = 0 Next Next ' sorted vert labels _sortedArray = New Integer(size - 1) {} End Sub   #End Region   #Region "- Public Methods -"   Public Function AddVertex(vertex As Integer) As Integer _vertices(System.Threading.Interlocked.Increment(_numVerts)-1) = vertex Return _numVerts - 1 End Function   Public Sub AddEdge(start As Integer, [end] As Integer) _matrix(start, [end]) = 1 End Sub   Public Function Sort() As Integer() ' Topological sort While _numVerts > 0 ' while vertices remain, ' get a vertex with no successors, or -1 Dim currentVertex As Integer = noSuccessors() If currentVertex = -1 Then ' must be a cycle Throw New Exception("Graph has cycles") End If   ' insert vertex label in sorted array (start at end) _sortedArray(_numVerts - 1) = _vertices(currentVertex)   ' delete vertex deleteVertex(currentVertex) End While   ' vertices all gone; return sortedArray Return _sortedArray End Function   #End Region   #Region "- Private Helper Methods -"   ' returns vert with no successors (or -1 if no such verts) Private Function noSuccessors() As Integer For row As Integer = 0 To _numVerts - 1 Dim isEdge As Boolean = False ' edge from row to column in adjMat For col As Integer = 0 To _numVerts - 1 If _matrix(row, col) > 0 Then ' if edge to another, isEdge = True ' this vertex has a successor try another Exit For End If Next If Not isEdge Then ' if no edges, has no successors Return row End If Next Return -1 ' no End Function   Private Sub deleteVertex(delVert As Integer) ' if not last vertex, delete from vertexList If delVert <> _numVerts - 1 Then For j As Integer = delVert To _numVerts - 2 _vertices(j) = _vertices(j + 1) Next   For row As Integer = delVert To _numVerts - 2 moveRowUp(row, _numVerts) Next   For col As Integer = delVert To _numVerts - 2 moveColLeft(col, _numVerts - 1) Next End If _numVerts -= 1 ' one less vertex End Sub   Private Sub moveRowUp(row As Integer, length As Integer) For col As Integer = 0 To length - 1 _matrix(row, col) = _matrix(row + 1, col) Next End Sub   Private Sub moveColLeft(col As Integer, length As Integer) For row As Integer = 0 To length - 1 _matrix(row, col) = _matrix(row, col + 1) Next End Sub   #End Region End Class  
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle). For the inverse functions,   use the same number and convert its answer to radians and degrees. If your language does not have trigonometric functions available or only has some available,   write functions to calculate the functions based on any   known approximation or identity.
#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(tan($radians)) . " " . atan(tan($radians)) * 180 / M_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 / / \ 7 8 9 The correct output should look like this: preorder: 1 2 4 7 5 3 6 8 9 inorder: 7 4 2 5 1 8 6 9 3 postorder: 7 4 5 2 8 9 6 3 1 level-order: 1 2 3 4 5 6 7 8 9 See also   Wikipedia article:   Tree traversal.
#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 = seven six~left = eight six~right = nine   out = .array~new .treetraverser~preorder(one, out); say "Preorder: " out~toString("l", ", ") out~empty .treetraverser~inorder(one, out); say "Inorder: " out~toString("l", ", ") out~empty .treetraverser~postorder(one, out); say "Postorder: " out~toString("l", ", ") out~empty .treetraverser~levelorder(one, out); say "Levelorder:" out~toString("l", ", ")     ::class node ::method init expose left right data use strict arg data left = .nil right = .nil   ::attribute left ::attribute right ::attribute data   ::class treeTraverser ::method preorder class use arg node, out if node \== .nil then do out~append(node~data) self~preorder(node~left, out) self~preorder(node~right, out) end   ::method inorder class use arg node, out if node \== .nil then do self~inorder(node~left, out) out~append(node~data) self~inorder(node~right, out) end   ::method postorder class use arg node, out if node \== .nil then do self~postorder(node~left, out) self~postorder(node~right, out) out~append(node~data) end   ::method levelorder class use arg node, out   if node == .nil then return nodequeue = .queue~new nodequeue~queue(node) loop while \nodequeue~isEmpty next = nodequeue~pull out~append(next~data) if next~left \= .nil then nodequeue~queue(next~left) if next~right \= .nil then nodequeue~queue(next~right) 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: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Nim
Nim
import 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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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 include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190
#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(hbound(employee)) fixed binary; declare true bit(1) value ('1'b), false bit(1) value ('0'b); declare dept character (4); declare text character (80) varying; declare (i, j, l, k, m, n, p, t) fixed binary; declare in file input;   open file (in) title ('/TOP-RANK.DAT, RECSIZE(80), TYPE(TEXT)' );   on endfile (in) go to completed_input; j = 0; do forever; get file (in) edit (text) (L); j = j + 1; i = index(text, ','); name(j) = substr(text, 1, i-1); k = index(text, ',', i+1); ID(j) = substr(text, i+1, k-(i+1)); i = k; k = index(text, ',', i+1); salary(j) = substr(text, i+1, k-(i+1)); department(j) = substr(text, k+1); end;   completed_input: m = hbound(employee); put skip list ('How many highest-paid employees do you want?'); get (n); put skip edit ('Looking for the ', trim(n), ' highest-paid employees in each department') (a); done = false; do i = 1 to m; do j = 1 to m; if done(j) then iterate; dept = department(j); /* done(j) = true; */ leave; end; /* Locate all the employees of this department. */ k = 0; do j = 1 to m; if ^done(j) & (department(j) = dept) then do; k = k + 1; ptr(k) = j; done(j) = true; end; end; if k = 0 then leave; /* (No more departments.) */   put skip list ('Employees in department ' || dept || ' are:-' ); do j = 1 to k; put skip list (employee(ptr(j))); end; /* We now have k employees in "dept". Now find the maximum n salaries. */ /* ptr points to all of them. */ /* Use a bubble sort to move n values to one end. */ do p = 1 to min(n, k); do j = 1 to k-1; if salary(ptr(j)) > salary(ptr(j+1)) then do; t = ptr(j+1); ptr(j+1) = ptr(j); ptr(j) = t; end; end; end;   /* Having moved the largest n values to the end of our list, */ /* we print them. */ put skip list ('Highest-paid employees in department ' || dept || ':-'); do j = k to k-min(k,n)+1 by -1; put skip list (employee(ptr(j)) ); end; end; put skip list ('FINISHED'); end rank;
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedia tic-tac-toe.
#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).     display_tic_tac_toe(TTT) :- retractall(box(_,_)), retractall(tic_tac_toe_window(_)), new(D, window('Tic-tac-Toe')), send(D, size, size(170,170)), X = 10, Y = 10, display(D, X, Y, 0, TTT), assert(tic_tac_toe_window(D)), send(D, open).   display(_, _, _, _, []).   display(D, X, Y, N, [A,B,C|R]) :- display_line(D, X, Y, N, [A,B,C]), Y1 is Y+50, N3 is N+3, display(D, X, Y1, N3, R).     display_line(_, _, _, _, []). display_line(D, X, Y, N, [C|R]) :- ( nonvar(C)-> C1 = C; C1 = ' '), new(B, tic_tac_toe_box(C1)), assertz(box(N, B)), send(D, display, B, point(X, Y)), X1 is X + 50, N1 is N+1, display_line(D, X1, Y, N1, R).       % class tic_tac_toe_box % display an 'x' when the player clicks % display an 'o' when the computer plays :- pce_begin_class(tic_tac_toe_box, box, "Graphical window with text").   variable(mess, any, both, "text to display").   initialise(P, Lbl) :-> send(P, send_super, initialise), send(P, slot, mess, Lbl), WS = 50, HS = 50, send(P, size, size(WS,HS)), send(P, recogniser, handler_group(new(click_gesture(left, '', single, message(@receiver, my_click))))).   % the box is clicked my_click(B) :-> send(B, set_val, x), send(@prolog, play).   % only works when the box is "free" set_val(B, Val) :-> get(B, slot, mess, ' '), send(B, slot, mess, Val), send(B, redraw), send(B, flush).     % redefined method to display custom graphical objects. '_redraw_area'(P, A:area) :-> send(P, send_super, '_redraw_area', A), %we display the text get(P, slot, mess, Lbl), new(Str1, string(Lbl)), get_object(P, area, area(X,Y,W,H)), send(P, draw_box, X, Y, W, H), send(P, draw_text, Str1, font(times, normal, 30), X, Y, W, H, center, center).   :- pce_end_class.   play :- numlist(0, 8, L), maplist(init, L, TTT), finished(x, TTT, Val), ( Val = 2 -> send(@display, inform,'You win !'), tic_tac_toe_window(D), send(D, destroy) ; ( Val = 1 -> send(@display, inform,'Draw !'), tic_tac_toe_window(D), send(D, destroy) ; next_move(TTT, TT1), maplist(display, L, TT1), finished(o, TT1, V), ( V = 2 -> send(@display, inform,'I win !'), tic_tac_toe_window(D), send(D, destroy) ; ( V = 1 -> send(@display, inform,'Draw !'), tic_tac_toe_window(D), send(D, destroy) ; true)))).     % use minmax to compute the next move next_move(TTT, TT1) :- minimax(o, 0, 1024, TTT, _V1- TT1).     % we display the new board display(I, V) :- nonvar(V), box(I, V1), send(V1, set_val, V).   display(_I, _V).   % we create the board for minmax init(I, V) :- box(I, V1), get(V1, slot, mess, V), V \= ' '.   init(_I, _V).   % winning position for the player P ? winned(P, [A1, A2, A3, A4, A5, A6, A7, A8, A9]) :- (is_winning_line(P, [A1, A2, A3]); is_winning_line(P, [A4, A5, A6]); is_winning_line(P, [A7, A8, A9]); is_winning_line(P, [A1, A4, A7]); is_winning_line(P, [A2 ,A5, A8]); is_winning_line(P, [A3, A6, A9]); is_winning_line(P, [A1, A5, A9]); is_winning_line(P, [A3, A5, A7])).     is_winning_line(P, [A, B, C]) :- nonvar(A), A = P, nonvar(B), B = P, nonvar(C), C = P.   % Winning position for the player eval(Player, Deep, TTT, V) :- winned(Player, TTT), ( Player = o -> V is 1000 - 50 * Deep; V is -1000+ 50 * Deep).   % Loosing position for the player eval(Player, Deep, TTT, V) :- select(Player, [o,x], [Player1]), winned(Player1, TTT), ( Player = x -> V is 1000 - 50 * Deep; V is -1000+ 50 * Deep).   % Draw position eval(_Player, _Deep, TTT, 0) :- include(var, TTT, []).     % we fetch the free positions of the board possible_move(TTT, LMove) :- new(C, chain), forall(between(0,8, I), ( nth0(I, TTT, X), ( var(X) -> send(C, append, I); true))), chain_list(C, LMove).   % we create the new position when the player P clicks % the box "N" assign_move(P, TTT, N, TT1) :- copy_term(TTT, TT1), nth0(N, TT1, P).   % We fetch all the possible boards obtained from board TTT % for the player P get_next(Player, Deep, TTT, Player1, Deep1, L):- possible_move(TTT, LMove), select(Player, [o,x], [Player1]), Deep1 is Deep + 1, maplist(assign_move(Player, TTT), LMove, L).     % The game is over ? % Player P wins finished(P, TTT, 2) :- winned(P, TTT).   % Draw finished(_P, TTT, 1) :- include(var, TTT, []).   % the game is not over finished(_P, _TTT, 0) .   % minmax must knows when the computer plays % (o for ordinateur in French) computer(o).    
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 solver interface type towers struct { // an empty struct. some other solver might fill this with some // data representation, maybe for algorithm validation, or maybe for // visualization. }   // play is sole method required to implement solver type func (t *towers) play(n int) { // drive recursive solution, per task description t.moveN(n, 1, 2, 3) }   // recursive algorithm func (t *towers) moveN(n, from, to, via int) { if n > 0 { t.moveN(n-1, from, via, to) t.move1(from, to) t.moveN(n-1, via, to, from) } }   // example function prints actions to screen. // enhance with validation or visualization as needed. func (t *towers) move1(from, to int) { fmt.Println("move disk from rod", from, "to rod", to) }
http://rosettacode.org/wiki/Topological_sort
Topological sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon. The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on. A tool exists that extracts library dependencies. Task Write a function that will return a valid compile order of VHDL libraries from their dependencies. Assume library names are single words. Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given. Any self dependencies should be ignored. Any un-orderable dependencies should be flagged. Use the following data as an example: LIBRARY LIBRARY DEPENDENCIES ======= ==================== des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee dw01 ieee dw01 dware gtech dw02 ieee dw02 dware dw03 std synopsys dware dw03 dw02 dw01 ieee gtech dw04 dw04 ieee dw01 dware gtech dw05 dw05 ieee dware dw06 dw06 ieee dware dw07 ieee dware dware ieee dware gtech ieee gtech ramlib std ieee std_cell_lib ieee std_cell_lib synopsys Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01. C.f.   Topological sort/Extracted top item. There are two popular algorithms for topological sorting:   Kahn's 1962 topological sort [1]   depth-first search [2] [3]
#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) { for (c in todo) if (_adjacency[r][c]) return true return false }   topoSort() { var res = [] var todo = List.filled(_vertices.count, 0) for (i in 0...todo.count) todo[i] = i while (!todo.isEmpty) { var outer = false var i = 0 for (r in todo) { if (!hasDependency(r, todo)) { todo.removeAt(i) res.add(_vertices[r]) outer = true break } i = i + 1 } if (!outer) { System.print("Graph has cycles") return "" } } return res } }   var s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05, " + "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys"   var deps = [ [2, 0], [2, 14], [2, 13], [2, 4], [2, 3], [2, 12], [2, 1], [3, 1], [3, 10], [3, 11], [4, 1], [4, 10], [5, 0], [5, 14], [5, 10], [5, 4], [5, 3], [5, 1], [5, 11], [6, 1], [6, 3], [6, 10], [6, 11], [7, 1], [7, 10], [8, 1], [8, 10], [9, 1], [9, 10], [10, 1], [11, 1], [12, 0], [12, 1], [13, 1] ]   var g = Graph.new(s, deps) System.print("Topologically sorted order:") System.print(g.topoSort()) System.print() // now insert [3, 6] at index 10 of deps deps.insert(10, [3, 6]) var g2 = Graph.new(s, deps) System.print("Following the addition of dw04 to the dependencies of dw01:") System.print(g2.topoSort())
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle). For the inverse functions,   use the same number and convert its answer to radians and degrees. If your language does not have trigonometric functions available or only has some available,   write functions to calculate the functions based on any   known approximation or identity.
#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 45.0)) *Scl) ) (prinl (format (asin (sin (/ pi 4))) *Scl) " " (format (rtod (asin (sin (dtor 45.0)))) *Scl) ) (prinl (format (acos (cos (/ pi 4))) *Scl) " " (format (rtod (acos (cos (dtor 45.0)))) *Scl) ) (prinl (format (atan (tan (/ pi 4))) *Scl) " " (format (rtod (atan (tan (dtor 45.0)))) *Scl) )
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle). For the inverse functions,   use the same number and convert its answer to radians and degrees. If your language does not have trigonometric functions available or only has some available,   write functions to calculate the functions based on any   known approximation or identity.
#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 = atand(v); put skip list (y);   /* hyperbolic functions: */ v = sinh(x); put skip list (v); v = cosh(x); put skip list (v); v = tanh(x); y = atanh(v); put skip list (y);  
http://rosettacode.org/wiki/Tree_traversal
Tree traversal
Task Implement a binary tree where each node carries an integer,   and implement:   pre-order,   in-order,   post-order,     and   level-order   traversal. Use those traversals to output the following tree: 1 / \ / \ / \ 2 3 / \ / 4 5 6 / / \ 7 8 9 The correct output should look like this: preorder: 1 2 4 7 5 3 6 8 9 inorder: 7 4 2 5 1 8 6 9 3 postorder: 7 4 5 2 8 9 6 3 1 level-order: 1 2 3 4 5 6 7 8 9 See also   Wikipedia article:   Tree traversal.
#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] {Preorder L} {Preorder R}]} end end   fun {Inorder T} case T of e then nil [] n(V L R) then {Concat [{Inorder L} [V] {Inorder R}]} end end   fun {Postorder T} case T of e then nil [] n(V L R) then {Concat [{Postorder L} {Postorder R} [V]]} end end   local fun {Collect Queue} case Queue of nil then nil [] e|Xr then {Collect Xr} [] n(V L R)|Xr then V|{Collect {Append Xr [L R]}} end end in fun {Levelorder T} {Collect [T]} end end in {Show {Preorder Tree}} {Show {Inorder Tree}} {Show {Postorder Tree}} {Show {Levelorder Tree}}
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190
#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') WHEN 30 THEN '-' WHEN 50 THEN 'Department: ' || DEPT_ID || ', pop: ' || POPULATION || '. Avg Salary: ' || TO_CHAR(SALARY, '99990.99') WHEN 70 THEN LPAD('Employee ID', 14) || LPAD('Employee name', 20) || LPAD('Salary', 9) || 'Rank' WHEN 90 THEN LPAD('+', 14, '-') || LPAD('+', 20, '-') || LPAD('+', 9, '-') || LPAD('+', 4, '-') ELSE LPAD(' ', 8) || LPAD(EMP_ID, 6) || LPAD(EMP_NAME, 20) || TO_CHAR(SALARY, '99990.99') || LPAD(CASE WHEN TIE_COUNT = 1 THEN ' ' ELSE 'T' END || RANK, 4) END "Top rank per group" FROM (SELECT 10 LINE ,NULL EMP_ID ,NULL EMP_NAME ,' ' DEPT_ID ,AVG(SALARY) SALARY ,0 RANK ,COUNT(DISTINCT DEPT_ID) TIE_COUNT ,COUNT(*) POPULATION FROM EMP UNION ALL SELECT 30 LINE ,NULL EMP_ID ,NULL EMP_NAME ,DEPT_ID ,0 SALARY ,0 RANK ,0 TIE_COUNT ,0 POPULATION FROM EMP GROUP BY DEPT_ID UNION ALL SELECT 50 LINE ,NULL EMP_ID ,NULL EMP_NAME ,DEPT_ID ,AVG(SALARY) SALARY ,0 RANK ,0 TIE_COUNT ,COUNT(*) POPULATION FROM EMP GROUP BY DEPT_ID UNION ALL SELECT 70 LINE ,NULL EMP_ID ,NULL EMP_NAME ,DEPT_ID ,0 SALARY ,0 RANK ,0 TIE_COUNT ,0 POPULATION FROM EMP GROUP BY DEPT_ID UNION ALL SELECT 90 LINE ,NULL EMP_ID ,NULL EMP_NAME ,DEPT_ID ,0 SALARY ,0 RANK ,0 TIE_COUNT ,0 POPULATION FROM EMP GROUP BY DEPT_ID UNION ALL SELECT 110 LINE ,EMP_ID ,EMP_NAME ,DEPT_ID ,SALARY ,(SELECT COUNT(DISTINCT EMP4.SALARY) FROM EMP EMP4 WHERE EMP4.DEPT_ID = EMP3.DEPT_ID AND EMP4.SALARY >= EMP3.SALARY) RANK ,(SELECT COUNT(*) FROM EMP EMP2 WHERE EMP2.DEPT_ID = EMP3.DEPT_ID AND EMP2.SALARY = EMP3.SALARY) TIE_COUNT ,0 POPULATION FROM EMP EMP3 WHERE TOP_N >= -- Here is the meat, Correlated subquery (SELECT COUNT(DISTINCT EMP4.SALARY) FROM EMP EMP4 WHERE EMP4.DEPT_ID = EMP3.DEPT_ID AND EMP4.SALARY >= EMP3.SALARY)) ORDER BY DEPT_ID ,LINE ,SALARY DESC ,EMP_ID;   V_EMP CSR_EMP%ROWTYPE; BEGIN FOR V_EMP IN CSR_EMP(TOP_N) LOOP DBMS_OUTPUT.PUT_LINE(v_emp."Top rank per group"); END LOOP; END;
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedia tic-tac-toe.
#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 in(0,3,6)))   def score(): for w in wins: b = board[w[0]] if b in 'XO' and all (board[i] == b for i in w): return b, [i+1 for i in w] return None, None   def finished(): return all (b in 'XO' for b in board)   def space(): return [ b for b in board if b not in 'XO']   def my_turn(xo): options = space() choice = random.choice(options) board[int(choice)-1] = xo return choice   def your_turn(xo): options = space() while True: choice = input(" Put your %s in any of these positions: %s "  % (xo, ''.join(options))).strip() if choice in options: break print( "Whoops I don't understand the input" ) board[int(choice)-1] = xo return choice   def me(xo='X'): printboard() print('I go at', my_turn(xo)) return score() assert not s[0], "\n%s wins across %s" % s   def you(xo='O'): printboard() # Call my_turn(xo) below for it to play itself print('You went at', your_turn(xo)) return score() assert not s[0], "\n%s wins across %s" % s     print(__doc__) while not finished(): s = me('X') if s[0]: printboard() print("\n%s wins across %s" % s) break if not finished(): s = you('O') if s[0]: printboard() print("\n%s wins across %s" % s) break else: print('\nA draw')  
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 { !(it.is(from) || it.is(to)) } -> if (!from) return def n = from.size() moveStack(tail(from, n-1), using, to) moveRing(from, to) moveStack(tail(using, n-1), 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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon. The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on. A tool exists that extracts library dependencies. Task Write a function that will return a valid compile order of VHDL libraries from their dependencies. Assume library names are single words. Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given. Any self dependencies should be ignored. Any un-orderable dependencies should be flagged. Use the following data as an example: LIBRARY LIBRARY DEPENDENCIES ======= ==================== des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee dw01 ieee dw01 dware gtech dw02 ieee dw02 dware dw03 std synopsys dware dw03 dw02 dw01 ieee gtech dw04 dw04 ieee dw01 dware gtech dw05 dw05 ieee dware dw06 dw06 ieee dware dw07 ieee dware dware ieee dware gtech ieee gtech ramlib std ieee std_cell_lib ieee std_cell_lib synopsys Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01. C.f.   Topological sort/Extracted top item. There are two popular algorithms for topological sorting:   Kahn's 1962 topological sort [1]   depth-first search [2] [3]
#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 is non-empty do (n:=S.pop()) : L.append(_); //remove a node n from S, add n to tail of L foreach m in (ds:=roots.find(n,List)){ //node m with an edge e from n to m allDs.del(allDs.index(m)); if (Void==allDs.find(m)) S.append(m); //m has no other incoming edges } roots.del(n); // remove edge e from the graph } if(roots) throw(Exception.ValueError("Cycle: "+roots.keys)); L }