task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Erlang
Erlang
-module(tok). -export([start/0]).   start() -> Lst = string:tokens("Hello,How,Are,You,Today",","), io:fwrite("~s~n", [string:join(Lst,".")]), ok.
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Euphoria
Euphoria
function split(sequence s, integer c) sequence out integer first, delim out = {} first = 1 while first<=length(s) do delim = find_from(c,s,first) if delim = 0 then delim = length(s)+1 end if out = append(out,s[first..delim-1]) first = delim + 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 ...
#Go
Go
package empty   func Empty() {}   func Count() { // count to a million for i := 0; i < 1e6; i++ { } }
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 ...
#Groovy
Groovy
import java.lang.management.ManagementFactory import java.lang.management.ThreadMXBean   def threadMX = ManagementFactory.threadMXBean assert threadMX.currentThreadCpuTimeSupported threadMX.threadCpuTimeEnabled = true   def clockCpuTime = { Closure c -> def start = threadMX.currentThreadCpuTime c.call() (th...
http://rosettacode.org/wiki/Top_rank_per_group
Top rank per group
Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett...
#FreeBASIC
FreeBASIC
#define N 3 'show the top three employees of each rank   'here is all the data to be read in   data "Tyler Bennett","E10297",32000,"D101" data "John Rappl","E21437",47000,"D050" data "George Woltman","E00127",53500,"D101" data "Adam Smith","E63535",18000,"D202" data "Claire Buckman","E39876",27800,"D202" data "Dav...
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#ERRE
ERRE
!-------------------------------------------- ! TRIS.R : gioca a tris contro l'operatore !-------------------------------------------- PROGRAM TRIS DIM TRIS%[9],T1%[9],PIECES$[3] !$SEGMENT=$B800 !$INCLUDE="PC.LIB" PROCEDURE DELAY(COUNT%) FOR Z%=1 TO COUNT DO END FOR END PROCEDURE PROCEDURE SET_BOARD ! ! Diseg...
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Clojure
Clojure
(defn towers-of-hanoi [n from to via] (when (pos? n) (towers-of-hanoi (dec n) from via to) (printf "Move from %s to %s\n" from to) (recur (dec n) via to from)))
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#PicoLisp
PicoLisp
(let R 0 (prinl R) (for (X 1 (>= 32 X)) (setq R (bin (pack (bin R) (bin (x| (dec (** 2 X)) R)) ) ) ) (prinl (pack 0 (bin R))) (inc 'X X) ) )
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#PowerShell
PowerShell
function New-ThueMorse ( $Digits ) { # Start with seed 0 $ThueMorse = "0"   # Decrement digits remaining $Digits--   # While we still have digits to calculate... While ( $Digits -gt 0 ) { # Number of digits we'll get this loop (what we still need up to the maximum availab...
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#Raku
Raku
sub tokenize ($string, :$sep!, :$esc!) { return $string.match(/([ <!before $sep | $esc> . | $esc . ]*)+ % $sep/)\ .[0].map(*.subst: /$esc )> ./, '', :g); }   say "'$_'" for tokenize 'one^|uno||three^^^^|four^^^|^cuatro|', sep => '|', esc => '^';
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#REXX
REXX
/*REXX program demonstrates tokenizing and displaying a string with escaping sequences. */ str = 'one^|uno||three^^^^|four^^^|^cuatro|' /*the character string to be tokenized.*/ esc = '^' /* " escape character to be used. */ sep = '|' ...
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
TopologicalSort[ Graph[Flatten[# /. {l_, ld_} :> Map[# -> l &, DeleteCases[ld, l]]]]] /. {_TopologicalSort -> $Failed} &@ {{"des_system_lib", {"std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee"}}, {"dw01", {"ieee", "dw01", "dware", "gtech"}}, {"dw02", ...
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#Raku
Raku
sub run_utm(:$state! is copy, :$blank!, :@rules!, :@tape = [$blank], :$halt, :$pos is copy = 0) { $pos += @tape if $pos < 0; die "Bad initial position" unless $pos ~~ ^@tape;   STEP: loop { print "$state\t"; for ^@tape { my $v = @tape[$_]; print $_ == $pos ?? "[$v]" !! " ...
http://rosettacode.org/wiki/Totient_function
Totient function
The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the integers up to a given positiv...
#Ruby
Ruby
  require "prime"   def 𝜑(n) n.prime_division.inject(1) {|res, (pr, exp)| res *= (pr-1) * pr**(exp-1) } end   1.upto 25 do |n| tot = 𝜑(n) puts "#{n}\t #{tot}\t #{"prime" if n-tot==1}" end   [100, 1_000, 10_000, 100_000].each do |u| puts "Number of primes up to #{u}: #{(1..u).count{|n| n-𝜑(n) == 1} }" end  
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#jq
jq
  # degrees to radians def radians: (-1|acos) as $pi | (. * $pi / 180);   def task: (-1|acos) as $pi | ($pi / 180) as $degrees | "Using radians:", " sin(-pi / 6) = \( (-$pi / 6) | sin )", " cos(3 * pi / 4) = \( (3 * $pi / 4) | cos)", " tan(pi / 3) = \( ($pi / 3) | tan)", " ...
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#Wren
Wren
import "io" for Stdin, Stdout import "/fmt" for Fmt   var f = Fn.new { |x| x.abs.sqrt + 5*x*x*x }   var s = List.filled(11, 0) System.print("Please enter 11 numbers:") var count = 0 while (count < 11) { Fmt.write(" Number $-2d : ", count + 1) Stdout.flush() var number = Num.fromString(Stdin.readLine()) ...
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#Scala
Scala
object TruncatablePrimes { def main(args: Array[String]): Unit = { val max = 1000000   println( s"""|ltPrime: ${ltPrimes.takeWhile(_ <= max).last} |rtPrime: ${rtPrimes.takeWhile(_ <= max).last} |""".stripMargin) }   def ltPrimes: LazyList[Int] = 2 #:: LazyList.from(3, 2).filter(i...
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 / ...
#Forth
Forth
\ binary tree (dictionary) : node ( l r data -- node ) here >r , , , r> ; : leaf ( data -- node ) 0 0 rot node ;   : >data ( node -- ) @ ; : >right ( node -- ) cell+ @ ; : >left ( node -- ) cell+ cell+ @ ;   : preorder ( xt tree -- ) dup 0= if 2drop exit then 2dup >data swap execute 2dup >left recurse >r...
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#F.23
F#
System.String.Join(".", "Hello,How,Are,You,Today".Split(','))
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 ...
#Halon
Halon
$t = uptime();   sleep(1);   echo uptime() - $t;
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 ...
#Haskell
Haskell
import System.CPUTime (getCPUTime)   -- We assume the function we are timing is an IO monad computation timeIt :: (Fractional c) => (a -> IO b) -> a -> IO c timeIt action arg = do startTime <- getCPUTime action arg finishTime <- getCPUTime return $ fromIntegral (finishTime - startTime) / 1000000000000   -- Vers...
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...
#FunL
FunL
data Employee( name, id, salary, dept )   employees = [ Employee( 'Tyler Bennett', 'E10297', 32000, 'D101' ), Employee( 'John Rappl', 'E21437', 47000, 'D050' ), Employee( 'George Woltman', 'E00127', 53500, 'D101' ), Employee( 'Adam Smith', 'E63535', 18000, 'D202' ), Employee( 'Claire Buckman', 'E39876', 27800...
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#Euphoria
Euphoria
  include std/console.e include std/text.e include std/search.e include std/sequence.e   sequence board sequence players = {"X","O"}   function DisplayBoard() for i = 1 to 3 do for j = 1 to 3 do printf(1,"%s",board[i][j]) if j < 3 then printf(1,"%s","|") end if end for if i < 3 then puts(1,"\n--...
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#CLU
CLU
move = proc (n, from, via, to: int) po: stream := stream$primary_output() if n > 0 then move(n-1, from, to, via) stream$putl(po, "Move disk from pole " || int$unparse(from) || " to pole " || int$unparse(to)) move(n-1, via, fr...
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#PureBasic
PureBasic
EnableExplicit   Procedure.i count_bits(v.i) Define c.i While v c+v&1 v>>1 Wend ProcedureReturn c EndProcedure   If OpenConsole() Define n.i For n=0 To 255 Print(Str(count_bits(n)%2)) Next PrintN(~"\n...fin") : Input() EndIf
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Python
Python
  m='0' print(m) for i in range(0,6): m0=m m=m.replace('0','a') m=m.replace('1','0') m=m.replace('a','1') m=m0+m print(m)  
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#Ring
Ring
  tokenize("one^|uno||three^^^^|four^^^|^cuatro|", "|", "^")   func tokenize(src, sep, esc) field = 1 escaping = false see "" + field + " " for i = 1 to len(src) char = substr(src, i, 1) if escaping see char escaping = false else switch char on sep see n...
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#Ruby
Ruby
  def tokenize(string, sep, esc) sep = Regexp.escape(sep) esc = Regexp.escape(esc) string.scan(/\G (?:^ | #{sep}) (?: [^#{sep}#{esc}] | #{esc} .)*/x).collect do |m| m.gsub(/#{esc}(.)/, '\1').gsub(/^#{sep}/, '') end end   p tokenize('one^|uno||three^^^^|four^^^|^cuatro|', '|', '^')    
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 ...
#Mercury
Mercury
  :- module topological_sort.   :- interface.   :- import_module io. :- pred main(io::di,io::uo) is det.     :- implementation. :- import_module string, solutions, list, set, require.   :- pred min_element(set(T),pred(T,T),T). :- mode min_element(in,pred(in,in) is semidet,out) is nondet. min_element(_,_,_):-fail. min_e...
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#REXX
REXX
/*REXX program executes a Turing machine based on initial state, tape, and rules. */ state = 'q0' /*the initial Turing machine state. */ term = 'qf' /*a state that is used for a halt. */ blank = 'B' ...
http://rosettacode.org/wiki/Totient_function
Totient function
The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the integers up to a given positiv...
#Rust
Rust
use num::integer::gcd;   fn main() { // Compute the totient of the first 25 natural integers println!("N\t phi(n)\t Prime"); for n in 1..26 { let phi_n = phi(n); println!("{}\t {}\t {:?}", n, phi_n, phi_n == n - 1); }   // Compute the number of prime numbers for various steps [1,...
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#Jsish
Jsish
help Math Math.method(...) Commands performing math operations on numbers Methods: abs acos asin atan atan2 ceil cos exp floor log max min pow random round sin sqrt tan
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#XBasic
XBasic
  ' Trabb Pardo-Knuth algorithm PROGRAM "tpkalgorithm" VERSION "0.0001"   IMPORT "xma"   DECLARE FUNCTION Entry () INTERNAL FUNCTION SINGLE F(SINGLE n)   FUNCTION Entry () ' Used "magic numbers" because of strict specification of the algorithm. SINGLE s[10] SINGLE tmp, r UBYTE i PRINT "Enter 11 numbers." FO...
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#XPL0
XPL0
include c:\cxpl\codes;   func real F(X); real X; return sqrt(abs(X)) + 5.0*X*X*X;   real Result, S(11); int I; [Text(0, "Please enter 11 numbers: "); for I:= 0 to 11-1 do S(I):= RlIn(0);   for I:= 11-1 downto 0 do [RlOut(0, S(I)); Result:= F(S(I)); if Result > 400.0 then Text(0,...
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#Sidef
Sidef
func t_prime(n, left=true) { var p = %w(2 3 5 7); var f = ( left ? { '1'..'9' ~X+ p }  : { p ~X+ '1'..'9' } ) n.times { p = f().grep{ .to_i.is_prime } } p.map{.to_i}.max }   say t_prime(5, left: true) say t_prime(5, left: false)
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 / ...
#Fortran
Fortran
  IF (STYLE.EQ."PRE") CALL OUT(HAS) IF (LINKL(HAS).GT.0) CALL TARZAN(LINKL(HAS),STYLE) IF (STYLE.EQ."IN") CALL OUT(HAS) IF (LINKR(HAS).GT.0) CALL TARZAN(LINKR(HAS),STYLE) IF (STYLE.EQ."POST") CALL OUT(HAS)
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Factor
Factor
"Hello,How,Are,You,Today" "," split "." join print
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Falcon
Falcon
  /* created by Aykayayciti Earl Lamont Montgomery April 9th, 2018 */   a = [] a = strSplit("Hello,How,Are,You,Today", ",") index = 0 start = 0 b = "" for index in [ start : len(a)-1 : 1 ] b = b + a[i] + "." end   > b  
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 ...
#HicEst
HicEst
t_start = TIME() ! returns seconds since midnight SYSTEM(WAIT = 1234) ! wait 1234 milliseconds t_end = TIME()   WRITE(StatusBar) t_end - t_start, " seconds"
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#Icon_and_Unicon
Icon and Unicon
procedure timef(f) #: time a function f local gcol,alloc,used,size,runtime,header,x,i   title := ["","total","static","string","block"] # headings collect() # start with collected memory (before baseline) every put(gcol := [], -&collections) ...
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...
#Go
Go
package main   import ( "fmt" "sort" )   // language-native data description type Employee struct { Name, ID string Salary int Dept string }   type EmployeeList []*Employee   var data = EmployeeList{ {"Tyler Bennett", "E10297", 32000, "D101"}, {"John Rappl", "E21437", 47000, "D050"}, ...
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#F.23
F#
type Brick = | Empty | Computer | User   let brickToString = function | Empty -> ' ' | Computer -> 'X' | User -> 'O'   // y -> x -> Brick type Board = Map<int, Map<int, Brick> >   let emptyBoard = let emptyRow = Map.ofList [0,Empty; 1,Empty; 2,Empty] Map.ofList [0,emptyRow; 1,emptyRow; 2,emptyRow]   let get (...
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#COBOL
COBOL
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. towers-of-hanoi.   PROCEDURE DIVISION. CALL "move-disk" USING 4, 1, 2, 3 . END PROGRAM towers-of-hanoi.   IDENTIFICATION DIVISION. PROGRAM-ID. move-disk RECURSIVE.   DATA DIVISION. LINKAGE SECTION. 01 n PIC 9 USAGE COMP. 01 from...
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Quackery
Quackery
[ [] 0 rot times [ i^ dup 1 - ^ dup 1 >> ^ hex 55555555 & if [ 1 swap - ] dup dip [ digit join ] ] drop ] is thue-morse ( n --> $ )   20 thue-morse echo$ cr
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#R
R
  thue_morse <- function(steps) { sb1 <- "0" sb2 <- "1" for (idx in 1:steps) { tmp <- sb1 sb1 <- paste0(sb1, sb2) sb2 <- paste0(sb2, tmp) } sb1 } cat(thue_morse(6), "\n")  
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Racket
Racket
#lang racket (define 1<->0 (match-lambda [#\0 #\1] [#\1 #\0])) (define (thue-morse-step (s "0")) (string-append s (list->string (map 1<->0 (string->list s)))))   (define (thue-morse n) (let inr ((n (max (sub1 n) 0)) (rv (list "0"))) (if (zero? n) (reverse rv) (inr (sub1 n) (cons (thue-morse-step (car rv)) rv)))...
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#Rust
Rust
const SEPARATOR: char = '|'; const ESCAPE: char = '^'; const STRING: &str = "one^|uno||three^^^^|four^^^|^cuatro|";   fn tokenize(string: &str) -> Vec<String> { let mut token = String::new(); let mut tokens: Vec<String> = Vec::new(); let mut chars = string.chars(); while let Some(ch) = chars.next() { ...
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#Scala
Scala
object TokenizeStringWithEscaping0 extends App {   val (markerSpE,markerSpF) = ("\ufffe" , "\uffff")   def tokenize(str: String, sep: String, esc: String): Array[String] = {   val s0 = str.replace( esc + esc, markerSpE).replace(esc + sep, markerSpF) val s = if (s0.last.toString == esc) s0.replace(esc, "") +...
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 ...
#Nim
Nim
import sequtils, strutils, sets, tables, sugar   type StringSet = HashSet[string]     proc topSort(data: var OrderedTable[string, StringSet]) = ## Topologically sort the data in place.   var ranks: Table[string, Natural] # Maps the keys to a rank.   # Remove self dependencies. for key, values in data.mpairs: ...
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#Ruby
Ruby
class Turing class Tape def initialize(symbols, blank, starting_tape) @symbols = symbols @blank = blank @tape = starting_tape @index = 0 end def read retval = @tape[@index] unless retval retval = @tape[@i...
http://rosettacode.org/wiki/Totient_function
Totient function
The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the integers up to a given positiv...
#S-BASIC
S-BASIC
  $lines   rem - return p mod q function mod(p, q = integer) = integer end = p - q * (p / q)   rem - return greatest common divisor of x and y function gcd(x, y = integer) = integer var r, temp = integer if x < y then begin temp = x x = y y = temp end r = mod(x, y) whi...
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#Julia
Julia
# v0.6.0   rad = π / 4 deg = 45.0   @show rad deg @show sin(rad) sin(deg2rad(deg)) @show cos(rad) cos(deg2rad(deg)) @show tan(rad) tan(deg2rad(deg)) @show asin(sin(rad)) asin(sin(rad)) |> rad2deg @show acos(cos(rad)) acos(cos(rad)) |> rad2deg @show atan(tan(rad)) atan(tan(rad)) |> rad2deg
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#zkl
zkl
fcn f(x) { x.abs().pow(0.5) + x.pow(3)*5 } reg ns; do{ ns=ask("11 numbers seperated by spaces: "); try{ ns=ns.split(" ").filter().apply("toFloat") } catch{} }while(not ns.isType(List) or ns.len()!=11); ns.reverse().apply(fcn(x){ fx:=f(x); "f(%7.3f)-->%s".fmt(x, if(fx>400)"Overflow" else fx) }) .pump(Console.pr...
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#Swift
Swift
func isPrime(_ n: Int) -> Bool { if n < 2 { return false } if n % 2 == 0 { return n == 2 } if n % 3 == 0 { return n == 3 } var p = 5 while p * p <= n { if n % p == 0 { return false } p += 2 if n % p == 0 { re...
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#Tcl
Tcl
package require Tcl 8.5   # Optimized version of the Sieve-of-Eratosthenes task solution proc sieve n { set primes [list] if {$n < 2} {return $primes} set nums [dict create] for {set i 2} {$i <= $n} {incr i} { dict set nums $i "" } set next 2 set limit [expr {sqrt($n)}] while {$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 / ...
#FreeBASIC
FreeBASIC
  #define NULL 0   Dim Shared As Byte maxnodos = 100 Dim Shared As Byte raiz = 0 Dim Shared As Byte izda = 1 Dim Shared As Byte dcha = 2 Dim Shared As Byte arbol(maxnodos, 3)   Sub crear_arbol() arbol(1, raiz) = 1 arbol(1, izda) = 2 : arbol(1, dcha) = 3 arbol(2, raiz) = 2 arbol(2, izda) =...
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Fantom
Fantom
  class Main { public static Void main () { str := "Hello,How,Are,You,Today" words := str.split(',') words.each |Str word| { echo ("${word}. ") } } }  
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Fennel
Fennel
(fn string.split [self sep] (let [pattern (string.format "([^%s]+)" sep) fields {}] (self:gsub pattern (fn [c] (tset fields (+ 1 (length fields)) c))) fields))   (let [str "Hello,How,Are,You,Today"] (print (table.concat (str:split ",") ".")))
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 ...
#Ioke
Ioke
use("benchmark")   func = method((1..50000) reduce(+))   Benchmark report(1, 1, 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 ...
#J
J
(6!:2 , 7!:2) '|: 50 50 50 $ i. 50^3' 0.00488008 3.14829e6 timespacex '|: 50 50 50 $ i. 50^3' 0.00388519 3.14829e6
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...
#Groovy
Groovy
def displayRank(employees, number) { employees.groupBy { it.Department }.sort().each { department, staff -> println "Department $department" println " Name ID Salary" staff.sort { e1, e2 -> e2.Salary <=> e1.Salary } staff[0..<Math.min(number, staff.size())].eac...
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#Forth
Forth
create board 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,   \ board: 0=empty, 1=player X, 2=player O : player. ( player -- ) C" XO" 1+ + @ emit ; : spot ( n -- addr ) cells board + ; : clean-board ( -- ) 9 0 do 0 i spot ! loop ;   : show-board CR ." +---+---+---+ +---+---+---+" CR 3 0 do ." | " 3 0 do i j 3 ...
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#CoffeeScript
CoffeeScript
hanoi = (ndisks, start_peg=1, end_peg=3) -> if ndisks staging_peg = 1 + 2 + 3 - start_peg - end_peg hanoi(ndisks-1, start_peg, staging_peg) console.log "Move disk #{ndisks} from peg #{start_peg} to #{end_peg}" hanoi(ndisks-1, staging_peg, end_peg)   hanoi(4)
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Raku
Raku
.say for (0, { '0' ~ @_.join.trans( "01" => "10", :g) } ... *)[^8];
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#REXX
REXX
/*REXX pgm generates & displays the Thue─Morse sequence up to the Nth term (inclusive). */ parse arg N . /*obtain the optional argument from CL.*/ if N=='' | N=="," then N= 80 /*Not specified? Then use the default.*/ $= ...
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#Sidef
Sidef
func tokenize(string, sep, esc) { var fields = string.split( Regex(esc.escape + '.(*SKIP)(*FAIL)|' + sep.escape, 's'), -1 ) fields.map{.gsub(Regex(esc.escape + '(.)'), {|s1| s1 }) } }   tokenize("one^|uno||three^^^^|four^^^|^cuatro|", '|', '^').each { |str| say str.dump }
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 ...
#Object_Pascal
Object Pascal
  program topologicalsortrosetta;   {* Topological sorter to parse e.g. dependencies. Written for FreePascal 2.4.x/2.5.1. Probably works in Delphi, but you'd have to change some units. *} {$IFDEF FPC} // FreePascal-specific setup {$mode objfpc} uses {$IFDEF UNIX} cwstring, {* widestring support for unix *} {$IFDEF Us...
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#Rust
Rust
use std::collections::VecDeque; use std::fmt::{Display, Formatter, Result};   fn main() { println!("Simple incrementer"); let rules_si = vec!( Rule::new("q0", '1', '1', Direction::Right, "q0"), Rule::new("q0", 'B', '1', Direction::Stay, "qf") ); let states_si = vec!("q0", "qf"); let ...
http://rosettacode.org/wiki/Totient_function
Totient function
The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the integers up to a given positiv...
#Scala
Scala
@tailrec def gcd(a: Int, b: Int): Int = if(b == 0) a else gcd(b, a%b) def totientLaz(num: Int): Int = LazyList.range(2, num).count(gcd(num, _) == 1) + 1
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#Kotlin
Kotlin
// version 1.1.2   import java.lang.Math.*   fun main(args: Array<String>) { val radians = Math.PI / 4.0 val degrees = 45.0 val conv = Math.PI / 180.0 val f = "%1.15f" var inverse: Double   println(" Radians Degrees") println("Angle  : ${f.format(radians)}\t ...
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#VBScript
VBScript
  start_time = Now   lt = 0 rt = 0   For h = 1 To 1000000 If IsLeftTruncatable(h) And h > lt Then lt = h End If If IsRightTruncatable(h) And h > rt Then rt = h End If Next   end_time = now   WScript.StdOut.WriteLine "Largest LTP from 1..1000000: " & lt WScript.StdOut.WriteLine "Largest RTP from 1..1000000: " & ...
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 / ...
#FunL
FunL
data Tree = Empty | Node( value, left, right )   def preorder( Empty ) = [] preorder( Node(v, l, r) ) = [v] + preorder( l ) + preorder( r )   inorder( Empty ) = [] inorder( Node(v, l, r) ) = inorder( l ) + [v] + inorder( r )   postorder( Empty ) = [] postorder( Node(v, l, ...
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Forth
Forth
: split ( str len separator len -- tokens count ) here >r 2swap begin 2dup 2, \ save this token ( addr len ) 2over search \ find next separator while dup negate here 2 cells - +! \ adjust last token length 2over nip /string \ start next search past separator r...
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Fortran
Fortran
PROGRAM Example   CHARACTER(23) :: str = "Hello,How,Are,You,Today" CHARACTER(5) :: word(5) INTEGER :: pos1 = 1, pos2, n = 0, i   DO pos2 = INDEX(str(pos1:), ",") IF (pos2 == 0) THEN n = n + 1 word(n) = str(pos1:) EXIT END IF n = n + 1 word(n) = str(pos1:pos1+pos2-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 ...
#Janet
Janet
(defmacro time "Print the time it takes to evaluate body to stderr.\n Evaluates to body." [body] (with-syms [$start $val] ~(let [,$start (os/clock) ,$val ,body] (eprint (- (os/clock) ,$start)) ,$val)))   (time (os/sleep 0.5))
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 ...
#Java
Java
import java.lang.management.ManagementFactory; import java.lang.management.ThreadMXBean;   public class TimeIt { public static void main(String[] args) { final ThreadMXBean threadMX = ManagementFactory.getThreadMXBean(); assert threadMX.isCurrentThreadCpuTimeSupported(); threadMX.setThreadCpuTimeEnabled(true);  ...
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...
#Haskell
Haskell
import Data.List (sortBy, groupBy)   import Text.Printf (printf)   import Data.Ord (comparing)   import Data.Function (on)   type ID = Int   type DEP = String   type NAME = String   type SALARY = Double   data Employee = Employee { nr :: ID , dep :: DEP , name :: NAME , sal :: SALARY }   employees :: [Employe...
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#Fortran
Fortran
  ! This is a fortran95 implementation of the game of tic-tac-toe. ! - Objective was to use less than 100 lines. ! - No attention has been devoted to efficiency. ! - Indentation by findent: https://sourceforge.net/projects/findent/ ! - This is free software, use as you like at own risk. ! - Compile: gfortran -o tictact...
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Common_Lisp
Common Lisp
(defun move (n from to via) (cond ((= n 1) (format t "Move from ~A to ~A.~%" from to)) (t (move (- n 1) from via to) (format t "Move from ~A to ~A.~%" from to) (move (- n 1) via to from))))
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Ring
Ring
  tm = "0" see tm for n = 1 to 6 tm = thue_morse(tm) see tm next   func thue_morse(previous) tm = "" for i = 1 to len(previous) if (substr(previous, i, 1) = "1") tm = tm + "0" else tm = tm + "1" ok next see nl return (previous + tm)  
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Ruby
Ruby
puts s = "0" 6.times{puts s << s.tr("01","10")}
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Rust
Rust
const ITERATIONS: usize = 8;   fn neg(sequence: &String) -> String { sequence.chars() .map(|ch| { (1 - ch.to_digit(2).unwrap()).to_string() }) .collect::<String>() }   fn main() { let mut sequence: String = String::from("0"); for i in 0..ITERATIONS { println!("{}:...
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#Simula
Simula
  SIMSET BEGIN   LINK CLASS ITEM(TXT); TEXT TXT;;   REF(HEAD) PROCEDURE SPLIT(TXT, SEP, ESC); TEXT TXT; CHARACTER SEP, ESC; BEGIN REF(HEAD) PARTS; CHARACTER CH; TEXT PART;   PART :- BLANKS(TXT.LENGTH); PARTS :- NEW HEAD; TXT.SETPOS(1); WHILE TXT.MORE D...
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#SNOBOL4
SNOBOL4
  * Program: tokenize_with_escape.sbl * To run: sbl tokenize_with_escape.sbl * Description: Tokenize a string with escaping * Comment: Tested using the Spitbol for Linux version of SNOBOL4   lf = substr(&alphabet,11,1) ;* New line or line feed     * Function tokenize will break parts out of a string, which are * separ...
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 ...
#OCaml
OCaml
let dep_libs = [ ("des_system_lib", ["std"; "synopsys"; "std_cell_lib"; "des_system_lib"; "dw02"; "dw01"; "ramlib"; "ieee"]); ("dw01", (*"dw04"::*)["ieee"; "dw01"; "dware"; "gtech"]); ("dw02", ["ieee"; "dw02"; "dware"]); ("dw03", ["std"; "synopsys"; "dware"; "dw03"; "dw02"; "dw01";...
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#Scala
Scala
  package utm.scala   import scala.annotation.tailrec import scala.language.implicitConversions   /** * Implementation of Universal Turing Machine in Scala that can simulate an arbitrary * Turing machine on arbitrary input * * @author Abdulla Abdurakhmanov (https://github.com/abdolence/utms) */ class Universa...
http://rosettacode.org/wiki/Totient_function
Totient function
The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the integers up to a given positiv...
#Shale
Shale
#!/usr/local/bin/shale primes library init dup var { pl sieve type primes::() 100000 0 pl generate primes::() } = go dup var { i var c0 var c1 var c2 var c3 var p var " N Phi Is prime" println i 1 = { i 25 <= } { i pl isprime primes::() { "True" } { "False" } if i pl phi primes::() i "%2...
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#Lambdatalk
Lambdatalk
  {def deg2rad {lambda {:d} {* {/ {PI} 180} :d}}} -> deg2rad {def rad2deg {lambda {:r} {* {/ 180 {PI}} :r}}} -> rad2deg   {deg2rad 180} -> 3.141592653589793 = PI {rad2deg {PI}}° -> 180°   {sin {deg2rad 45}} -> 0.7071067811865475 = PI/4 {cos {deg2rad 45}} -> 0.7071067811865476 = PI/4 {tan {deg2rad 45}} -> 0.999999999...
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#Wren
Wren
import "/fmt" for Fmt import "/math" for Int   var limit = 999999 var c = Int.primeSieve(limit, false) var leftFound = false var rightFound = false System.print("Largest truncatable primes less than a million:") var i = limit while (i > 2) { if (!c[i]) { if (!rightFound) { var p = (i/10).floor ...
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 / ...
#F.C5.8Drmul.C3.A6
Fōrmulæ
  maxnodes%=100 ! set a limit to size of tree content%=0 ! index of content field left%=1 ! index of left tree right%=2 ! index of right tree DIM tree%(maxnodes%,3) ! create space for tree ' OPENW 1 CLEARW 1 ' @create_tree PRINT "Preorder: "; @preorder_traversal(1) PRINT "" PRINT "Inorder: "; @inorder_traversal(1)...
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Frink
Frink
  println[join[".", split[",", "Hello,How,Are,You,Today"]]]  
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Gambas
Gambas
Public Sub Main() Dim sString As String[] = Split("Hello,How,Are,You,Today")   Print sString.Join(".")   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 ...
#JavaScript
JavaScript
  function test() { let n = 0 for(let i = 0; i < 1000000; i++){ n += i } }   let start = new Date().valueOf() test() let end = new Date().valueOf()   console.log('test() took ' + ((end - start) / 1000) + ' seconds') // test() took 0.001 seconds  
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#Julia
Julia
# v0.6.0   function countto(n::Integer) i = zero(n) println("Counting...") while i < n i += 1 end println("Done!") end   @time countto(10 ^ 5) @time countto(10 ^ 10)
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...
#HicEst
HicEst
CHARACTER source="Test.txt", outP='Top_rank.txt', fmt='A20,A8,i6,2x,A10' CHARACTER name*20, employee_ID*10, department*10, temp*10 REAL :: idx(1), N_top_salaries=3   ! Open the source with 4 "," separated columns, skip line 1: OPEN(FIle=source, Format='SL=1;4,;', LENgth=L) ALLOCATE(idx, L)   ! Sort salary column 3 de...
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#FreeBASIC
FreeBASIC
    'About 400 lines of code, but it is a graphical (GUI ish) i.e. mouse driven. 'I have made provision for the player to beat the computer now and then.     Type box As long x,y As long wide,high,index Dim As ulong colour As String caption Declare Sub show Declare Sub NewCapti...
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#D
D
import std.stdio;   void hanoi(in int n, in char from, in char to, in char via) { if (n > 0) { hanoi(n - 1, from, via, to); writefln("Move disk %d from %s to %s", n, from, to); hanoi(n - 1, via, to, from); } }   void main() { hanoi(3, 'L', 'M', 'R'); }
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Scala
Scala
def thueMorse(n: Int): String = { val (sb0, sb1) = (new StringBuilder("0"), new StringBuilder("1")) (0 until n).foreach { _ => val tmp = sb0.toString() sb0.append(sb1) sb1.append(tmp) } sb0.toString() }   (0 to 6).foreach(i => println(s"$i : ${thueMorse(i)}"))
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Sidef
Sidef
func recmap(repeat, seed, transform, callback) { func (repeat, seed) { callback(seed) repeat > 0 && __FUNC__(repeat-1, transform(seed)) }(repeat, seed) }   recmap(6, "0", {|s| s + s.tr('01', '10') }, { .say })
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#Swift
Swift
extension String { func tokenize(separator: Character, escape: Character) -> [String] { var token = "" var tokens = [String]() var chars = makeIterator()   while let char = chars.next() { switch char { case separator: tokens.append(token) token = "" case escape: ...