task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were separated by the separators, become the elements of the output list. Empty fields should be preserved, even at the start and end. Rules for escaping: "Escaped" means preceded by an occurrence of the escape character that is not already escaped itself. When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special). Each occurrence of the escape character that was used to escape something, should not become part of the output. Test case Demonstrate that your function satisfies the following test-case: Input Output string: one^|uno||three^^^^|four^^^|^cuatro| separator character: | escape character: ^ one|uno three^^ four^|cuatro (Print the output list in any format you like, as long as it is it easy to see what the fields are.) 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
#Tcl
Tcl
oo::class create tokens { constructor {s} { puts [coroutine Next my Iter $s] oo::objdefine [self] forward next Next } method Iter {s} { yield [info coroutine] for {set i 0} {$i < [string length $s]} {incr i} { yield [string index $s $i] } return -code break } }   proc tokenize {s {sep |} {escape ^}} { set part "" set parts "" set iter [tokens new $s] while {1} { set c [$iter next] if {$c eq $escape} { append part [$iter next] } elseif {$c eq $sep} { lappend parts $part set part "" } else { append part $c } } lappend parts $part return $parts }   puts [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 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]
#OxygenBasic
OxygenBasic
  'TOPOLOGICAL SORT   uses parseutil 'getword() lenw uses console   string dat=" LIBRARY LIBRARY DEPENDENCIES ======= ==================== des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee dw01 ieee dw01 dware gtech dw02 ieee dw02 dware dw03 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 " gosub Dims gosub CaptureData gosub GetSystemLibs gosub RemoveSelfReference gosub OrderByDependency gosub DisplayResults end   /*RESULTS: libraries in dependency order ----------------------------- std ieee dware gtech ramlib std_cell_lib synopsys dw01 dw02 des_system_lib dw03 dw04 dw05 dw06 dw07 <<   remainder: ---------- << */       Dims: ===== 'VARIABLES int p 'width of first column int h 'length of each line int i 'iterator / counter int j 'main iterator int b 'table char offset int e 'end of each line int bd 'each offset of dependencises line int le 'length of each lib name int lend 'size of table int k 'character indexer int m 'iterator int n 'iterator int cw 'presence flag int lw 'length of keyword int a 'iinstr result int dc 'new lib list indexer / counter string wr 'keyword string wn 'keyword '--arrays-- string datl[64] 'list of lib names string datd[64] 'lists of lib dependencies string datn[64] 'new list in dependency ordert ret     CaptureData: ============ dat=lcase dat 'GET HEADING POSITION p=instr dat,"library depend" p-=3 'crlf -1 'REMOVE HEADING h=instr 3,dat,cr h+=2 h=instr h,dat,cr 'to remove underlines 'print h cr h+=2 dat=mid dat,h 'print dat "<" cr b=1 'PREPARE DATA lend=len dat do i++ datl[i]=rtrim(mid(dat,b,p)) le=len datl[i] e=instr b+le,dat,cr bd=b+p datd[i]=" "+mid(dat,bd,e-bd)+" " 'print datl[i] "," datd[i] cr b=e+2 if b>lend-2 exit do endif loop ret   GetSystemLibs: ============== 'SCAN DEPENDENCIES 'GET SYSTEM LIBS NOT LISTED for j=1 to i k=1 do wr=getword datd[j],k if not wr exit do endif cw=0 for m=1 to i if wr=datl[m] 'on lib list cw=m endif next if cw=0 'lib not on library list 'add wr to new lib list dc++ : datn[dc]=wr 'remove lib names from dependency lists gosub BlankOutNames endif loop next 'j group of dependencies ret     RemoveSelfReference: ==================== 'REMOVE SELF REFERENCE + NO DEPENDENCIES for j=1 to i wr=" "+datl[j]+" " lw=len(wr) a=instr(datd[j],wr) if a mid(datd[j],a,space(lw)) 'blank out self endif gosub RemoveLibFromLists next ret ' OrderByDependency: ================== ' for j=1 to i if datl[j] gosub RemoveLibFromLists if cw then j=0 'repeat cycle endif next ret ' DisplayResults: =============== print cr cr print "libraries in dependency order" cr print "-----------------------------" cr for j=1 to dc print datn[j] cr next print "<<" cr cr print "remainder:" cr print "----------" cr for j=1 to i if datl[j] print datl[j] " , " datd[j] cr endif next print "<<" cr   pause end   RemoveLibFromLists: =================== cw=0 k=1 : wr=getword datd[j],k if lenw=0 dc++ : datn[dc]=datl[j] 'add to new lib list datl[j]="" : datd[j]="" 'eliminate frecord rom further checks gosub BlankOutNames 'eliminate all lib references from table cw=1 'flag alteration endif ret   BlankOutNames: ============== wn=" "+datn[dc]+" " 'add word boundaries lw=len wn for n=1 to i if datd[n] a=instr(datd[n],wn) if a mid datd[n],a,space(lw) 'blank out endif endif next ret  
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 a machine capable of taking the definition of any other Turing machine and executing it. Of course, you will not have an infinite tape, but you should emulate this as much as is possible. The three permissible actions on the tape are "left", "right" and "stay". To test your universal Turing machine (and prove your programming language is Turing complete!), you should execute the following two Turing machines based on the following definitions. Simple incrementer States: q0, qf Initial state: q0 Terminating states: qf Permissible symbols: B, 1 Blank symbol: B Rules: (q0, 1, 1, right, q0) (q0, B, 1, stay, qf) The input for this machine should be a tape of 1 1 1 Three-state busy beaver States: a, b, c, halt Initial state: a Terminating states: halt Permissible symbols: 0, 1 Blank symbol: 0 Rules: (a, 0, 1, right, b) (a, 1, 1, left, c) (b, 0, 1, left, a) (b, 1, 1, right, b) (c, 0, 1, left, b) (c, 1, 1, stay, halt) The input for this machine should be an empty tape. Bonus: 5-state, 2-symbol probable Busy Beaver machine from Wikipedia States: A, B, C, D, E, H Initial state: A Terminating states: H Permissible symbols: 0, 1 Blank symbol: 0 Rules: (A, 0, 1, right, B) (A, 1, 1, left, C) (B, 0, 1, right, C) (B, 1, 1, right, B) (C, 0, 1, right, D) (C, 1, 0, left, E) (D, 0, 1, left, A) (D, 1, 1, left, D) (E, 0, 1, stay, H) (E, 1, 0, left, A) The input for this machine should be an empty tape. This machine runs for more than 47 millions steps.
#Scheme
Scheme
;----------------------------------------------------------------------------------------------   ; The tape is a doubly-linked list of "cells". Each cell is a pair in which the cdr points ; to the cell on its right, and the car is a vector containing: 0: the value of the cell; ; 1: pointer to the cell on this cell's left; 2: #t if the cell has never been written.   ; Make a new cell with the given contents, but linked to no other cell(s). ; (This is the only place that a cell can be marked as un-written.) (define make-cell (lambda (val . opt-unwrit) (list (vector val '() (if (pair? opt-unwrit) (car opt-unwrit) #f)))))   ; Return the un-written flag of the cell. (define cell-unwrit? (lambda (cell) (vector-ref (car cell) 2)))   ; Return the value of the cell. (define cell-get (lambda (cell) (vector-ref (car cell) 0)))   ; Store the value of the cell. ; Clears the un-written flag of the cell. (define cell-set! (lambda (cell val) (vector-set! (car cell) 0 val) (vector-set! (car cell) 2 #f)))   ; Return the cell to the right of the given cell on the tape. ; Returns () if there is no cell to the right. (define cell-right (lambda (cell) (cdr cell)))   ; Return the cell to the left of the given cell on the tape. ; Returns () if there is no cell to the left. (define cell-left (lambda (cell) (vector-ref (car cell) 1)))   ; Return the cell to the right of the given cell on the tape. ; Extends the tape with the give blank symbol if there is no cell to the right. ; Optionally, passes the given un-written flag to make-cell (if needed). (define cell-extend-right (lambda (cell blank . opt-unwrit) (if (null? (cdr cell)) (let ((new (if (pair? opt-unwrit) (make-cell blank (car opt-unwrit)) (make-cell blank)))) (vector-set! (car new) 1 cell) (set-cdr! cell new) new) (cell-right cell))))   ; Return the cell to the left of the given cell on the tape. ; Extends the tape with the give blank symbol if there is no cell to the left. ; Optionally, passes the given un-written flag to make-cell (if needed). (define cell-extend-left (lambda (cell blank . opt-unwrit) (if (null? (vector-ref (car cell) 1)) (let ((new (if (pair? opt-unwrit) (make-cell blank (car opt-unwrit)) (make-cell blank)))) (set-cdr! new cell) (vector-set! (car cell) 1 new) new) (cell-left cell))))   ; Make a new tape whose cells contain the values in the given list. ; Optionally, pad the tape per the given blank symbol, left-padding and right-padding amounts. (define make-tape (lambda (values . opt-pads) (unless (pair? values) (error 'make-tape "values argument is not a list" pads)) (let* ((tape (make-cell (car values))) (last (do ((values (cdr values) (cdr values)) (cell tape (cell-extend-right cell (car values)))) ((null? values) cell)))) (when (pair? opt-pads) (let ((blank (list-ref opt-pads 0)) (left (list-ref opt-pads 1)) (right (list-ref opt-pads 2))) (unless (and (integer? left) (integer? right)) (error 'make-tape "padding arguments must be integers" opt-pads)) (do ((count 0 (1+ count)) (cell last (cell-extend-right cell blank #t))) ((>= count right))) (do ((count 0 (1+ count)) (cell tape (cell-extend-left cell blank #t))) ((>= count left))))) tape)))   ; Make a deep copy of the given tape. ; Note: Only copies from the given cell forward. (define tape-copy (lambda (tape) (let ((copy (make-cell (cell-get tape)))) (do ((tape (cdr tape) (cdr tape)) (cell copy (cell-extend-right cell (cell-get tape)))) ((null? tape))) copy)))   ; Return the first cell on a tape. ; Optionally, leading blank symbols are not included (will return last cell of blank tape). (define tape-fst (lambda (cell . opt-blank) (let ((fst (do ((fst cell (cell-left fst))) ((null? (cell-left fst)) fst)))) (if (null? opt-blank) fst (do ((fst fst (cell-right fst))) ((or (null? (cell-right fst)) (not (eq? (car opt-blank) (cell-get fst)))) fst))))))   ; Return the last cell on a tape. ; Optionally, trailing blank symbols are not included (will return first cell of blank tape). (define tape-lst (lambda (cell . opt-blank) (let ((lst (do ((lst cell (cell-right lst))) ((null? (cell-right lst)) lst)))) (if (null? opt-blank) lst (do ((lst lst (cell-left lst))) ((or (null? (cell-left lst)) (not (eq? (car opt-blank) (cell-get lst)))) lst))))))   ; Return true if the given tape is empty. (I.e. contains nothing but blank symbols.) (define tape-empty? (lambda (cell blank) (let ((fst (tape-fst cell blank))) (and (null? (cell-right fst)) (eq? blank (cell-get fst))))))   ; Convert the contents of a tape to a string. ; Place a mark around the indicated cell (if any match). ; Prints the entire contents regardless of which cell is given. ; Optionally, leading and trailing instances of the given blank symbol are suppressed. ; The values of un-written cells are not shown, though space for them is included. (define tape->string (lambda (cell mark . opt-blank) (let ((strlst (list #\[)) (marked-prev #f) (fst (if (null? opt-blank) (tape-fst cell) (tape-fst cell (car opt-blank)))) (lst (if (null? opt-blank) (tape-lst cell) (tape-lst cell (car opt-blank))))) (do ((cell fst (cell-right cell))) ((eq? cell (cell-right lst))) (let* ((mark-now (eq? cell mark)) (fmtstr (cond (mark-now " {~a}") (marked-prev " ~a") (else " ~a"))) (value (if (and (not mark-now) (cell-unwrit? cell)) " " (cell-get cell)))) (set! strlst (append strlst (string->list (format fmtstr value)))) (set! marked-prev mark-now))) (list->string (append strlst (string->list (if marked-prev " ]" " ]")))))))   ;----------------------------------------------------------------------------------------------   ; A Turing Machine contains the 7-tuple that formally defines it, stored in an array to ; make access relatively fast. The transitions are stored in an association list keyed by ; the pair (q_i . s_j) for ease of lookup.   ; Make a new Turing Machine from the given arguments: ; Symbols list, blank symbol, input symbols list, states list, initial state, final (accepting) ; states list, and list of transitions. A transition is a 5-element list of: state (q_i), ; symbol read (s_i), symbol to write (s_ij), direction to move (d_ij), and next state (q_ij). (define make-turing (lambda (symbols blank inputs states initial finals . transitions) ; Raise error if any element in list lst is not in list set. (define all-list-in-set (lambda (set lst msg) (for-each (lambda (val) (unless (memq val set) (error 'make-turing msg val))) lst))) ; Raise error if the given transition is not correctly formed. (define transition-validate (lambda (tran) (when (or (not (list? tran)) (not (= 5 (length tran)))) (error 'make-turing "transition not a length-5 list" tran)) (let ((q_i (list-ref tran 0)) (s_j (list-ref tran 1)) (s_ij (list-ref tran 2)) (d_ij (list-ref tran 3)) (q_ij (list-ref tran 4))) (unless (memq q_i states) (error 'make-turing "q_i not in states" q_i)) (unless (memq s_j symbols) (error 'make-turing "s_j not in symbols" s_j)) (unless (memq s_ij symbols) (error 'make-turing "s_ij not in symbols" s_ij)) (unless (memq d_ij '(L R N)) (error 'make-turing "d_ij not in {L R N}" d_ij)) (unless (memq q_ij states) (error 'make-turing "q_ij not in states" q_ij))))) ; Convert the given transitions list into an alist of transitions keyed by (q_i . s_j). (define transitions-alist (lambda (trns) (cond ((null? trns) '()) (else (cons (cons (cons (caar trns) (cadar trns)) (list (cddar trns))) (transitions-alist (cdr trns))))))) ; Validate all the arguments. (unless (list? symbols) (error 'make-turing "symbols not a list" symbols)) (unless (memq blank symbols) (error 'make-turing "blank not in symbols" blank)) (all-list-in-set symbols inputs "inputs not all in symbols") (unless (list? states) (error 'make-turing "states not a list" states)) (unless (memq initial states) (error 'make-turing "initial not in states" initial)) (all-list-in-set states finals "finals not all in states") (for-each (lambda (tran) (transition-validate tran)) transitions) ; Construct and return the Turing Machine tuple vector. (let ((tuple (make-vector 7))) (vector-set! tuple 0 symbols) (vector-set! tuple 1 blank) (vector-set! tuple 2 inputs) (vector-set! tuple 3 states) (vector-set! tuple 4 initial) (vector-set! tuple 5 finals) (vector-set! tuple 6 (transitions-alist transitions)) tuple)))   ; Return the symbols of a Turing Machine. (define-syntax turing-symbols (syntax-rules () ((_ tm) (vector-ref tm 0))))   ; Return the blank symbol of a Turing Machine. (define-syntax turing-blank (syntax-rules () ((_ tm) (vector-ref tm 1))))   ; Return the input symbols of a Turing Machine. (define-syntax turing-inputs (syntax-rules () ((_ tm) (vector-ref tm 2))))   ; Return the states of a Turing Machine. (define-syntax turing-states (syntax-rules () ((_ tm) (vector-ref tm 3))))   ; Return the initial state of a Turing Machine. (define-syntax turing-initial (syntax-rules () ((_ tm) (vector-ref tm 4))))   ; Return the final states of a Turing Machine. (define-syntax turing-finals (syntax-rules () ((_ tm) (vector-ref tm 5))))   ; Return the transitions of a Turing Machine. (define-syntax turing-transitions (syntax-rules () ((_ tm) (vector-ref tm 6))))   ; Return the q_i (current state) of alist element transition. (define-syntax tran-q_i (syntax-rules () ((_ atran) (car (car atran)))))   ; Return the s_j (symbol read from the tape) of alist element transition. (define-syntax tran-s_j (syntax-rules () ((_ atran) (cdr (car atran)))))   ; Return the s_ij (symbol written) of alist element transition. (define-syntax tran-s_ij (syntax-rules () ((_ atran) (car (cadr atran)))))   ; Return the d_ij (direction of move) of alist element transition. (define-syntax tran-d_ij (syntax-rules () ((_ atran) (cadr (cadr atran)))))   ; Return the q_ij (state transition) of alist element transition. (define-syntax tran-q_ij (syntax-rules () ((_ atran) (caddr (cadr atran)))))   ; Lookup the transition matching the given state and symbol in the given Turing Machine. (define atrns-lookup (lambda (state symbol tm) (assoc (cons state symbol) (turing-transitions tm))))   ; Convert the given Turing Machine transition to a string. (define tran->string (lambda (atran) (format "(~a ~a ~a ~a ~a)" (tran-q_i atran) (tran-s_j atran) (tran-s_ij atran) (tran-d_ij atran) (tran-q_ij atran))))   ; Convert the given Turing Machine definition to a string. ; Options (zero or more) are, in order: component prefix string (default ""); ; component suffix string (default ""); component separator string (default newline). (define turing->string (lambda (tm . opts) (let ((prestr (if (> (length opts) 0) (list-ref opts 0) "")) (sufstr (if (> (length opts) 1) (list-ref opts 1) "")) (sepstr (if (> (length opts) 2) (list-ref opts 2) (make-string 1 #\newline))) (strlst '())) (set! strlst (append strlst (string->list (format "~a~a~a~a" prestr (turing-symbols tm) sufstr sepstr)))) (set! strlst (append strlst (string->list (format "~a~a~a~a" prestr (turing-blank tm) sufstr sepstr)))) (set! strlst (append strlst (string->list (format "~a~a~a~a" prestr (turing-inputs tm) sufstr sepstr)))) (set! strlst (append strlst (string->list (format "~a~a~a~a" prestr (turing-states tm) sufstr sepstr)))) (set! strlst (append strlst (string->list (format "~a~a~a~a" prestr (turing-initial tm) sufstr sepstr)))) (set! strlst (append strlst (string->list (format "~a~a~a~a" prestr (turing-finals tm) sufstr (if (> (length (turing-transitions tm)) 0) sepstr ""))))) (do ((index 0 (1+ index))) ((>= index (length (turing-transitions tm)))) (set! strlst (append strlst (string->list (format "~a~a~a~a" prestr (tran->string (list-ref (turing-transitions tm) index)) sufstr (if (< index (1- (length (turing-transitions tm)))) sepstr "")))))) (list->string strlst))))   ;----------------------------------------------------------------------------------------------   ; Run the given Turing Machine on the given input tape. ; If specified, display log of progress. Optionally, abort after given number of iterations. ; Returns the count of iterations, the accepting state (if one; else void), and the output ; tape as multiple values. (define turing-run (lambda (tm cell show-log? . opt-abort) ; Validate contents of input tape. (Leading/trailing blanks allowed; internals are not.) (unless (tape-empty? cell (turing-blank tm)) (let ((fst (tape-fst cell (turing-blank tm))) (lst (tape-lst cell (turing-blank tm)))) (if (eq? fst lst) (unless (memq (cell-get fst) (turing-symbols tm)) (error 'turing-run "input tape has disallowed content" (cell-get fst))) (do ((cell fst (cell-right cell))) ((eq? cell (cell-right lst))) (unless (memq (cell-get cell) (turing-inputs tm)) (error 'turing-run "input tape has disallowed content" (cell-get cell))))))) ; Initialize state and head. (let ((state (turing-initial tm)) (head cell) (atran #f) (abort (and (pair? opt-abort) (integer? (car opt-abort)) (> (car opt-abort) 0) (car opt-abort)))) ; Loop until no transition matches state/symbol or reached a final state. (do ((count 0 (1+ count)) (atran (atrns-lookup state (cell-get head) tm) (atrns-lookup state (cell-get head) tm))) ((or (not atran) (memq state (turing-finals tm)) (and abort (>= count abort))) ; Display final progress (optional). (when show-log? (let* ((string (format "~a" state)) (strlen (string-length string)) (padlen (max 1 (- 25 strlen))) (strpad (make-string padlen #\ ))) (printf "~a~a~a~%" string strpad (tape->string cell head)))) ; Return resultant count, accepting state (or void), and tape. (values count (if (memq state (turing-finals tm)) state (void)) head)) ; Display progress (optional). (when show-log? (let* ((string (format "~a ~a -> ~a ~a ~a" state (cell-get head) (tran-s_ij atran) (tran-d_ij atran) (tran-q_ij atran))) (strlen (string-length string)) (padlen (max 1 (- 25 strlen))) (strpad (make-string padlen #\ ))) (printf "~a~a~a~%" string strpad (tape->string cell head)))) ; Iterate. (cell-set! head (tran-s_ij atran)) (set! state (tran-q_ij atran)) (set! head (case (tran-d_ij atran) ((L) (cell-extend-left head (turing-blank tm))) ((R) (cell-extend-right head (turing-blank tm))) ((N) head)))))))   ;----------------------------------------------------------------------------------------------
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 positive integer   n   that are relatively prime to   n   counts the integers   k   in the range   1 ≤ k ≤ n   for which the greatest common divisor   gcd(n,k)   is equal to   1   counts numbers   ≤ n   and   prime to   n If the totient number   (for N)   is one less than   N,   then   N   is prime. Task Create a   totient   function and:   Find and display   (1 per line)   for the 1st   25   integers:   the integer   (the index)   the totient number for that integer   indicate if that integer is prime   Find and display the   count   of the primes up to          100   Find and display the   count   of the primes up to       1,000   Find and display the   count   of the primes up to     10,000   Find and display the   count   of the primes up to   100,000     (optional) Show all output here. Related task   Perfect totient numbers Also see   Wikipedia: Euler's totient function.   MathWorld: totient function.   OEIS: Euler totient function phi(n).
#Sidef
Sidef
func 𝜑(n) { n.factor_exp.prod {|p| (p[0]-1) * p[0]**(p[1]-1) } }
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that 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.
#Liberty_BASIC
Liberty BASIC
pi = ACS(-1) radians = pi / 4.0 rtod = 180 / pi degrees = radians * rtod dtor = pi / 180   'LB works in radians, so degrees require conversion print "Sin: ";SIN(radians);" "; SIN(degrees*dtor) print "Cos: ";COS(radians);" "; COS(degrees*dtor) print "Tan: ";TAN(radians);" ";TAN(degrees*dtor) print "- Inverse functions:" print "Asn: ";ASN(SIN(radians));" Rad, "; ASN(SIN(degrees*dtor))*rtod;" Deg" print "Acs: ";ACS(COS(radians));" Rad, "; ACS(COS(degrees*dtor))*rtod;" Deg" print "Atn: ";ATN(TAN(radians));" Rad, "; ATN(TAN(degrees*dtor))*rtod;" Deg"
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, 739, 73, and 7 formed by removing digits from its right are also prime. No zeroes are allowed in truncatable primes. Task The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied). Related tasks Find largest left truncatable prime in a given base Sieve of Eratosthenes See also Truncatable Prime from MathWorld.]
#XPL0
XPL0
code CrLf=9, IntOut=11;   func Prime(P); \Return true if P is a prime number int P; \(1 is not prime, but 2 is, etc.) int I; [if P<=1 then return false; \negative numbers are not prime for I:= 2 to sqrt(P) do if rem(P/I) = 0 then return false; return true; ];   func RightTrunc(N); \Return largest right-truncatable prime < one million int N; int M; [for N:= 1_000_000-1 downto 2 do [M:= N; loop [if not Prime(M) then quit; M:= M/10; if rem(0) = 0 then quit; \no zeros allowed if M=0 then return N; ]; ]; ];   func LeftTrunc(N); \Return largest left-truncatable prime < one million int N; int M, P; [for N:= 1_000_000-1 downto 2 do [M:= N; P:=100_000; loop [if not Prime(M) then quit; M:= rem(M/P); P:= P/10; if M<P then quit; \no zeros allowed if M=0 then return N; ]; ]; ];   [IntOut(0, LeftTrunc); CrLf(0); IntOut(0, RightTrunc); CrLf(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, 739, 73, and 7 formed by removing digits from its right are also prime. No zeroes are allowed in truncatable primes. Task The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied). Related tasks Find largest left truncatable prime in a given base Sieve of Eratosthenes See also Truncatable Prime from MathWorld.]
#zkl
zkl
const million=0d1_000_000;   var pTable=Data(million+1,Int).fill(0); // actually bytes, all zero primes:=Utils.Generator(Import("sieve").postponed_sieve); while((p:=primes.next())<million){ pTable[p]=1; }   fcn rightTrunc(n){ while(n){ if(not pTable[n]) return(False); n/=10; } True } fcn leftTrunc(n){ // 999,907 is not allowed ns:=n.toString(); if (ns.holds("0")) return(False); while(ns){ if(not pTable[ns]) return(False); ns=ns[1,*]; } True }
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.
#GFA_Basic
GFA Basic
  maxnodes%=100 ! set a limit to size of tree content%=0 ! index of content field left%=1 ! index of left tree right%=2 ! index of right tree DIM tree%(maxnodes%,3) ! create space for tree ' OPENW 1 CLEARW 1 ' @create_tree PRINT "Preorder: "; @preorder_traversal(1) PRINT "" PRINT "Inorder: "; @inorder_traversal(1) PRINT "" PRINT "Postorder: "; @postorder_traversal(1) PRINT "" PRINT "Levelorder: "; @levelorder_traversal(1) PRINT "" ' ~INP(2) CLOSEW 1 ' ' Define the example tree ' PROCEDURE create_tree tree%(1,content%)=1 tree%(1,left%)=2 tree%(1,right%)=3 tree%(2,content%)=2 tree%(2,left%)=4 tree%(2,right%)=5 tree%(3,content%)=3 tree%(3,left%)=6 tree%(3,right%)=0 ! 0 is used for no subtree tree%(4,content%)=4 tree%(4,left%)=7 tree%(4,right%)=0 tree%(5,content%)=5 tree%(5,left%)=0 tree%(5,right%)=0 tree%(6,content%)=6 tree%(6,left%)=8 tree%(6,right%)=9 tree%(7,content%)=7 tree%(7,left%)=0 tree%(7,right%)=0 tree%(8,content%)=8 tree%(8,left%)=0 tree%(8,right%)=0 tree%(9,content%)=9 tree%(9,left%)=0 tree%(9,right%)=0 RETURN ' ' Preorder traversal from given node ' PROCEDURE preorder_traversal(node%) IF node%<>0 ! 0 means there is no node PRINT tree%(node%,content%); preorder_traversal(tree%(node%,left%)) preorder_traversal(tree%(node%,right%)) ENDIF RETURN ' ' Postorder traversal from given node ' PROCEDURE postorder_traversal(node%) IF node%<>0 ! 0 means there is no node postorder_traversal(tree%(node%,left%)) postorder_traversal(tree%(node%,right%)) PRINT tree%(node%,content%); ENDIF RETURN ' ' Inorder traversal from given node ' PROCEDURE inorder_traversal(node%) IF node%<>0 ! 0 means there is no node inorder_traversal(tree%(node%,left%)) PRINT tree%(node%,content%); inorder_traversal(tree%(node%,right%)) ENDIF RETURN ' ' Level order traversal from given node ' PROCEDURE levelorder_traversal(node%) LOCAL nodes%,first_free%,current% ' ' Set up initial queue of nodes ' DIM nodes%(maxnodes%) ! some working space to store queue of nodes current%=1 nodes%(current%)=node% first_free%=current%+1 ' WHILE nodes%(current%)<>0 ' add the children of current node onto queue IF tree%(nodes%(current%),left%)<>0 nodes%(first_free%)=tree%(nodes%(current%),left%) first_free%=first_free%+1 ENDIF IF tree%(nodes%(current%),right%)<>0 nodes%(first_free%)=tree%(nodes%(current%),right%) first_free%=first_free%+1 ENDIF ' print the current node content PRINT tree%(nodes%(current%),content%); ' advance to next node current%=current%+1 WEND RETURN  
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
#GAP
GAP
SplitString("Hello,How,Are,You,Today", ","); # [ "Hello", "How", "Are", "You", "Today" ]   JoinStringsWithSeparator(last, "."); # "Hello.How.Are.You.Today"
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: 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
#Genie
Genie
[indent=4]   init str:string = "Hello,How,Are,You,Today" words:array of string[] = str.split(",") joined:string = string.joinv(".", words) print joined
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Kotlin
Kotlin
// version 1.1.2 // need to enable runtime assertions with JVM -ea option   import java.lang.management.ManagementFactory import java.lang.management.ThreadMXBean   fun countTo(x: Int) { println("Counting..."); (1..x).forEach {} println("Done!") }   fun main(args: Array<String>) { val counts = intArrayOf(100_000_000, 1_000_000_000) val threadMX = ManagementFactory.getThreadMXBean() assert(threadMX.isCurrentThreadCpuTimeSupported) threadMX.isThreadCpuTimeEnabled = true for (count in counts) { val start = threadMX.currentThreadCpuTime countTo(count) val end = threadMX.currentThreadCpuTime println("Counting to $count takes ${(end-start)/1000000}ms") } }
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.
#Lasso
Lasso
local(start = micros) loop(100000) => { 'nothing is outout because no autocollect' } 'time for 100,000 loop repititions: '+(micros - #start)+' microseconds'
http://rosettacode.org/wiki/Top_rank_per_group
Top rank per group
Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett,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
#Icon_and_Unicon
Icon and Unicon
record Employee(name,id,salary,dept)   procedure getEmployees () employees := [ Employee("Tyler Bennett","E10297",32000,"D101"), Employee("John Rappl","E21437",47000,"D050"), Employee("George Woltman","E00127",53500,"D101"), Employee("Adam Smith","E63535",18000,"D202"), Employee("Claire Buckman","E39876",27800,"D202"), Employee("David McClellan","E04242",41500,"D101"), Employee("Rich Holcomb","E01234",49500,"D202"), Employee("Nathan Adams","E41298",21900,"D050"), Employee("Richard Potter","E43128",15900,"D101"), Employee("David Motsinger","E27002",19250,"D202"), Employee("Tim Sampair","E03033",27000,"D101"), Employee("Kim Arlich","E10001",57000,"D190"), Employee("Timothy Grove","E16398",29900,"D190") ] return employees end   procedure show_employee (employee) every writes (!employee || " ") write () end   procedure main (args) N := integer(args[1]) # N set from command line employees := getEmployees () groups := set() every employee := !employees do insert(groups, employee.dept)   every group := !groups do { write ("== Top " || N || " in group " || group) employeesInGroup := [] every employee := !employees do { if employee.dept == group then put(employeesInGroup, employee) } # sort by third field and reverse, so highest salary comes first employeesInGroup := reverse(sortf(employeesInGroup, 3)) # show the first N records, up to the end of the list every show_employee (!employeesInGroup[1:(1+min(N,*employeesInGroup))]) } 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.
#Go
Go
package main   import ( "bufio" "fmt" "math/rand" "os" "strings" )   var b []byte   func printBoard() { fmt.Printf("%s\n%s\n%s\n", b[0:3], b[3:6], b[6:9]) }   var pScore, cScore int var pMark, cMark byte = 'X', 'O' var in = bufio.NewReader(os.Stdin)   func main() { b = make([]byte, 9) fmt.Println("Play by entering a digit.") for { // start of game for i := range b { b[i] = '1' + byte(i) } computerStart := cMark == 'X' if computerStart { fmt.Println("I go first, playing X's") } else { fmt.Println("You go first, playing X's") } TakeTurns: for { if !computerStart { if !playerTurn() { return } if gameOver() { break TakeTurns }   } computerStart = false computerTurn() if gameOver() { break TakeTurns } } fmt.Println("Score: you", pScore, "me", cScore) fmt.Println("\nLet's play again.") } }   func playerTurn() bool { var pm string var err error for i := 0; i < 3; i++ { // retry loop printBoard() fmt.Printf("%c's move? ", pMark) if pm, err = in.ReadString('\n'); err != nil { fmt.Println(err) return false } pm = strings.TrimSpace(pm) if pm >= "1" && pm <= "9" && b[pm[0]-'1'] == pm[0] { x := pm[0] - '1' b[x] = pMark return true } } fmt.Println("You're not playing right.") return false }   var choices = make([]int, 9)   func computerTurn() { printBoard() var x int defer func() { fmt.Println("My move:", x+1) b[x] = cMark }() // look for two in a row block := -1 for _, l := range lines { var mine, yours int x = -1 for _, sq := range l { switch b[sq] { case cMark: mine++ case pMark: yours++ default: x = sq } } if mine == 2 && x >= 0 { return // strategy 1: make winning move } if yours == 2 && x >= 0 { block = x } } if block >= 0 { x = block // strategy 2: make blocking move return } // default strategy: random move choices = choices[:0] for i, sq := range b { if sq == '1'+byte(i) { choices = append(choices, i) } } x = choices[rand.Intn(len(choices))] }   func gameOver() bool { // check for win for _, l := range lines { if b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]] { printBoard() if b[l[0]] == cMark { fmt.Println("I win!") cScore++ pMark, cMark = 'X', 'O' } else { fmt.Println("You win!") pScore++ pMark, cMark = 'O', 'X' } return true } } // check for empty squares for i, sq := range b { if sq == '1'+byte(i) { return false } } fmt.Println("Cat game.") pMark, cMark = cMark, pMark return true }   var lines = [][]int{ {0, 1, 2}, // rows {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, // columns {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, // diagonals {2, 4, 6}, }
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Dart
Dart
main() { moveit(from,to) { print("move ${from} ---> ${to}"); }   hanoi(height,toPole,fromPole,usePole) { if (height>0) { hanoi(height-1,usePole,fromPole,toPole); moveit(fromPole,toPole); hanoi(height-1,toPole,usePole,fromPole); } }   hanoi(3,3,1,2); }
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#SQL
SQL
WITH recursive a(a) AS (SELECT '0' UNION ALL SELECT REPLACE(REPLACE(hex(a),'30','01'),'31','10') FROM a) SELECT * FROM a;
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Tcl
Tcl
proc tm_expand {s} {string map {0 01 1 10} $s} # this could also be written as: # interp alias {} tm_expand {} string map {0 01 1 10}   proc tm {k} { set s 0 while {[incr k -1] >= 0} { set s [tm_expand $s] } return $s }
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#uBasic.2F4tH
uBasic/4tH
For x = 0 to 6 ' sequence loop Print Using "_#";x;": "; ' print sequence For y = 0 To (2^x)-1 ' element loop Print AND(FUNC(_Parity(y)),1); ' print element Next ' next element Print ' terminate elements line Next ' next sequence   End   _Parity Param (1) ' parity function Local (1) ' number of bits set b@ = 0 ' no bits set yet Do While a@ # 0  ' until all bits are counted If AND (a@, 1) Then b@ = b@ + 1 ' bit set? increment count a@ = SHL(a@, -1) ' shift the number Loop Return (b@) ' return number of bits set
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 separated by the separators, become the elements of the output list. Empty fields should be preserved, even at the start and end. Rules for escaping: "Escaped" means preceded by an occurrence of the escape character that is not already escaped itself. When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special). Each occurrence of the escape character that was used to escape something, should not become part of the output. Test case Demonstrate that your function satisfies the following test-case: Input Output string: one^|uno||three^^^^|four^^^|^cuatro| separator character: | escape character: ^ one|uno three^^ four^|cuatro (Print the output list in any format you like, as long as it is it easy to see what the fields are.) 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
#TMG
TMG
prog: char(sep) * char(esc) * str: smark token: forw/outp ( [ch==esc?] char(ch) any(!<<>>) token | [ch==sep?] char(ch) outp str | any(!<<>>) token ); outp: parse(( scopy = { <"> 1 <"> * } )); forw: peek/chkeof; peek: [ch=0] char(ch) fail; chkeof: ( [ch?] succ | fail );   ch: 0; sep: 0; esc: 0;
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 separated by the separators, become the elements of the output list. Empty fields should be preserved, even at the start and end. Rules for escaping: "Escaped" means preceded by an occurrence of the escape character that is not already escaped itself. When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special). Each occurrence of the escape character that was used to escape something, should not become part of the output. Test case Demonstrate that your function satisfies the following test-case: Input Output string: one^|uno||three^^^^|four^^^|^cuatro| separator character: | escape character: ^ one|uno three^^ four^|cuatro (Print the output list in any format you like, as long as it is it easy to see what the fields are.) 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
#VBA
VBA
Private Function tokenize(s As String, sep As String, esc As String) As Collection Dim ret As New Collection Dim this As String Dim skip As Boolean   If Len(s) <> 0 Then For i = 1 To Len(s) si = Mid(s, i, 1) If skip Then this = this & si skip = False Else If si = esc Then skip = True Else If si = sep Then ret.Add this this = "" Else this = this & si End If End If End If Next i ret.Add this End If Set tokenize = ret End Function   Public Sub main() Dim out As Collection Set out = tokenize("one^|uno||three^^^^|four^^^|^cuatro|", "|", "^") Dim outstring() As String ReDim outstring(out.Count - 1) For i = 0 To out.Count - 1 outstring(i) = out(i + 1) Next i Debug.Print Join(outstring, ", ") End Sub
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]
#Oz
Oz
declare Deps = unit( des_system_lib: [std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee] dw01: [ieee dw01 dware gtech] dw02: [ieee dw02 dware] dw03: [std synopsys dware dw03 dw02 dw01 ieee gtech] dw04: [dw04 ieee 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:nil )   %% Describe possible solutions proc {TopologicalOrder Solution} FullDeps = {Complete Deps} in %% The solution is a record that maps library names %% to finite domain variables. %% The smaller the value, the earlier it must be compiled Solution = {FD.record sol {Arity FullDeps} 1#{Width FullDeps}} %% for every lib on the left side {Record.forAllInd FullDeps proc {$ LibName Dependants} %% ... and every dependant on the right side for Dependant in Dependants do %% propagate compilation order if Dependant \= LibName then Solution.LibName >: Solution.Dependant end end end } %% enumerate solutions {FD.distribute naive Solution} end   %% adds empty list of dependencies for libs that only occur on the right side fun {Complete Dep} AllLibs = {Nub {Record.foldL Dep Append nil}} in {Adjoin {List.toRecord unit {Map AllLibs fun {$ L} L#nil end}} Dep} end   %% removes duplicates fun {Nub Xs} D = {Dictionary.new} in for X in Xs do D.X := unit end {Dictionary.keys D} end   %% print grouped by parallelizable jobs proc {PrintSolution Sol} for I in 1..{Record.foldL Sol Value.max 1} do for Lib in {Arity {Record.filter Sol fun {$ X} X == I end}} do {System.printInfo Lib#" "} end {System.printInfo "\n"} end end   fun {GetOrderedLibs Sol} {Map {Sort {Record.toListInd Sol} CompareSecond} SelectFirst} end fun {CompareSecond A B} A.2 < B.2 end fun {SelectFirst X} X.1 end in case {SearchOne TopologicalOrder} of nil then {System.showInfo "Un-orderable."} [] [Sol] then {System.showInfo "A possible topological ordering: "} {ForAll {GetOrderedLibs Sol} System.showInfo}   {System.showInfo "\nBONUS - grouped by parallelizable compile jobs:"} {PrintSolution Sol} end
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such a machine capable of taking the definition of any other Turing machine and executing it. Of course, you will not have an infinite tape, but you should emulate this as much as is possible. The three permissible actions on the tape are "left", "right" and "stay". To test your universal Turing machine (and prove your programming language is Turing complete!), you should execute the following two Turing machines based on the following definitions. Simple incrementer States: q0, qf Initial state: q0 Terminating states: qf Permissible symbols: B, 1 Blank symbol: B Rules: (q0, 1, 1, right, q0) (q0, B, 1, stay, qf) The input for this machine should be a tape of 1 1 1 Three-state busy beaver States: a, b, c, halt Initial state: a Terminating states: halt Permissible symbols: 0, 1 Blank symbol: 0 Rules: (a, 0, 1, right, b) (a, 1, 1, left, c) (b, 0, 1, left, a) (b, 1, 1, right, b) (c, 0, 1, left, b) (c, 1, 1, stay, halt) The input for this machine should be an empty tape. Bonus: 5-state, 2-symbol probable Busy Beaver machine from Wikipedia States: A, B, C, D, E, H Initial state: A Terminating states: H Permissible symbols: 0, 1 Blank symbol: 0 Rules: (A, 0, 1, right, B) (A, 1, 1, left, C) (B, 0, 1, right, C) (B, 1, 1, right, B) (C, 0, 1, right, D) (C, 1, 0, left, E) (D, 0, 1, left, A) (D, 1, 1, left, D) (E, 0, 1, stay, H) (E, 1, 0, left, A) The input for this machine should be an empty tape. This machine runs for more than 47 millions steps.
#SequenceL
SequenceL
//region Imports   import <Utilities/Conversion.sl>; import <Utilities/Sequence.sl>;   //endregion   //region Types   MCONFIG ::= (Label: char(1), Symbols: char(2), Operations: char(2), FinalConfig: char(1)); STATE ::= (CurrentConfig: char(1), CurrentPosition: int(0), Tape: char(1)); INPUT_DATA ::= (Iterations: int(0), InitialTape: char(1), StartingPosition: int(0), InitialConfig: char(1), MConfigs: MCONFIG(1));   //endregion   //region Constants   SPACE_CHAR := '_'; DELIMITTER := '|';   NULL_CONFIG := (Label: "", Symbols: [], Operations: [], FinalConfig: "");   TRACE_HEADER := ["Config:\t| Place:\t| Tape:"];   //endregion   //region Helpers   StateToString(state(0)) := state.CurrentConfig ++ " \t\t| " ++ intToString(state.CurrentPosition) ++ " \t| " ++ state.Tape;   StateToArrowString(state(0)) := state.Tape ++ "\n" ++ duplicate(' ', state.CurrentPosition - 1) ++ "|\n" ++ duplicate(' ', state.CurrentPosition - 1) ++ state.CurrentConfig ++ "\n";   HeadOfEach(strings(2))[i] := head(strings[i]);   RemoveCharacter(character(0), string(1))[i] := string[i] when not(string[i] = character);   GetFSquares(Tape(1))[i] := Tape[i] when (i mod 2) = 1;   //endregion   //region Parsing   ParseConfig(Line(1)) := let entries := split(Line, DELIMITTER); label := entries[1]; symbols := split(entries[2], ','); operations := split(entries[3], ','); finalConfig := entries[4]; in ((Label: label, Symbols: symbols, Operations: operations, FinalConfig: finalConfig) when not((Line[1] = '/') and (Line[2] = '/'))) when size(Line) > 0;   ParseTextFile(Text(1)) := let noSpaces := RemoveCharacter('\t', RemoveCharacter('\r', RemoveCharacter(' ', Text))); lines := split(noSpaces, '\n'); iterations := stringToInt(lines[1]); initialTape := lines[2]; initialPosition := stringToInt(lines[3]); initialConfig := lines[4]; mConfigs := ParseConfig(lines[5 ... size(lines)]); in (Iterations: iterations, InitialTape: initialTape, StartingPosition: initialPosition, InitialConfig: initialConfig, MConfigs: mConfigs);   //endregion   //region Config Finding   Matches: char(0) * char(2) -> bool; Matches(currentSymbol(0), symbols(2)) := true when size(symbols) = 0 //some(equalListNT("", symbols)) else true when currentSymbol = SPACE_CHAR and some(equalListNT("none", symbols)) else true when not(currentSymbol = SPACE_CHAR) and some(equalListNT("any", symbols)) else true when some(currentSymbol = HeadOfEach(symbols)) else false;   GetCurrentSymbol(State(0)) := State.Tape[State.CurrentPosition] when size(State.Tape) >= State.CurrentPosition and State.CurrentPosition > 0 else SPACE_CHAR;   GetConfigHelper(label(1), symbol(0), mConfigs(1))[i] := mConfigs[i] when equalList(mConfigs[i].Label, label) and Matches(symbol, mConfigs[i].Symbols);   GetConfig(label(1), symbol(0), mConfigs(1)) := let searchResults := GetConfigHelper(label, symbol, mConfigs); in NULL_CONFIG when size(searchResults) = 0 else searchResults[1];   //endregion   //region Operations   TrimTapeEnd(tape(1), position(0)) := tape when position = size(tape) else tape when not(last(tape) = SPACE_CHAR) else TrimTapeEnd(allButLast(tape), position);   ApplyOperations(State(0), Operations(2)) := let newState := ApplyOperation(State, head(Operations)); in State when size(Operations) = 0 else ApplyOperations(newState, tail(Operations));   ApplyOperation(State(0), Operation(1)) := let newTape := PrintOperation(head(tail(Operation)), State.CurrentPosition, State.Tape) when head(Operation) = 'P' else EraseOperation(State.CurrentPosition, State.Tape) when head(Operation) = 'E' else [SPACE_CHAR] ++ State.Tape when head(Operation) = 'L' and State.CurrentPosition = 1 else State.Tape ++ [SPACE_CHAR] when head(Operation) = 'R' and State.CurrentPosition = size(State.Tape) else State.Tape;   newPosition := 1 when head(Operation) = 'L' and State.CurrentPosition = 1 else State.CurrentPosition + 1 when head(Operation) = 'R' else State.CurrentPosition - 1 when head(Operation) = 'L' else State.CurrentPosition;   trimmedTape := TrimTapeEnd(newTape, newPosition); in State when size(Operation) = 0 else (CurrentPosition: newPosition, Tape: trimmedTape);   PrintOperation(Symbol(0), Position(0), Tape(1)) := let diff := Position - size(Tape) when Position > size(Tape) else 0; expandedTape := Tape ++ duplicate(SPACE_CHAR, diff); finalTape := setElementAt(expandedTape, Position, Symbol); in finalTape;   EraseOperation(Position(0), Tape(1)) := PrintOperation(SPACE_CHAR, Position, Tape);   //endregion   //region Execution   RunMachine(Text(1), Flag(1)) := let input := ParseTextFile(Text); initialState := (CurrentConfig: input.InitialConfig, CurrentPosition: input.StartingPosition, Tape: input.InitialTape);   processed := Process(initialState, input.MConfigs, input.Iterations); processedWithTrace := ProcessWithTrace(initialState, input.MConfigs, input.Iterations); in "\n" ++ delimit(TRACE_HEADER ++ StateToString(processedWithTrace), '\n') when equalList(Flag, "trace") else "\n" ++ delimit(StateToArrowString(processedWithTrace), '\n') when equalList(Flag, "arrow-trace") else processed.Tape when equalList(Flag, "tape") else TrimTapeEnd(GetFSquares(processed.Tape), 1) when equalList(Flag, "f-squares") else boolToString(DoesMachineHalt(initialState, input.MConfigs, input.Iterations)) when equalList(Flag, "halts") else StateToString(processed);   DoesMachineHalt(InitialState(0), mConfigs(1), Iterations(0)) := let resultState := Process(InitialState, mConfigs, Iterations); in equalList(resultState.CurrentConfig, "halt");   ProcessWithTrace(InitialState(0), mConfigs(1), Iterations(0)) := [InitialState] when Iterations <= 0 or size(InitialState.CurrentConfig) = 0 or equalList(InitialState.CurrentConfig, "halt") else [InitialState] ++ ProcessWithTrace(Iterate(InitialState, mConfigs), mConfigs, Iterations - 1);   Process(InitialState(0), mConfigs(1), Iterations(0)) := InitialState when Iterations = 0 or size(InitialState.CurrentConfig) = 0 or equalList(InitialState.CurrentConfig, "halt") else Process(Iterate(InitialState, mConfigs), mConfigs, Iterations - 1);   Iterate(State(0), mConfigs(1)) := let currentConfig := GetConfig(State.CurrentConfig, GetCurrentSymbol(State), mConfigs); newState := Execute(State, currentConfig); in newState;   Execute(State(0), mConfig(0)) := let newState := ApplyOperations(State, mConfig.Operations); in (CurrentConfig: mConfig.FinalConfig, CurrentPosition: newState.CurrentPosition, Tape: newState.Tape);   //endregion
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 positive integer   n   that are relatively prime to   n   counts the integers   k   in the range   1 ≤ k ≤ n   for which the greatest common divisor   gcd(n,k)   is equal to   1   counts numbers   ≤ n   and   prime to   n If the totient number   (for N)   is one less than   N,   then   N   is prime. Task Create a   totient   function and:   Find and display   (1 per line)   for the 1st   25   integers:   the integer   (the index)   the totient number for that integer   indicate if that integer is prime   Find and display the   count   of the primes up to          100   Find and display the   count   of the primes up to       1,000   Find and display the   count   of the primes up to     10,000   Find and display the   count   of the primes up to   100,000     (optional) Show all output here. Related task   Perfect totient numbers Also see   Wikipedia: Euler's totient function.   MathWorld: totient function.   OEIS: Euler totient function phi(n).
#Tiny_BASIC
Tiny BASIC
REM PRINT THE DATA FOR N=1 TO 25 LET N = 0 10 LET N = N + 1 IF N = 26 THEN GOTO 100 GOSUB 1000 IF T = N - 1 THEN LET P = 1 IF T <> N - 1 THEN LET P = 0 PRINT N," ", T," ",P GOTO 10 100 REM COUNT PRIMES BELOW 10000 LET C = 0 LET N = 2 110 GOSUB 1000 IF T = N - 1 THEN LET C = C + 1 IF N = 100 THEN PRINT "There are ", C, " primes below 100." IF N = 1000 THEN PRINT "There are ", C, " primes below 1000." IF N = 10000 THEN PRINT "There are ", C, " primes below 10000." LET N = N + 1 IF N < 10001 THEN GOTO 110 END 1000 REM TOTIENT FUNCTION OF INTEGER N LET M = 1 LET T = 0 1010 IF M > N THEN RETURN LET A = N LET B = M REM NEED TO RENAME THESE SO THEY ARE PRESERVED GOSUB 2000 IF G = 1 THEN LET T = T + 1 LET M = M + 1 GOTO 1010 2000 REM GCD OF INTEGERS A, B 2010 IF A>B THEN GOTO 2020 LET B = B - A IF A=0 THEN LET G = B IF A=0 THEN RETURN 2020 LET S = A LET A = B LET B = S GOTO 2010
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.
#Logo
Logo
print sin 45 print cos 45 print arctan 1 make "pi (radarctan 0 1) * 2 ; based on quadrant if uses two parameters print radsin :pi / 4 print radcos :pi / 4 print 4 * radarctan 1
http://rosettacode.org/wiki/Tree_traversal
Tree traversal
Task Implement a binary tree where each node carries an integer,   and implement:   pre-order,   in-order,   post-order,     and   level-order   traversal. Use those traversals to output the following tree: 1 / \ / \ / \ 2 3 / \ / 4 5 6 / / \ 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.
#Go
Go
package main   import "fmt"   type node struct { value int left, right *node }   func (n *node) iterPreorder(visit func(int)) { if n == nil { return } visit(n.value) n.left.iterPreorder(visit) n.right.iterPreorder(visit) }   func (n *node) iterInorder(visit func(int)) { if n == nil { return } n.left.iterInorder(visit) visit(n.value) n.right.iterInorder(visit) }   func (n *node) iterPostorder(visit func(int)) { if n == nil { return } n.left.iterPostorder(visit) n.right.iterPostorder(visit) visit(n.value) }   func (n *node) iterLevelorder(visit func(int)) { if n == nil { return } for queue := []*node{n}; ; { n = queue[0] visit(n.value) copy(queue, queue[1:]) queue = queue[:len(queue)-1] if n.left != nil { queue = append(queue, n.left) } if n.right != nil { queue = append(queue, n.right) } if len(queue) == 0 { return } } }   func main() { tree := &node{1, &node{2, &node{4, &node{7, nil, nil}, nil}, &node{5, nil, nil}}, &node{3, &node{6, &node{8, nil, nil}, &node{9, nil, nil}}, nil}} fmt.Print("preorder: ") tree.iterPreorder(visitor) fmt.Println() fmt.Print("inorder: ") tree.iterInorder(visitor) fmt.Println() fmt.Print("postorder: ") tree.iterPostorder(visitor) fmt.Println() fmt.Print("level-order: ") tree.iterLevelorder(visitor) fmt.Println() }   func visitor(value int) { fmt.Print(value, " ") }
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
#Go
Go
package main   import ( "fmt" "strings" )   func main() { s := "Hello,How,Are,You,Today" fmt.Println(strings.Join(strings.Split(s, ","), ".")) }
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: 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
#Groovy
Groovy
println 'Hello,How,Are,You,Today'.split(',').join('.')
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Lingo
Lingo
on testFunc () repeat with i = 1 to 1000000 x = sqrt(log(i)) end repeat end
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Logo
Logo
to time output first first shell "|date +%s| end to elapsed :block localmake "start time run :block (print time - :start [seconds elapsed]) end   elapsed [wait 300]  ; 5 seconds elapsed
http://rosettacode.org/wiki/Top_rank_per_group
Top rank per group
Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett,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
#IS-BASIC
IS-BASIC
100 PROGRAM "Employee.bas"(N) 110 LET NR=100:LET X=0 120 STRING NAME$(1 TO NR)*20,ID$(1 TO NR)*6,DEPT$(1 TO NR)*4 130 NUMERIC SALARY(1 TO NR) 140 DO UNTIL N>0 AND N<=NR 150 INPUT PROMPT "Enter the number of ranks: ":N$ 160 LET N=VAL(N$) 170 LOOP 180 CALL READDATA 190 CALL SORT 200 CALL LST 210 END 220 DEF READDATA 230 LET EOF=0 240 OPEN #1:"Employee.dat" 250 WHEN EXCEPTION USE IOERROR 260 DO 270 LET X=X+1 280 INPUT #1:NAME$(X),ID$(X),SALARY(X),DEPT$(X) 290 LOOP UNTIL EOF OR X=NR 300 END WHEN 310 HANDLER IOERROR 320 IF EXTYPE<>8001 THEN PRINT EXSTRING$(EXTYPE) 330 CLOSE #1 340 LET X=X-1:LET EOF=-1 350 IF X=0 THEN PRINT "No data.":STOP 360 CONTINUE 370 END HANDLER 380 END DEF 390 DEF SORT 400 LET GAP=X:LET SW=1 410 DO WHILE GAP>1 OR SW 420 LET GAP=MAX(INT(GAP/1.3),1):LET SW=0 430 FOR I=1 TO X-GAP 440 IF DEPT$(I)>DEPT$(I+GAP) OR DEPT$(I)=DEPT$(I+GAP) AND SALARY(I)<SALARY(I+GAP) THEN 450 LET T$=NAME$(I):LET NAME$(I)=NAME$(I+GAP):LET NAME$(I+GAP)=T$ 460 LET T$=DEPT$(I):LET DEPT$(I)=DEPT$(I+GAP):LET DEPT$(I+GAP)=T$ 470 LET T$=ID$(I):LET ID$(I)=ID$(I+GAP):LET ID$(I+GAP)=T$ 480 LET T=SALARY(I):LET SALARY(I)=SALARY(I+GAP):LET SALARY(I+GAP)=T 490 LET SW=1 500 END IF 510 NEXT 520 LOOP 530 END DEF 540 DEF LST 550 LET J=1:LET PREV$="" 560 FOR I=1 TO X 570 IF DEPT$(I)<>PREV$ THEN PRINT "Department ";DEPT$(I):LET PREV$=DEPT$(I):LET J=1 580 IF J<=N THEN PRINT " ";NAME$(I);TAB(23);ID$(I),SALARY(I):LET J=J+1 590 NEXT 600 END DEF
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.
#Groovy
Groovy
class Main {   def input = new Scanner(System.in)   static main(args) { Main main = new Main(); main.play(); }   public void play() {   TicTackToe game = new TicTackToe(); game.init() def gameOver = false def player = game.player1   println "Players take turns marking a square. Only squares \n"+ "not already marked can be picked. Once a player has \n"+ "marked three squares in a row, column or diagonal, they win! If all squares \n"+ "are marked and no three squares are the same, a tied game is declared.\n"+ "Player 1 is O and Player 2 is X \n"+ "Have Fun! \n\n" println "${game.drawBoard()}"   while (!gameOver && game.plays < 9) {   player = game.currentPlayer == 1 ? game.player1 :game.player2 def validPick = false; while (!validPick) {   def square println "Next $player, enter move by selecting square's number :" try { square = input.nextLine(); } catch (Exception ex) { }   if (square.length() == 1 && Character.isDigit(square.toCharArray()[0])) { validPick = game.placeMarker(square) } if (!validPick) { println "Select another Square" }   }   (game.checkWinner(player))? gameOver = true : game.switchPlayers() println(game.drawBoard());   } println "Game Over, " + ((gameOver == true)? "$player Wins" : "Draw") }   }   public class TicTackToe {   def board = new Object[3][3] def final player1 = "player 1" def final player2 = "player 2" def final marker1 = 'X' def final marker2 = 'O'   int currentPlayer int plays   public TicTacToe(){   }     def init() { int counter = 0; (0..2).each { row -> (0..2).each { col -> board[row][col] = (++counter).toString(); } } plays = 0 currentPlayer =1 }   def switchPlayers() { currentPlayer = (currentPlayer == 1) ? 2:1 plays++ }   def placeMarker(play) { def result = false (0..2).each { row -> (0..2).each { col -> if (board[row][col].toString()==play.toString()){ board[row][col] = (currentPlayer == 1) ? marker2 : marker1; result = true; } } } return result; }   def checkWinner(player) { char current = (player == player1)? marker2: marker1 //Checking return checkRows(current) || checkColumns(current) ||checkDiagonals(current); }   def checkRows(char current){ (0..2).any{ line -> board[line].every { it == current} } }     def checkColumns(char current){ (0..2).any{i -> (0..2).every{j -> board[j][i]==current } } }   def checkDiagonals(char current){ def rightDiag = [board[0][0],board[1][1],board[2][2]] def leftDiag = [board[0][2],board[1][1],board[2][0]] return rightDiag.every{it == current} || leftDiag.every{it == current} }     def drawBoard() { StringBuilder builder = new StringBuilder("Game board: \n"); (0..2).each { row-> (0..2).each {col -> builder.append("[" + board[row][col] + "]"); } builder.append("\n"); } builder.append("\n"); return builder.toString(); } }
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Dc
Dc
[ # move(from, to) n # print from [ --> ]n # print " --> " p # print to\n sw # p doesn't pop, so get rid of the value ]sm [ # init(n) sw # tuck n away temporarily 9 # sentinel as bottom of stack lw # bring n back 1 # "from" tower's label 3 # "to" tower's label 0 # processed marker ]si [ # Move() lt # push to lf # push from lmx # call move(from, to) ]sM [ # code block <d> ln # push n lf # push from lt # push to 1 # push processed marker 1 ln # push n 1 # push 1 - # n - 1 lf # push from ll # push left 0 # push processed marker 0 ]sd [ # code block <e> ln # push n 1 # push 1 - # n - 1 ll # push left lt # push to 0 # push processed marker 0 ]se [ # code block <x> ln 1 =M ln 1 !=d ]sx [ # code block <y> lMx lex ]sy [ # quit() q # exit the program ]sq [ # run() d 9 =q # if stack empty, quit() sp # processed st # to sf # from sn # n 6 # lf # - # lt # - # 6 - from - to sl # lp 0 =x # lp 0 !=y # lrx # loop ]sr 5lix # init(n) lrx # run()
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#VBA
VBA
Option Explicit   Sub Main() Dim i&, t$ For i = 1 To 8 t = Thue_Morse(t) Debug.Print i & ":=> " & t Next End Sub   Private Function Thue_Morse(s As String) As String Dim k$ If s = "" Then k = "0" Else k = s k = Replace(k, "1", "2") k = Replace(k, "0", "1") k = Replace(k, "2", "0") End If Thue_Morse = s & k End Function
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Text   Module Module1   Sub Sequence(steps As Integer) Dim sb1 As New StringBuilder("0") Dim sb2 As New StringBuilder("1") For index = 1 To steps Dim tmp = sb1.ToString sb1.Append(sb2) sb2.Append(tmp) Next Console.WriteLine(sb1) End Sub   Sub Main() Sequence(6) End Sub   End Module
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 separated by the separators, become the elements of the output list. Empty fields should be preserved, even at the start and end. Rules for escaping: "Escaped" means preceded by an occurrence of the escape character that is not already escaped itself. When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special). Each occurrence of the escape character that was used to escape something, should not become part of the output. Test case Demonstrate that your function satisfies the following test-case: Input Output string: one^|uno||three^^^^|four^^^|^cuatro| separator character: | escape character: ^ one|uno three^^ four^|cuatro (Print the output list in any format you like, as long as it is it easy to see what the fields are.) 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
#Vlang
Vlang
fn tokenize_string(s string, sep u8, escape u8) ?[]string { mut tokens := []string{} mut runes := []u8{} mut in_escape := false for r in s { if in_escape { in_escape = false runes << r } else if r == escape { in_escape = true } else if r == sep { tokens << runes.bytestr() runes = runes[..0] } else { runes << r } } tokens << runes.bytestr() if in_escape { return error("invalid terminal escape") } return tokens }   const sample = "one^|uno||three^^^^|four^^^|^cuatro|" const separator = `|` const escape = `^` fn main() { println("Input: $sample") tokens := tokenize_string(sample, separator, escape)? println("Tokens: $tokens") }
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]
#Pascal
Pascal
sub print_topo_sort { my %deps = @_;   my %ba; while ( my ( $before, $afters_aref ) = each %deps ) { for my $after ( @{ $afters_aref } ) { $ba{$before}{$after} = 1 if $before ne $after; $ba{$after} ||= {}; } }   while ( my @afters = sort grep { ! %{ $ba{$_} } } keys %ba ) { print "@afters\n"; delete @ba{@afters}; delete @{$_}{@afters} for values %ba; }   print !!%ba ? "Cycle found! ". join( ' ', sort keys %ba ). "\n" : "---\n"; }   my %deps = ( des_system_lib => [qw( std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee )], dw01 => [qw( ieee dw01 dware gtech )], dw02 => [qw( ieee dw02 dware )], dw03 => [qw( std synopsys dware dw03 dw02 dw01 ieee gtech )], dw04 => [qw( dw04 ieee dw01 dware gtech )], dw05 => [qw( dw05 ieee dware )], dw06 => [qw( dw06 ieee dware )], dw07 => [qw( ieee dware )], dware => [qw( ieee dware )], gtech => [qw( ieee gtech )], ramlib => [qw( std ieee )], std_cell_lib => [qw( ieee std_cell_lib )], synopsys => [qw( )], ); print_topo_sort(%deps); push @{ $deps{'dw01'} }, 'dw04'; # Add unresolvable dependency print_topo_sort(%deps);
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 a machine capable of taking the definition of any other Turing machine and executing it. Of course, you will not have an infinite tape, but you should emulate this as much as is possible. The three permissible actions on the tape are "left", "right" and "stay". To test your universal Turing machine (and prove your programming language is Turing complete!), you should execute the following two Turing machines based on the following definitions. Simple incrementer States: q0, qf Initial state: q0 Terminating states: qf Permissible symbols: B, 1 Blank symbol: B Rules: (q0, 1, 1, right, q0) (q0, B, 1, stay, qf) The input for this machine should be a tape of 1 1 1 Three-state busy beaver States: a, b, c, halt Initial state: a Terminating states: halt Permissible symbols: 0, 1 Blank symbol: 0 Rules: (a, 0, 1, right, b) (a, 1, 1, left, c) (b, 0, 1, left, a) (b, 1, 1, right, b) (c, 0, 1, left, b) (c, 1, 1, stay, halt) The input for this machine should be an empty tape. Bonus: 5-state, 2-symbol probable Busy Beaver machine from Wikipedia States: A, B, C, D, E, H Initial state: A Terminating states: H Permissible symbols: 0, 1 Blank symbol: 0 Rules: (A, 0, 1, right, B) (A, 1, 1, left, C) (B, 0, 1, right, C) (B, 1, 1, right, B) (C, 0, 1, right, D) (C, 1, 0, left, E) (D, 0, 1, left, A) (D, 1, 1, left, D) (E, 0, 1, stay, H) (E, 1, 0, left, A) The input for this machine should be an empty tape. This machine runs for more than 47 millions steps.
#Sidef
Sidef
func run_utm(state="", blank="", rules=[], tape=[blank], halt="", pos=0) {   if (pos < 0) { pos += tape.len; }   if (pos !~ tape.range) { die "Bad initial position"; }   loop { print "#{state}\t"; tape.range.each { |i| var v = tape[i]; print (i == pos ? "[#{v}]" : " #{v} "); }; print "\n";   if (state == halt) { break; }   rules.each { |rule| var (s0, v0, v1, dir, s1) = rule...; if ((s0 != state) || (tape[pos] != v0)) { next; }   tape[pos] = v1;   given(dir) { when ('left') { if (pos == 0) { tape.unshift(blank) } else { --pos }; } when ('right') { if (++pos >= tape.len) { tape.append(blank) } } }   state = s1; goto :NEXT; }   die 'No matching rules'; @:NEXT; } }   print "incr machine\n"; run_utm( halt: 'qf', state: 'q0', tape: %w(1 1 1), blank: 'B', rules: [ %w(q0 1 1 right q0), %w(q0 B 1 stay qf), ]);   say "\nbusy beaver"; run_utm( halt: 'halt', state: 'a', blank: '0', rules: [ %w(a 0 1 right b), %w(a 1 1 left c), %w(b 0 1 left a), %w(b 1 1 right b), %w(c 0 1 left b), %w(c 1 1 stay halt), ]);   say "\nsorting test"; run_utm( halt: 'STOP', state: 'A', blank: '0', tape: %w(2 2 2 1 2 2 1 2 1 2 1 2 1 2), rules: [ %w(A 1 1 right A), %w(A 2 3 right B), %w(A 0 0 left E), %w(B 1 1 right B), %w(B 2 2 right B), %w(B 0 0 left C), %w(C 1 2 left D), %w(C 2 2 left C), %w(C 3 2 left E), %w(D 1 1 left D), %w(D 2 2 left D), %w(D 3 1 right A), %w(E 1 1 left E), %w(E 0 0 right STOP), ]);
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 positive integer   n   that are relatively prime to   n   counts the integers   k   in the range   1 ≤ k ≤ n   for which the greatest common divisor   gcd(n,k)   is equal to   1   counts numbers   ≤ n   and   prime to   n If the totient number   (for N)   is one less than   N,   then   N   is prime. Task Create a   totient   function and:   Find and display   (1 per line)   for the 1st   25   integers:   the integer   (the index)   the totient number for that integer   indicate if that integer is prime   Find and display the   count   of the primes up to          100   Find and display the   count   of the primes up to       1,000   Find and display the   count   of the primes up to     10,000   Find and display the   count   of the primes up to   100,000     (optional) Show all output here. Related task   Perfect totient numbers Also see   Wikipedia: Euler's totient function.   MathWorld: totient function.   OEIS: Euler totient function phi(n).
#VBA
VBA
Private Function totient(ByVal n As Long) As Long Dim tot As Long: tot = n Dim i As Long: i = 2 Do While i * i <= n If n Mod i = 0 Then Do While True n = n \ i If n Mod i <> 0 Then Exit Do Loop tot = tot - tot \ i End If i = i + IIf(i = 2, 1, 2) Loop If n > 1 Then tot = tot - tot \ n End If totient = tot End Function   Public Sub main() Debug.Print " n phi prime" Debug.Print " --------------" Dim count As Long Dim tot As Integer, n As Long For n = 1 To 25 tot = totient(n) prime = (n - 1 = tot) count = count - prime Debug.Print Format(n, "@@"); Format(tot, "@@@@@"); Format(prime, "@@@@@@@@") Next n Debug.Print Debug.Print "Number of primes up to 25 = "; Format(count, "@@@@") For n = 26 To 100000 count = count - (totient(n) = n - 1) Select Case n Case 100, 1000, 10000, 100000 Debug.Print "Number of primes up to"; n; String$(6 - Len(CStr(n)), " "); "="; Format(count, "@@@@@") Case Else End Select Next n End Sub
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.
#Logtalk
Logtalk
  :- object(trignomeric_functions).   :- public(show/0). show :- % standard trignomeric functions work with radians write('sin(pi/4.0) = '), SIN is sin(pi/4.0), write(SIN), nl, write('cos(pi/4.0) = '), COS is cos(pi/4.0), write(COS), nl, write('tan(pi/4.0) = '), TAN is tan(pi/4.0), write(TAN), nl, write('asin(sin(pi/4.0)) = '), ASIN is asin(sin(pi/4.0)), write(ASIN), nl, write('acos(cos(pi/4.0)) = '), ACOS is acos(cos(pi/4.0)), write(ACOS), nl, write('atan(tan(pi/4.0)) = '), ATAN is atan(tan(pi/4.0)), write(ATAN), nl, write('atan2(3,4) = '), ATAN2 is atan2(3,4), write(ATAN2), nl.   :- end_object.  
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.
#Groovy
Groovy
def preorder; preorder = { Node node -> ([node] + node.children().collect { preorder(it) }).flatten() }   def postorder; postorder = { Node node -> (node.children().collect { postorder(it) } + [node]).flatten() }   def inorder; inorder = { Node node -> def kids = node.children() if (kids.empty) [node] else if (kids.size() == 1 && kids[0].'@right') [node] + inorder(kids[0]) else inorder(kids[0]) + [node] + (kids.size()>1 ? inorder(kids[1]) : []) }   def levelorder = { Node node -> def nodeList = [] def level = [node] while (!level.empty) { nodeList += level def nextLevel = level.collect { it.children() }.flatten() level = nextLevel } nodeList }   class BinaryNodeBuilder extends NodeBuilder { protected Object postNodeCompletion(Object parent, Object node) { assert node.children().size() < 3 node } }
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: 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
#Haskell
Haskell
{-# OPTIONS_GHC -XOverloadedStrings #-} import Data.Text (splitOn,intercalate) import qualified Data.Text.IO as T (putStrLn)   main = T.putStrLn . intercalate "." $ splitOn "," "Hello,How,Are,You,Today"
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: 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
#HicEst
HicEst
CHARACTER string="Hello,How,Are,You,Today", list   nWords = INDEX(string, ',', 256) + 1 maxWordLength = LEN(string) - 2*nWords ALLOCATE(list, nWords*maxWordLength)   DO i = 1, nWords EDIT(Text=string, SePaRators=',', item=i, WordEnd, CoPyto=CHAR(i, maxWordLength, list)) ENDDO   DO i = 1, nWords WRITE(APPend) TRIM(CHAR(i, maxWordLength, list)), '.' ENDDO
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.
#Lua
Lua
function Test_Function() for i = 1, 10000000 do local s = math.log( i ) s = math.sqrt( s ) end end   t1 = os.clock() Test_Function() t2 = os.clock()   print( os.difftime( t2, t1 ) )
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Module sumtolimit (limit) { sum=limit-limit n=sum n++ while limit {sum+=limit*n:limit--:n-!} } Cls ' clear screen Profiler sumtolimit 10000% Print TimeCount Profiler sumtolimit 10000& Print TimeCount Profiler sumtolimit 10000# Print TimeCount Profiler sumtolimit 10000@ Print TimeCount Profiler sumtolimit 10000~ Print TimeCount Profiler sumtolimit 10000 Print TimeCount } Checkit  
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
#J
J
NB. Dynamically generate convenience functions ('`',,;:^:_1: N=:{.Employees) =:, (_&{"1)`'' ([^:(_ -: ])L:0)"0 _~ i.# E =: {: Employees   NB. Show top six ranked employees in each dept N , (<@:>"1@:|:@:((6 <. #) {. ] \: SALARY)/.~ DEPT) |: <"1&> E
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedia tic-tac-toe.
#Haskell
Haskell
  module Main where   import System.Random import Data.List (intercalate, find, minimumBy) import System.Environment (getArgs) import Data.Char (digitToInt) import Data.Maybe (listToMaybe, mapMaybe) import Control.Monad (guard) import Data.Ord (comparing)   -- check if there is a horizontal, vertical or diagonal line of -- X or O tictactoe :: String -> Bool tictactoe a = tictactoeFor 'X' a /= tictactoeFor 'O' a   -- check if there is a horizontal, vertical or diagonal line -- for the given player "n" tictactoeFor :: Char -> String -> Bool tictactoeFor n [a,b,c,d,e,f,g,h,i] = [n,n,n] `elem` [[a,b,c],[d,e,f],[g,h,i],[a,d,g], [b,e,h],[c,f,i],[a,e,i],[c,e,g]]   -- empty game board start :: String start = " "   -- check if there is an X or an O at the given position isPossible :: Int -> String -> Bool isPossible n game = (game !! n) `notElem` "XO"   -- try to place an X or an O at a given position. -- "Right" + modified board means success, "Left" + unmodified board -- means failure place :: Int -> Char -> String -> Either String String place i c game = if isPossible i game then Right $ take i game ++ [c] ++ drop (i + 1) game else Left game   -- COMPUTER AI -- get the number of movements, starting from a given non-empty board -- and a position for the next movement, until the specified player -- wins or no movement is possible -- the positions are chosen sequentially, so there's not much -- intelligence here anyway developGame :: Bool -> Int -> Int -> Char -> String -> (Int, Char, String) developGame iterateMore moves i player game | i > 8 = -- if i arrives to the last position, iterate again from 0 -- but do it only once if iterateMore then developGame False moves 0 player game -- draw game (after one iteration, still no winning moves) else (moves, player, game) -- draw game (game board full) or a win for the player | moves == 9 || tictactoeFor player game = (moves, player, game) -- make a move, if possible, and continue playing | otherwise = case place i otherPlayer game of -- position i is not empty. try with the next position Left _ -> developGame iterateMore moves (i + 1) otherPlayer game -- position i was empty, so it was a valid move. -- change the player and make a new move, starting at pos 0 Right newGame -> developGame iterateMore (moves + 1) 0 otherPlayer newGame where otherPlayer = changePlayer player   -- COMPUTER AI -- starting from a given non-empty board, try to guess which position -- could lead the player to the fastest victory. bestMoveFor :: Char -> String -> Int bestMoveFor player game = bestMove where -- drive the game to its end for each starting position continuations = [ (x, developGame True 0 x player game) | x <- [0..8] ] -- compare the number of moves of the game and take the -- shortest one move (_, (m, _, _)) = m (bestMove, _) = minimumBy (comparing move) continuations   -- canBlock checks if the opponent has two pieces in a row and the -- other cell in the row is empty, and places the player's piece there, -- blocking the opponent canBlock :: Char -> String -> Maybe Int canBlock p [a,b,c,d,e,f,g,h,i] = listToMaybe $ mapMaybe blockable [[a,b,c],[d,e,f],[g,h,i],[a,d,g], [b,e,h],[c,f,i],[a,e,i],[c,e,g]] where blockable xs = do guard $ length (filter (== otherPlayer) xs) == 2 x <- find (`elem` "123456789") xs return $ digitToInt x otherPlayer = changePlayer p   -- format a game board for on-screen printing showGame :: String -> String showGame [a,b,c,d,e,f,g,h,i] = topBottom ++ "| | 1 | 2 | 3 |\n" ++ topBottom ++ row "0" [[a],[b],[c]] ++ row "3" [[d],[e],[f]] ++ row "6" [[g],[h],[i]] where topBottom = "+----+---+---+---+\n" row n x = "| " ++ n ++ "+ | " ++ intercalate " | " x ++ " |\n" ++ topBottom   -- ask the user to press a numeric key and convert it to an int enterNumber :: IO Int enterNumber = do c <- getChar if c `elem` "123456789" then do putStrLn "" return $ digitToInt c else do putStrLn "\nPlease enter a digit!" enterNumber   -- a human player's turn: get the number of pieces put on the board, -- the next piece to be put (X or O) and a game board, and return -- a new game state, checking if the piece can be placed on the board. -- if it can't, make the user try again. turn :: (Int, Char, String) -> IO (Int, Char, String) turn (count, player, game) = do putStr $ "Please tell me where you want to put an " ++ [player] ++ ": " pos <- enterNumber case place (pos - 1) player game of Left oldGame -> do putStrLn "That place is already taken!\n" turn (count, player, oldGame) Right newGame -> return (count + 1, changePlayer player, newGame)   -- alternate between X and O players changePlayer :: Char -> Char changePlayer 'O' = 'X' changePlayer 'X' = 'O'   -- COMPUTER AI -- make an automatic turn, placing an X or an O game board. -- the first movement is always random. -- first, the computer looks for two pieces of his opponent in a row -- and tries to block. -- otherwise, it tries to guess the best position for the next movement. -- as a last resort, it places a piece randomly. autoTurn :: Bool -> (Int, Char, String) -> IO (Int, Char, String) autoTurn forceRandom (count, player, game) = do -- try a random position 'cause everything else failed -- count == 0 overrides the value of forceRandom i <- if count == 0 || forceRandom then randomRIO (0,8) else return $ case canBlock player game of -- opponent can't be blocked. try to guess -- the best movement Nothing -> bestMoveFor player game -- opponent can be blocked, so just do it! Just blockPos -> blockPos -- if trying to place a piece at a calculated position doesn't work, -- just try again with a random value case place i player game of Left oldGame -> autoTurn True (count, player, oldGame) Right newGame -> do putStrLn $ "It's player " ++ [player] ++ "'s turn." return (count + 1, changePlayer player, newGame)   -- play a game until someone wins or the board becomes full. -- depending on the value of the variable "auto", ask the user(s) to -- put some pieces on the board or do it automatically play :: Int -> (Int, Char, String) -> IO () play auto cpg@(_, player, game) = do newcpg@(newCount, newPlayer, newGame) <- case auto of -- if both players are human, always ask them 0 -> turn cpg -- if both players are computer, always play auto 1 -> autoTurn False cpg -- X is computer, O is human 2 -> if player == 'X' then autoTurn False cpg else turn cpg -- X is human, O is computer 3 -> if player == 'O' then autoTurn False cpg else turn cpg putStrLn $ "\n" ++ showGame newGame if tictactoe newGame then putStrLn $ "Player " ++ [changePlayer newPlayer] ++ " wins!\n" else if newCount == 9 then putStrLn "Draw!\n" else play auto newcpg   -- main program: greet the user, ask for a game type, ask for the -- player that'll start the game, and play the game beginning with an -- empty board main :: IO () main = do a <- getArgs if null a then usage else do let option = head a if option `elem` ["0","1","2","3"] then do putStrLn $ "\n" ++ showGame start let m = read option :: Int play m (0, 'X', start) else usage   usage :: IO () usage = do putStrLn "TIC-TAC-TOE GAME\n================\n" putStrLn "How do you want to play?" putStrLn "Run the program with one of the following options." putStrLn "0 : both players are human" putStrLn "1 : both players are computer" putStrLn "2 : player X is computer and player O is human" putStrLn "3 : player X is human and player O is computer" putStrLn "Player X always begins."  
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Delphi
Delphi
proc move(byte n, src, via, dest) void: if n>0 then move(n-1, src, dest, via); writeln("Move disk from pole ",src," to pole ",dest); move(n-1, via, src, dest) fi corp   proc nonrec main() void: move(4, 1, 2, 3) corp
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Wren
Wren
var thueMorse = Fn.new { |n| var sb0 = "0" var sb1 = "1" (0...n).each { |i| var tmp = sb0 sb0 = sb0 + sb1 sb1 = sb1 + tmp } return sb0 }   for (i in 0..6) System.print("%(i) : %(thueMorse.call(i))")
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#XLISP
XLISP
(defun thue-morse (n) (defun flip-bits (s) (defun flip (l) (if (not (null l)) (cons (if (equal (car l) #\1) #\0 #\1) (flip (cdr l))))) (list->string (flip (string->list s)))) (if (= n 0) "0" (string-append (thue-morse (- n 1)) (flip-bits (thue-morse (- n 1))))))   ; define RANGE, for testing purposes   (defun range (x y) (if (< x y) (cons x (range (+ x 1) y))))   ; test THUE-MORSE by printing the strings it returns for n = 0 to n = 6   (mapcar (lambda (n) (print (thue-morse n))) (range 0 7))
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 separated by the separators, become the elements of the output list. Empty fields should be preserved, even at the start and end. Rules for escaping: "Escaped" means preceded by an occurrence of the escape character that is not already escaped itself. When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special). Each occurrence of the escape character that was used to escape something, should not become part of the output. Test case Demonstrate that your function satisfies the following test-case: Input Output string: one^|uno||three^^^^|four^^^|^cuatro| separator character: | escape character: ^ one|uno three^^ four^|cuatro (Print the output list in any format you like, as long as it is it easy to see what the fields are.) 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
#Wren
Wren
var SPE = "\ufffe" // unused unicode character in Specials block var SPF = "\uffff" // ditto   var tokenize = Fn.new { |str, sep, esc| str = str.replace(esc + esc, SPE).replace(esc + sep, SPF) str = (str[-1] == esc) ? str[0...-1].replace(esc, "") + esc : str.replace(esc, "") return str.split(sep).map { |s| s.replace(SPE, esc).replace(SPF, sep) }.toList }   var str = "one^|uno||three^^^^|four^^^|^cuatro|" var sep = "|" var esc = "^" var items = tokenize.call(str, sep, esc) for (item in items) System.print((item == "") ? "(empty)" : item)
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]
#Perl
Perl
sub print_topo_sort { my %deps = @_;   my %ba; while ( my ( $before, $afters_aref ) = each %deps ) { for my $after ( @{ $afters_aref } ) { $ba{$before}{$after} = 1 if $before ne $after; $ba{$after} ||= {}; } }   while ( my @afters = sort grep { ! %{ $ba{$_} } } keys %ba ) { print "@afters\n"; delete @ba{@afters}; delete @{$_}{@afters} for values %ba; }   print !!%ba ? "Cycle found! ". join( ' ', sort keys %ba ). "\n" : "---\n"; }   my %deps = ( des_system_lib => [qw( std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee )], dw01 => [qw( ieee dw01 dware gtech )], dw02 => [qw( ieee dw02 dware )], dw03 => [qw( std synopsys dware dw03 dw02 dw01 ieee gtech )], dw04 => [qw( dw04 ieee dw01 dware gtech )], dw05 => [qw( dw05 ieee dware )], dw06 => [qw( dw06 ieee dware )], dw07 => [qw( ieee dware )], dware => [qw( ieee dware )], gtech => [qw( ieee gtech )], ramlib => [qw( std ieee )], std_cell_lib => [qw( ieee std_cell_lib )], synopsys => [qw( )], ); print_topo_sort(%deps); push @{ $deps{'dw01'} }, 'dw04'; # Add unresolvable dependency print_topo_sort(%deps);
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 a machine capable of taking the definition of any other Turing machine and executing it. Of course, you will not have an infinite tape, but you should emulate this as much as is possible. The three permissible actions on the tape are "left", "right" and "stay". To test your universal Turing machine (and prove your programming language is Turing complete!), you should execute the following two Turing machines based on the following definitions. Simple incrementer States: q0, qf Initial state: q0 Terminating states: qf Permissible symbols: B, 1 Blank symbol: B Rules: (q0, 1, 1, right, q0) (q0, B, 1, stay, qf) The input for this machine should be a tape of 1 1 1 Three-state busy beaver States: a, b, c, halt Initial state: a Terminating states: halt Permissible symbols: 0, 1 Blank symbol: 0 Rules: (a, 0, 1, right, b) (a, 1, 1, left, c) (b, 0, 1, left, a) (b, 1, 1, right, b) (c, 0, 1, left, b) (c, 1, 1, stay, halt) The input for this machine should be an empty tape. Bonus: 5-state, 2-symbol probable Busy Beaver machine from Wikipedia States: A, B, C, D, E, H Initial state: A Terminating states: H Permissible symbols: 0, 1 Blank symbol: 0 Rules: (A, 0, 1, right, B) (A, 1, 1, left, C) (B, 0, 1, right, C) (B, 1, 1, right, B) (C, 0, 1, right, D) (C, 1, 0, left, E) (D, 0, 1, left, A) (D, 1, 1, left, D) (E, 0, 1, stay, H) (E, 1, 0, left, A) The input for this machine should be an empty tape. This machine runs for more than 47 millions steps.
#Standard_ML
Standard ML
(*** Signatures ***)   signature TAPE = sig datatype move = Left | Right | Stay   type ''a tape val empty : ''a tape val moveLeft  : ''a tape -> ''a tape val moveRight : ''a tape -> ''a tape val move  : ''a tape -> move -> ''a tape val getSymbol : ''a tape -> ''a option val write  : ''a option -> ''a tape -> ''a tape val leftOf  : ''a tape -> ''a option list (* Symbols left of the head in reverse order *) val rightOf  : ''a tape -> ''a option list (* Symbols right of of the head *) end   signature MACHINE = sig structure Tape : TAPE   type state = int   (* ''a is band alphabet type *) type ''a transitions = (state * ''a option Vector.vector) -> (state * (Tape.move * ''a option) Vector.vector)   type ''a configuration = { state : state, tapes : ''a Tape.tape Vector.vector }   type ''a machine = { alphabet : ''a Vector.vector, (* (not used) *) states : state Vector.vector, (* (not used) *) start  : state, (* element of stats *) final  : state, (* element of stats *) transitions : ''a transitions, (* transitions *) tapes  : ''a Tape.tape Vector.vector (* vector of the initial tapes *) } end       signature UNIVERSALMACHINE = sig structure Machine : MACHINE   val start : ''a Machine.machine -> ''a Machine.configuration   (* Find a holding configuration (limited by n steps) * Execute the handler for each step *) val simulate : (''a Machine.configuration -> unit) -> ''a Machine.machine -> int option -> ''a Machine.configuration option end     (*** Implementation ***)   structure Tape :> TAPE = struct   (* * NONE => blank field * SOME a => written field *) type ''a symbol = ''a option   datatype move = Left | Right | Stay   (* * Four cases: * 1 The tape is complete empty. * 2 The head is in the written area. * On the right and on the left handside are symbols, * On the head is a symbol. * 3/4 The head is (n-1) fields over the right/left edge of the written area. * There is at least one entry and a rest list of entries. *) datatype ''a tape = Empty | Middle of ''a symbol list * ''a symbol * ''a symbol list | LeftOf of ''a symbol * ''a symbol list * int | RightOf of ''a symbol * ''a symbol list * int   val empty = Empty   fun rep a 0 = nil | rep a n = a :: rep a (n-1)   fun leftOf (Empty) = nil | leftOf (Middle (ls, _, _)) = ls | leftOf (RightOf (r, rs, i)) = rep NONE i @ r :: rs | leftOf (LeftOf _) = nil   fun rightOf (Empty) = nil | rightOf (Middle (_, _, rs)) = rs | rightOf (RightOf _) = nil | rightOf (LeftOf (l, ls, i)) = rep NONE i @ l :: ls   fun write (NONE) t = t (* Cannot write a blank field! *) | write a t = Middle (leftOf t, a, rightOf t)   fun getSymbol (Middle (_, m, _)) = m | getSymbol _ = NONE (* blank *)     fun moveRight (Empty) = Empty | moveRight (Middle (ls, m, nil)) = RightOf (m, ls, 0) | moveRight (Middle (ls, m, r::rs)) = Middle (m::ls, r, rs) | moveRight (RightOf (l, ls, n)) = RightOf (l, ls, n+1) | moveRight (LeftOf (r, rs, 0)) = Middle (nil, r, rs) | moveRight (LeftOf (r, rs, n)) = LeftOf (r, rs, n-1)     fun moveLeft (Empty) = Empty | moveLeft (Middle (nil, m, rs)) = LeftOf (m, rs, 0) | moveLeft (Middle (l::ls, m, rs)) = Middle (ls, l, m::rs) | moveLeft (RightOf (l, ls, 0)) = Middle (ls, l, nil) | moveLeft (RightOf (l, ls, n)) = RightOf (l, ls, n-1) | moveLeft (LeftOf (r, rs, n)) = LeftOf (r, rs, n+1)     fun move tape Stay = tape | move tape Right = moveRight tape | move tape Left = moveLeft tape   (* Test *) local val tape : int tape = empty (* [] *) val tape = moveRight tape (* [] *) val NONE = getSymbol tape val tape = write (SOME 42) tape (* [42] *) val (SOME 42) = getSymbol tape val tape = moveRight tape (* 42, [] *) val tape = moveRight tape (* 42, , [] *) val NONE = getSymbol tape val tape = moveLeft tape (* 42, [] *) val NONE = getSymbol tape val tape = moveLeft tape (* [42] *) val (SOME 42) = getSymbol tape val tape = write NONE tape (* [42] *) (* !!! *) val (SOME 42) = getSymbol tape val tape = moveLeft tape (* [], 42 *) val tape = moveLeft tape (* [], , 42 *) val tape = write (SOME 47) tape (* [47], , 42 *) val (SOME 47) = getSymbol tape val tape = moveRight tape (* 47, [], 42 *) val NONE = getSymbol tape val tape = moveRight tape (* 47, , [42] *) val (SOME 42) = getSymbol tape in end end   structure Machine :> MACHINE = struct structure Tape = Tape   type state = int   (* ''a is band alphabet type *) type ''a transitions = (state * ''a option Vector.vector) -> (state * (Tape.move * ''a option) Vector.vector)   type ''a configuration = { state : state, tapes : ''a Tape.tape Vector.vector }   type ''a machine = { alphabet : ''a Vector.vector, states : state Vector.vector, start  : state, final  : state, transitions : ''a transitions, tapes  : ''a Tape.tape Vector.vector } end   structure UniversalMachine :> UNIVERSALMACHINE = struct   structure Machine = Machine   fun start ({ start, tapes, ... } : ''a Machine.machine) : ''a Machine.configuration = { state = start, tapes = tapes }   fun doTransition ({ state, tapes } : ''a Machine.configuration) ((state', actions) : (Machine.state * (Machine.Tape.move * ''a option) Vector.vector)) : ''a Machine.configuration = { state = state', tapes = Vector.mapi (fn (i, tape) => let val (move, write) = Vector.sub (actions, i) val tape' = Machine.Tape.write write tape val tape'' = Machine.Tape.move tape' move in tape'' end) tapes }   fun getSymbols ({ tapes, ... } : ''a Machine.configuration) : ''a option Vector.vector = Vector.map (Machine.Tape.getSymbol) tapes   fun step ({ transitions, ... } : ''a Machine.machine) (conf : ''a Machine.configuration) : ''a Machine.configuration = doTransition conf (transitions (#state conf, getSymbols conf))   fun isFinal ({final, ...} : ''a Machine.machine) ({state, ...} : ''a Machine.configuration) : bool = final = state   fun iter term (SOME 0) f s = NONE | iter term (SOME n) f s = if term s then SOME s else iter term (SOME (n-1)) f (f s) | iter term NONE f s = if term s then SOME s else iter term NONE f (f s)     fun simulate handler (machine : ''a Machine.machine) optcount = let val endconf = iter (isFinal machine) optcount (fn conf => (handler conf; step machine conf)) (start machine) in case endconf of NONE => NONE | SOME conf => (handler conf; endconf) end   end     structure ExampleMachines = struct   structure Machine = UniversalMachine.Machine   (* Tranform the 5-Tuple notation into the vector function *) fun makeTransitions nil : ''a Machine.transitions = (fn (t, vec) => (print (Int.toString t); raise Subscript)) | makeTransitions ((s : Machine.state, read : ''a option, write : ''a option, move : Machine.Tape.move, s' : Machine.state) :: ts) = fn (t, vec) => if s=t andalso vec=(Vector.fromList [read]) then (s', Vector.fromList [(move, write)]) else makeTransitions ts (t, vec)   (* `createTape xs` creates an tape initialized by xs, where the head stands on the first element of xs *) fun createTape' nil = Machine.Tape.empty | createTape' (x::xs) = Machine.Tape.moveLeft (Machine.Tape.write x (createTape' xs))   fun createTape xs = Machine.Tape.moveRight (createTape' (rev xs))     (* Convert a tape into a string to print it. It needs a function that converts each symbol to string *) fun tapeToStr (symStr : ''a -> string) (tape : ''a Machine.Tape.tape) : string = let val left  : ''a option list = rev (Machine.Tape.leftOf tape) val right  : ''a option list = Machine.Tape.rightOf tape val current  : ''a option = Machine.Tape.getSymbol tape val symToStr : ''a option -> string = (fn (NONE) => "#" | (SOME a) => symStr a) in String.concatWith " " ((map symToStr left) @ [ "|" ^ symToStr current ^ "|" ] @ (map symToStr right)) end   (* Convert a vector to a list *) fun vectToList vect = List.tabulate (Vector.length vect, fn i => Vector.sub (vect, i))     (* Do this before every step and after the last step. *) fun handler (symToStr : ''a -> string) ({state, tapes} : ''a Machine.configuration) : unit = let val str = "State " ^ Int.toString state ^ "\n" ^ String.concat (vectToList (Vector.mapi (fn (i, tape) => "Tape #" ^ Int.toString i ^ ": " ^ tapeToStr symToStr tape ^ "\n") tapes)) in print str end     (* Simulate and make result into string *) fun simulate (symToStr : ''a -> string) (machine : ''a Machine.machine) (optcount : int option) : string = case (UniversalMachine.simulate (handler symToStr) machine optcount) of NONE => "Did not terminate." | SOME ({state, tapes} : ''a Machine.configuration) => "Terminated."       (* Now finaly the machines! *)   val incrementer : unit Machine.machine = { alphabet = Vector.fromList [()], states = Vector.fromList [0, 1], start = 0, final = 1, tapes = Vector.fromList [createTape (map SOME [(), (), (), ()])], transitions = makeTransitions [ (0, SOME (), SOME (), Machine.Tape.Right, 0), (0, NONE, SOME (), Machine.Tape.Stay, 1)] }   val busybeaver : unit Machine.machine = { alphabet = Vector.fromList [()], states = Vector.fromList [0, 1, 2, 3], start = 0, final = 3, tapes = Vector.fromList [Machine.Tape.empty], transitions = makeTransitions [ (0, NONE, SOME (), Machine.Tape.Right, 1), (0, SOME (), SOME (), Machine.Tape.Left, 2), (1, NONE, SOME (), Machine.Tape.Left, 0), (1, SOME (), SOME (), Machine.Tape.Right, 1), (2, NONE, SOME (), Machine.Tape.Left, 1), (2, SOME (), SOME (), Machine.Tape.Stay, 3)] }   val sorting : int Machine.machine = { alphabet = Vector.fromList [1,2,3], states = Vector.fromList [0,1,2,3,4,5], start = 1, final = 0, tapes = Vector.fromList [createTape (map SOME [2, 1, 2, 2, 1, 1])], transitions = makeTransitions [ (1, SOME 1, SOME 1, Machine.Tape.Right, 1), (1, SOME 2, SOME 3, Machine.Tape.Right, 2), (1, NONE, NONE, Machine.Tape.Left, 5), (2, SOME 1, SOME 1, Machine.Tape.Right, 2), (2, SOME 2, SOME 2, Machine.Tape.Right, 2), (2, NONE, NONE, Machine.Tape.Left, 3), (3, SOME 1, SOME 2, Machine.Tape.Left, 3), (3, SOME 2, SOME 2, Machine.Tape.Left, 3), (3, SOME 3, SOME 2, Machine.Tape.Left, 5), (4, SOME 1, SOME 1, Machine.Tape.Left, 4), (4, SOME 2, SOME 2, Machine.Tape.Left, 4), (4, SOME 3, SOME 1, Machine.Tape.Right, 1), (5, SOME 1, SOME 1, Machine.Tape.Left, 5), (5, NONE, NONE, Machine.Tape.Right, 0)] } end   (** Invoke Simulations **) local open ExampleMachines val unitToString = (fn () => "()") fun simulate_unit machine optcount = print (simulate unitToString machine optcount ^ "\n") fun simulate_int machine optcount = print (simulate Int.toString machine optcount ^ "\n") in val () = print "Simulate incrementer...\n\n" val () = simulate_unit incrementer NONE val () = print "\nSimulate Busy Beaver...\n\n" val () = simulate_unit busybeaver NONE val () = print "\nSimulate Sorting...\n\n" val () = simulate_int sorting NONE end  
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 positive integer   n   that are relatively prime to   n   counts the integers   k   in the range   1 ≤ k ≤ n   for which the greatest common divisor   gcd(n,k)   is equal to   1   counts numbers   ≤ n   and   prime to   n If the totient number   (for N)   is one less than   N,   then   N   is prime. Task Create a   totient   function and:   Find and display   (1 per line)   for the 1st   25   integers:   the integer   (the index)   the totient number for that integer   indicate if that integer is prime   Find and display the   count   of the primes up to          100   Find and display the   count   of the primes up to       1,000   Find and display the   count   of the primes up to     10,000   Find and display the   count   of the primes up to   100,000     (optional) Show all output here. Related task   Perfect totient numbers Also see   Wikipedia: Euler's totient function.   MathWorld: totient function.   OEIS: Euler totient function phi(n).
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Linq.Enumerable   Module Module1   Sub Main() For i = 1 To 25 Dim t = Totient(i) Console.WriteLine("{0}{1}{2}{3}", i, vbTab, t, If(t = i - 1, vbTab & "prime", "")) Next Console.WriteLine()   Dim j = 100 While j <= 100000 Console.WriteLine($"{Range(1, j).Count(Function(x) Totient(x) + 1 = x):n0} primes below {j:n0}") j *= 10 End While End Sub   Function Totient(n As Integer) As Integer If n < 3 Then Return 1 End If If n = 3 Then Return 2 End If   Dim tot = n   If (n And 1) = 0 Then tot >>= 1 Do n >>= 1 Loop While (n And 1) = 0 End If   Dim i = 3 While i * i <= n If n Mod i = 0 Then tot -= tot \ i Do n \= i Loop While (n Mod i) = 0 End If i += 2 End While   If n > 1 Then tot -= tot \ n End If   Return tot End Function   End Module
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.
#Lua
Lua
print(math.cos(1), math.sin(1), math.tan(1), math.atan(1), math.atan2(3, 4))
http://rosettacode.org/wiki/Tree_traversal
Tree traversal
Task Implement a binary tree where each node carries an integer,   and implement:   pre-order,   in-order,   post-order,     and   level-order   traversal. Use those traversals to output the following tree: 1 / \ / \ / \ 2 3 / \ / 4 5 6 / / \ 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.
#Haskell
Haskell
---------------------- TREE TRAVERSAL --------------------   data Tree a = Empty | Node { value :: a, left :: Tree a, right :: Tree a }   preorder, inorder, postorder, levelorder :: Tree a -> [a] preorder Empty = [] preorder (Node v l r) = v : preorder l <> preorder r   inorder Empty = [] inorder (Node v l r) = inorder l <> (v : inorder r)   postorder Empty = [] postorder (Node v l r) = postorder l <> postorder r <> [v]   levelorder x = loop [x] where loop [] = [] loop (Empty : xs) = loop xs loop (Node v l r : xs) = v : loop (xs <> [l, r])   --------------------------- TEST ------------------------- 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 )   asciiTree :: String asciiTree = unlines [ " 1", " / \\", " / \\", " / \\", " 2 3", " / \\ /", " 4 5 6", " / / \\", " 7 8 9" ]   -------------------------- OUTPUT ------------------------ main :: IO () main = do putStrLn asciiTree mapM_ putStrLn $ zipWith ( \s xs -> justifyLeft 14 ' ' (s <> ":") <> unwords (show <$> xs) ) ["preorder", "inorder", "postorder", "level-order"] ([preorder, inorder, postorder, levelorder] <*> [tree]) where justifyLeft n c s = take n (s <> replicate n c)
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
#Icon_and_Unicon
Icon and Unicon
procedure main() A := [] "Hello,How,Are,You,Today" ? { while put(A, 1(tab(upto(',')),=",")) put(A,tab(0)) } every writes(!A,".") write() end
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Maple
Maple
CodeTools:-Usage(ifactor(32!+1), output = realtime, quiet);
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
AbsoluteTiming[x];
http://rosettacode.org/wiki/Top_rank_per_group
Top rank per group
Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett,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
#Java
Java
import java.io.File; import java.util.*;   public class TopRankPerGroup {   private static class Employee { final String name; final String id; final String department; final int salary;   Employee(String[] rec) { name = rec[0]; id = rec[1]; salary = Integer.parseInt(rec[2]); department = rec[3]; }   @Override public String toString() { return String.format("%s %s %d %s", id, name, salary, department); } }   public static void main(String[] args) throws Exception { int N = args.length > 0 ? Integer.parseInt(args[0]) : 3;   Map<String, List<Employee>> records = new TreeMap<>(); try (Scanner sc = new Scanner(new File("data.txt"))) { while (sc.hasNextLine()) { String[] rec = sc.nextLine().trim().split(", ");   List<Employee> lst = records.get(rec[3]); if (lst == null) { lst = new ArrayList<>(); records.put(rec[3], lst); } lst.add(new Employee(rec)); } }   records.forEach((key, val) -> { System.out.printf("%nDepartment %s%n", key); val.stream() .sorted((a, b) -> Integer.compare(b.salary, a.salary)) .limit(N).forEach(System.out::println); }); } }
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.
#Icon_and_Unicon
Icon and Unicon
  # Play TicTacToe   $define E " " # empty square $define X "X" # X piece $define O "O" # O piece   # -- define a board record Board(a, b, c, d, e, f, g, h, i)   procedure display_board (board, player) write ("\n===============") write (board.a || " | " || board.b || " | " || board.c) write ("---------") write (board.d || " | " || board.e || " | " || board.f) write ("---------") write (board.g || " | " || board.h || " | " || board.i) end   # return a set of valid moves (empty positions) in given board procedure empty_fields (board) fields := set() every i := !fieldnames(board) do if (board[i] == E) then insert (fields, i) return fields end   procedure game_start () return Board (E, E, E, E, E, E, E, E, E) end   procedure game_is_drawn (board) return *empty_fields(board) = 0 end   procedure game_won_by (board, player) return (board.a == board.b == board.c == player) | (board.d == board.e == board.f == player) | (board.g == board.h == board.i == player) | (board.a == board.d == board.g == player) | (board.b == board.e == board.h == player) | (board.c == board.f == board.i == player) | (board.a == board.e == board.i == player) | (board.g == board.e == board.c == player) end   procedure game_over (board) return game_is_drawn (board) | game_won_by (board, O) | game_won_by (board, X) end   # -- players make their move on the board # assume there is at least one empty square   procedure human_move (board, player) choice := "z" options := empty_fields (board) # keep prompting until player selects a valid square until member (options, choice) do { writes ("Choose one of: ") every writes (!options || " ") writes ("\n> ") choice := read () } board[choice] := player end   # pick and make a move at random from empty positions procedure random_move (board, player) board[?empty_fields(board)] := player end   # -- manage the game play procedure play_game () # hold procedures for players' move in variables player_O := random_move player_X := human_move   # randomly determine if human or computer moves first if (?2 = 0) then { write ("Human plays first as O") player_O := human_move player_X := random_move } else write ("Computer plays first, human is X")   # set up the game to start board := game_start () player := O display_board (board, player) # loop until the game is over, getting each player to move in turn until game_over (board) do { write (player || " to play next") # based on player, prompt for the next move if (player == O) then (player_O (board, player)) else (player_X (board, player)) # change player to move player := if (player == O) then X else O display_board (board, player) } # finish by writing out result if game_won_by (board, O) then write ("O won") else if game_won_by (board, X) then write ("X won") else write ("draw") # neither player won, so must be a draw end   # -- get things started procedure main () play_game () end  
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Draco
Draco
proc move(byte n, src, via, dest) void: if n>0 then move(n-1, src, dest, via); writeln("Move disk from pole ",src," to pole ",dest); move(n-1, via, src, dest) fi corp   proc nonrec main() void: move(4, 1, 2, 3) corp
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Dyalect
Dyalect
func hanoi(n, a, b, c) { if n > 0 { hanoi(n - 1, a, c, b) print("Move disk from \(a) to \(c)") hanoi(n - 1, b, a, c) } }   hanoi(4, "A", "B", "C")
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#XPL0
XPL0
string 0; \use zero-terminated strings char Thue; int N, I, J; [Thue:= Reserve(Free); \reserve all available memory Thue(0):= ^0; J:= 1; \set index to terminator for N:= 0 to 6 do [Thue(J):= 0; \terminate string Text(0, Thue); \show result CrLf(0); I:= 0; \invert string and store it on the end repeat Thue(J+I):= Thue(I) xor 1; I:= I+1; until I = J; J:= J+I; \set index to terminator ]; ]
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Yabasic
Yabasic
tm$ = "0" for i=1 to 8  ? tm$ tm$ = tm$ + inverte$(tm$) next   sub inverte$(tm$) local i   for i = 1 to len(tm$) mid$(tm$, i, 1) = str$(not val(mid$(tm$, i, 1))) next return tm$ end sub
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#zkl
zkl
fcn nextTM(str){ str.pump(str,'-.fp("10")) } // == fcn(c){ "10" - c }) }
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were separated by the separators, become the elements of the output list. Empty fields should be preserved, even at the start and end. Rules for escaping: "Escaped" means preceded by an occurrence of the escape character that is not already escaped itself. When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special). Each occurrence of the escape character that was used to escape something, should not become part of the output. Test case Demonstrate that your function satisfies the following test-case: Input Output string: one^|uno||three^^^^|four^^^|^cuatro| separator character: | escape character: ^ one|uno three^^ four^|cuatro (Print the output list in any format you like, as long as it is it easy to see what the fields are.) 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
#zkl
zkl
fcn tokenize(str,sep,esc){ sink:=Sink(String); foreach c in (str){ switch(c){ case(esc){ sink.write(__cWalker.next()); } // error if ^EoS case(sep){ sink.write("\xff"); } else { sink.write(c) } } } sink.close().split("\xff"); }
http://rosettacode.org/wiki/Topological_sort
Topological sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort 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]
#Phix
Phix
sequence names enum RANK, NAME, DEP -- content of names -- rank is 1 for items to compile first, then 2, etc, -- or 0 if cyclic dependencies prevent compilation. -- name is handy, and makes the result order alphabetic! -- dep is a list of dependencies (indexes to other names) function add_dependency(string name) integer k = find(name,vslice(names,NAME)) if k=0 then names = append(names,{0,name,{}}) k = length(names) end if return k end function procedure topsort(string input) names = {} sequence lines = split(input,'\n') for i=1 to length(lines) do sequence line = split(lines[i]), dependencies = {} integer k = add_dependency(line[1]) for j=2 to length(line) do integer l = add_dependency(line[j]) if l!=k then -- ignore self-references dependencies &= l end if end for names[k][DEP] = dependencies end for -- Now populate names[RANK] iteratively: bool more = true integer rank = 0 while more do more = false rank += 1 for i=1 to length(names) do if names[i][RANK]=0 then bool ok = true for j=1 to length(names[i][DEP]) do integer ji = names[i][DEP][j], nr = names[ji][RANK] if nr=0 or nr=rank then -- not yet compiled, or same pass ok = false exit end if end for if ok then names[i][RANK] = rank more = true end if end if end for end while names = sort(names) -- (ie by [RANK=1] then [NAME=2]) integer prank = names[1][RANK] if prank=0 then puts(1,"** CYCLIC **:") end if for i=1 to length(names) do rank = names[i][RANK] if i>1 then puts(1,iff(rank=prank?" ":"\n")) end if puts(1,names[i][NAME]) prank = rank end for puts(1,"\n") end procedure constant input = """ 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""" topsort(input) puts(1,"\nbad input:\n") topsort(input&"\ndw01 dw04")
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 a machine capable of taking the definition of any other Turing machine and executing it. Of course, you will not have an infinite tape, but you should emulate this as much as is possible. The three permissible actions on the tape are "left", "right" and "stay". To test your universal Turing machine (and prove your programming language is Turing complete!), you should execute the following two Turing machines based on the following definitions. Simple incrementer States: q0, qf Initial state: q0 Terminating states: qf Permissible symbols: B, 1 Blank symbol: B Rules: (q0, 1, 1, right, q0) (q0, B, 1, stay, qf) The input for this machine should be a tape of 1 1 1 Three-state busy beaver States: a, b, c, halt Initial state: a Terminating states: halt Permissible symbols: 0, 1 Blank symbol: 0 Rules: (a, 0, 1, right, b) (a, 1, 1, left, c) (b, 0, 1, left, a) (b, 1, 1, right, b) (c, 0, 1, left, b) (c, 1, 1, stay, halt) The input for this machine should be an empty tape. Bonus: 5-state, 2-symbol probable Busy Beaver machine from Wikipedia States: A, B, C, D, E, H Initial state: A Terminating states: H Permissible symbols: 0, 1 Blank symbol: 0 Rules: (A, 0, 1, right, B) (A, 1, 1, left, C) (B, 0, 1, right, C) (B, 1, 1, right, B) (C, 0, 1, right, D) (C, 1, 0, left, E) (D, 0, 1, left, A) (D, 1, 1, left, D) (E, 0, 1, stay, H) (E, 1, 0, left, A) The input for this machine should be an empty tape. This machine runs for more than 47 millions steps.
#Tcl
Tcl
proc turing {states initial terminating symbols blank tape rules {doTrace 1}} { set state $initial set idx 0 set tape [split $tape ""] if {[llength $tape] == 0} { set tape [list $blank] } foreach rule $rules { lassign $rule state0 sym0 sym1 move state1 set R($state0,$sym0) [list $sym1 $move $state1] } while {$state ni $terminating} { set sym [lindex $tape $idx] lassign $R($state,$sym) sym1 move state1 if {$doTrace} { ### Print the state, great for debugging puts "[join $tape ""]\t$state->$state1" puts "[string repeat { } $idx]^" } lset tape $idx $sym1 switch $move { left { if {[incr idx -1] < 0} { set idx 0 set tape [concat [list $blank] $tape] } } right { if {[incr idx] == [llength $tape]} { lappend tape $blank } } } set state $state1 } return [join $tape ""] }
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 positive integer   n   that are relatively prime to   n   counts the integers   k   in the range   1 ≤ k ≤ n   for which the greatest common divisor   gcd(n,k)   is equal to   1   counts numbers   ≤ n   and   prime to   n If the totient number   (for N)   is one less than   N,   then   N   is prime. Task Create a   totient   function and:   Find and display   (1 per line)   for the 1st   25   integers:   the integer   (the index)   the totient number for that integer   indicate if that integer is prime   Find and display the   count   of the primes up to          100   Find and display the   count   of the primes up to       1,000   Find and display the   count   of the primes up to     10,000   Find and display the   count   of the primes up to   100,000     (optional) Show all output here. Related task   Perfect totient numbers Also see   Wikipedia: Euler's totient function.   MathWorld: totient function.   OEIS: Euler totient function phi(n).
#Wren
Wren
import "/fmt" for Fmt   var totient = Fn.new { |n| var tot = n var i = 2 while (i*i <= n) { if (n%i == 0) { while(n%i == 0) n = (n/i).floor tot = tot - (tot/i).floor } if (i == 2) i = 1 i = i + 2 } if (n > 1) tot = tot - (tot/n).floor return tot }   System.print(" n phi prime") System.print("---------------") var count = 0 for (n in 1..25) { var tot = totient.call(n) var isPrime = (n - 1) == tot if (isPrime) count = count + 1 System.print("%(Fmt.d(2, n))  %(Fmt.d(2, tot))  %(isPrime)") } System.print("\nNumber of primes up to 25 = %(count)") for (n in 26..100000) { var tot = totient.call(n) if (tot == n - 1) count = count + 1 if (n == 100 || n == 1000 || n%10000 == 0) { System.print("\nNumber of primes up to %(Fmt.d(-6, n)) = %(count)") } }
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.
#Maple
Maple
sin(Pi/3); cos(Pi/3); tan(Pi/3);
http://rosettacode.org/wiki/Tree_traversal
Tree traversal
Task Implement a binary tree where each node carries an integer,   and implement:   pre-order,   in-order,   post-order,     and   level-order   traversal. Use those traversals to output the following tree: 1 / \ / \ / \ 2 3 / \ / 4 5 6 / / \ 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.
#Icon_and_Unicon
Icon and Unicon
procedure main() bTree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]] showTree(bTree, preorder|inorder|postorder|levelorder) end   procedure showTree(tree, f) writes(image(f),":\t") every writes(" ",f(tree)[1]) write() end   procedure preorder(L) if \L then suspend L | preorder(L[2|3]) end   procedure inorder(L) if \L then suspend inorder(L[2]) | L | inorder(L[3]) end   procedure postorder(L) if \L then suspend postorder(L[2|3]) | L end   procedure levelorder(L) if \L then { queue := [L] while nextnode := get(queue) do { every put(queue, \nextnode[2|3]) suspend nextnode } } 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
#Io
Io
"Hello,How,Are,You,Today" split(",") join(".") println
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: 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
#J
J
s=: 'Hello,How,Are,You,Today' ] t=: <;._1 ',',s +-----+---+---+---+-----+ |Hello|How|Are|You|Today| +-----+---+---+---+-----+  ; t,&.>'.' Hello.How.Are.You.Today.   '.' (I.','=s)}s NB. two steps combined Hello.How.Are.You.Today
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Maxima
Maxima
f(n) := if n < 2 then n else f(n - 1) + f(n - 2)$   /* First solution, call the time function with an output line number, it gives the time taken to compute that line. Here it's assumed to be %o2 */ f(24); 46368   time(%o2); [0.99]   /* Second solution, change a system flag to print timings for all following lines */ showtime: true$   f(24); Evaluation took 0.9400 seconds (0.9400 elapsed) 46368
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.
#MiniScript
MiniScript
start = time for i in range(1,100000) end for duration = time - start print "Process took " + duration + " seconds"
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Nim
Nim
import times, strutils   proc doWork(x: int) = var n = x for i in 0..10000000: n += i   template time(statement: untyped): float = let t0 = cpuTime() statement cpuTime() - t0   echo "Time = ", time(doWork(100)).formatFloat(ffDecimal, precision = 3), " s"
http://rosettacode.org/wiki/Top_rank_per_group
Top rank per group
Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett,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
#JavaScript
JavaScript
var data = [ {name: "Tyler Bennett", id: "E10297", salary: 32000, dept: "D101"}, {name: "John Rappl", id: "E21437", salary: 47000, dept: "D050"}, {name: "George Woltman", id: "E00127", salary: 53500, dept: "D101"}, {name: "Adam Smith", id: "E63535", salary: 18000, dept: "D202"}, {name: "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 top_rank(n) { var by_dept = group_by_dept(data); for (var dept in by_dept) { output(dept); for (var i = 0; i < n && i < by_dept[dept].length; i++) { var emp = by_dept[dept][i]; output(emp.name + ", id=" + emp.id + ", salary=" + emp.salary); } output(""); } }   // group by dept, and sort by salary function group_by_dept(data) { var by_dept = {}; for (var idx in data) { var dept = data[idx].dept; if ( ! has_property(by_dept, dept)) { by_dept[dept] = new Array(); } by_dept[dept].push(data[idx]); } for (var dept in by_dept) { // numeric sort by_dept[dept].sort(function (a,b){return b.salary - a.salary}); } return by_dept; }   function has_property(obj, propname) { return typeof(obj[propname]) != "undefined"; }   function output(str) { try { WScript.Echo(str); // WSH } catch(err) { print(str); // Rhino } }   top_rank(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.
#J
J
  Note 'ttt adjudicates or plays'   use: markers ttt characters   characters represent the cell names.   markers is a length 3 character vector of the characters to use for first and second player followed by the opponent's mark. 'XOX' means X plays 1st, O is the other mark, and the first strategy plays 1st. 'XOO' means X plays 1st, O is the other mark, and the second strategy moves first.   The game is set up for the computer as the first strategy (random), and human as second.   A standard use: 'XOX'ttt'abcdefghijkl'   Example game reformatted w/ emacs artist-mode to fit your display:   '#-#'ttt'wersdfxcv' w│e│r w│e│r .... -│e│r . -│e│# ─┼─┼─ . ─┼─┼─ .. ─┼─┼─ .. ─┼─┼─ s│d│f . s│#│f .. s│#│f .. -│#│f ─┼─┼─ .. ─┼─┼─ . ─┼─┼─ ... ─┼─┼─ x│c│v .. -│c│v . -│c│# .. -│c│# d .. v .. r . VICTORY w│e│r .. w│e│r .. -│e│# . ─┼─┼─ ... ─┼─┼─ .. ─┼─┼─ . s│#│f ... s│#│f .. s│#│f . ─┼─┼─ .. ─┼─┼─ ... ─┼─┼─ ... x│c│v -│c│# -│c│# -->cell for -? -->cell for -? -->cell for -? x w s )   while=: conjunction def 'u ^: v ^:_' NB. j assumes while is a verb and needs to know while is a conjunction.   ttt=: outcome@:((display@:move) while undecided)@:display@:prepare   blindfolded_variant=: outcome@:display@:(move while undecided)@:display@:prepare   outcome=: {&(>;:'kitty VICTORY')@:won NB. (outcome does not pass along the state) move=: post locate undecided=: won nor full prepare=: , board@:] NB. form the state vector   Note 'locate' is a monadic verb. y is the state vector. returns the character of the chosen cell. Generally: locate=: second_strategy`first_strategy@.(first = mark) Simplified: locate=: human_locate NB. human versus human ) locate=: human_locate`computer_locate@.(first = mark)   display=: show [: (1 1,:5 5)&(];.0)@:": [: <"0 fold   computer_locate=: [: show@{. board -. marks NB. strategy: first available computer_locate=: [: show@({~ ?@:#) board -. marks NB. strategy: random   human_locate=: monad define state=. y m=. mark state b=. board state cells=. b -. marks state show '-->cell for ' , m , '?' whilst. cell -.@:e. cells do. cell =. {. (1!:1]1) , m end. )   post=: 2&A.@:(3&{.)@:[ prepare mark@:[`((i.~ board)~)`(board@:[)}   mark=: {. NB. mark of the current player from state marks=: 2&{. NB. extract both markers from state board=: _9&{. NB. extract board from state first=: 2&{ NB. extract first player from state   show=: [ smoutput   full=: 2 = #@:~. won=: test@:fold fold=: 3 3 $ board test=: [: any [: all [: infix_pairs_agree |:@:lines   lines=: , diagonal , diagonal@:|. , |: diagonal=: (<0 1)&|: all=: *./ any=: +./ nor=: 8 b. infix_pairs_agree=: 2&(=/\)  
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#E
E
def move(out, n, fromPeg, toPeg, viaPeg) { if (n.aboveZero()) { move(out, n.previous(), fromPeg, viaPeg, toPeg) out.println(`Move disk $n from $fromPeg to $toPeg.`) move(out, n.previous(), viaPeg, toPeg, fromPeg) } }   move(stdout, 4, def left {}, def right {}, def middle {})
http://rosettacode.org/wiki/Topological_sort
Topological sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort 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]
#Picat
Picat
topological_sort(Precedences, Sorted) =>   Edges = [K=V : [K,V] in Precedences], Nodes = (domain(Edges) ++ range(Edges)).remove_dups(), Sorted1 = [], while (member(X,Nodes), not membchk(X,range(Edges))) Sorted1 := Sorted1 ++ [X], Nodes := Nodes.delete(X), Edges := Edges.delete_key(X) end,  % detect and remove a cycle if Nodes.length > 0 then println("\nThe graph is cyclic. Here's the detected cycle."), println(nodes_in_cycle=Nodes), println(edges_in_cycle=Edges), Sorted = [without_cycle=Sorted1,cycle=Nodes] else Sorted = Sorted1 end, nl.   % domain are the keys in L domain(L) = [K : K=_V in L].   % range are the values of L range(L) = [V : _K=V in L].   % deletes all pairs in L where a key is X % (this is lessf on a multi-map in GNU SETL) delete_key(L,X) = [K=V : K=V in L, K!=X].
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 a machine capable of taking the definition of any other Turing machine and executing it. Of course, you will not have an infinite tape, but you should emulate this as much as is possible. The three permissible actions on the tape are "left", "right" and "stay". To test your universal Turing machine (and prove your programming language is Turing complete!), you should execute the following two Turing machines based on the following definitions. Simple incrementer States: q0, qf Initial state: q0 Terminating states: qf Permissible symbols: B, 1 Blank symbol: B Rules: (q0, 1, 1, right, q0) (q0, B, 1, stay, qf) The input for this machine should be a tape of 1 1 1 Three-state busy beaver States: a, b, c, halt Initial state: a Terminating states: halt Permissible symbols: 0, 1 Blank symbol: 0 Rules: (a, 0, 1, right, b) (a, 1, 1, left, c) (b, 0, 1, left, a) (b, 1, 1, right, b) (c, 0, 1, left, b) (c, 1, 1, stay, halt) The input for this machine should be an empty tape. Bonus: 5-state, 2-symbol probable Busy Beaver machine from Wikipedia States: A, B, C, D, E, H Initial state: A Terminating states: H Permissible symbols: 0, 1 Blank symbol: 0 Rules: (A, 0, 1, right, B) (A, 1, 1, left, C) (B, 0, 1, right, C) (B, 1, 1, right, B) (C, 0, 1, right, D) (C, 1, 0, left, E) (D, 0, 1, left, A) (D, 1, 1, left, D) (E, 0, 1, stay, H) (E, 1, 0, left, A) The input for this machine should be an empty tape. This machine runs for more than 47 millions steps.
#UNIX_Shell
UNIX Shell
#!/usr/bin/env bash main() { printf 'Simple Incrementer\n' printf '1 1 1' | run_utm q0 qf B q0,1,1,R,q0 q0,B,1,S,qf   printf '\nThree-state busy beaver\n' run_utm a halt 0 \ a,0,1,R,b a,1,1,L,c b,0,1,L,a b,1,1,R,b c,0,1,L,b c,1,1,S,halt \ </dev/null }   run_utm() { local initial=$1 final=$2 blank=$3 shift 3 local rules=("$@") tape mapfile -t -d' ' tape if (( ! ${#tape[@]} )); then tape=( "$blank" ) fi local state=$initial local head=0 while [[ $state != $final ]]; do print_state "$state" "$head" "${tape[@]}" local symbol=${tape[head]} local found=0 rule from input output move to for rule in "${rules[@]}"; do IFS=, read from input output move to <<<"$rule" if [[ $state == $from && $symbol == $input ]]; then found=1 break fi done if (( ! found )); then printf >&2 "Configuration error: no match for state=$state input=$sym\n" return 1 fi tape[head]=$output state=$to case "$move" in L) if (( ! head-- )); then head=0 tape=("$blank" "${tape[@]}") fi  ;; R) if (( ++head >= ${#tape[@]} )); then tape+=("$blank") fi  ;; esac done print_state "$state" "$head" "${tape[@]}" }   print_state() { local state=$1 head=$2 shift 2 local tape=("$@") printf '%s' "$state" printf '  %s' "${tape[@]}" printf '\r' (( t = ${#state} + 1 + 3 * head )) printf '\e['"$t"'C<\e[C>\n' }   main "$@"  
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 positive integer   n   that are relatively prime to   n   counts the integers   k   in the range   1 ≤ k ≤ n   for which the greatest common divisor   gcd(n,k)   is equal to   1   counts numbers   ≤ n   and   prime to   n If the totient number   (for N)   is one less than   N,   then   N   is prime. Task Create a   totient   function and:   Find and display   (1 per line)   for the 1st   25   integers:   the integer   (the index)   the totient number for that integer   indicate if that integer is prime   Find and display the   count   of the primes up to          100   Find and display the   count   of the primes up to       1,000   Find and display the   count   of the primes up to     10,000   Find and display the   count   of the primes up to   100,000     (optional) Show all output here. Related task   Perfect totient numbers Also see   Wikipedia: Euler's totient function.   MathWorld: totient function.   OEIS: Euler totient function phi(n).
#XPL0
XPL0
func GCD(N, D); \Return the greatest common divisor of N and D int N, D; \numerator and denominator int R; [if D > N then [R:= D; D:= N; N:= R]; \swap D and N while D > 0 do [R:= rem(N/D); N:= D; D:= R; ]; return N; ]; \GCD   func Totient(N); \Return the totient of N int N, Phi, M; [Phi:= 0; for M:= 1 to N do if GCD(M, N) = 1 then Phi:= Phi+1; return Phi; ];   int N, Phi, Pwr, C, Limit; [Text(0, "n phi is prime^m^j"); for N:= 1 to 25 do [IntOut(0, N); ChOut(0, 9\tab\); Phi:= Totient(N); IntOut(0, Phi); ChOut(0, 9\tab\); Text(0, if Phi = N-1 then "true" else "false"); CrLf(0); ]; CrLf(0); for Pwr:= 2 to 4 do [C:= 0; Limit:= fix(Pow(10.0, float(Pwr))); IntOut(0, Limit); ChOut(0, 9\tab\); for N:= 1 to Limit do [Phi:= Totient(N); if Phi = N-1 then C:= C+1; ]; IntOut(0, C); CrLf(0); ]; ]
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Sin[1] Cos[1] Tan[1] ArcSin[1] ArcCos[1] ArcTan[1] Sin[90 Degree] Cos[90 Degree] Tan[90 Degree]
http://rosettacode.org/wiki/Tree_traversal
Tree traversal
Task Implement a binary tree where each node carries an integer,   and implement:   pre-order,   in-order,   post-order,     and   level-order   traversal. Use those traversals to output the following tree: 1 / \ / \ / \ 2 3 / \ / 4 5 6 / / \ 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.
#Isabelle
Isabelle
theory Tree imports Main begin   datatype 'a tree = Leaf | Node "'a tree" 'a "'a tree"   definition example :: "int tree" where "example ≡ Node (Node (Node (Node Leaf 7 Leaf) 4 Leaf ) 2 (Node Leaf 5 Leaf) ) 1 (Node (Node (Node Leaf 8 Leaf) 6 (Node Leaf 9 Leaf) ) 3 Leaf )"   fun preorder :: "'a tree ⇒ 'a list" where "preorder Leaf = []" | "preorder (Node l a r) = a # preorder l @ preorder r"   lemma "preorder example = [1, 2, 4, 7, 5, 3, 6, 8, 9]" by code_simp   fun inorder :: "'a tree ⇒ 'a list" where "inorder Leaf = []" | "inorder (Node l a r) = inorder l @ [a] @ inorder r"   lemma "inorder example = [7, 4, 2, 5, 1, 8, 6, 9, 3]" by code_simp   fun postorder :: "'a tree ⇒ 'a list" where "postorder Leaf = []" | "postorder (Node l a r) = postorder l @ postorder r @ [a]"   lemma "postorder example = [7, 4, 5, 2, 8, 9, 6, 3, 1]" by code_simp   lemma "set (inorder t) = set (preorder t)" "set (preorder t) = set (postorder t)" "set (inorder t) = set (postorder t)" by(induction t, simp, simp)+   text‹ For a breadth first search, we will have a queue of the nodes we still want to visit. The type of the queue is \<^typ>‹'a tree list›. With each step, summing the sizes of the subtrees in the queue, the queue gets smaller. Thus, the breadth first search terminates. Isabelle cannot figure out this termination argument automatically, so we provide some help by defining what the size of a tree is. › fun tree_size :: "'a tree ⇒ nat" where "tree_size Leaf = 1" | "tree_size (Node l _ r) = 1 + tree_size l + tree_size r"   function (sequential) bfs :: "'a tree list ⇒ 'a list" where "bfs [] = []" | "bfs (Leaf#q) = bfs q" | "bfs ((Node l a r)#q) = a # bfs (q @ [l,r])" by pat_completeness auto termination bfs by(relation "measure (λqs. sum_list (map tree_size qs))") simp+   fun levelorder :: "'a tree ⇒ 'a list" where "levelorder t = bfs [t]"   lemma "levelorder example = [1, 2, 3, 4, 5, 6, 7, 8, 9]" by code_simp   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
#Java
Java
String toTokenize = "Hello,How,Are,You,Today"; System.out.println(String.join(".", toTokenize.split(",")));
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: 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
#JavaScript
JavaScript
alert( "Hello,How,Are,You,Today".split(",").join(".") );
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#OCaml
OCaml
let time_it action arg = let start_time = Sys.time () in ignore (action arg); let finish_time = Sys.time () in finish_time -. start_time
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Oforth
Oforth
>#[ 0 1000 seq apply(#+) ] bench . 267 500500 ok
http://rosettacode.org/wiki/Top_rank_per_group
Top rank per group
Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett,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
#jq
jq
{ "Employee Name": "Tyler Bennett", "Employee ID": "E10297", "Salary": "32000", "Department": "D101" }
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedia tic-tac-toe.
#Java
Java
  import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Hashtable;   public class TicTacToe { public static void main(String[] args) { TicTacToe now=new TicTacToe(); now.startMatch(); }   private int[][] marks; private int[][] wins; private int[] weights; private char[][] grid; private final int knotcount=3; private final int crosscount=4; private final int totalcount=5; private final int playerid=0; private final int compid=1; private final int truceid=2; private final int playingid=3; private String movesPlayer; private byte override; private char[][] overridegrid={{'o','o','o'},{'o','o','o'},{'o','o','o'}}; private char[][] numpad={{'7','8','9'},{'4','5','6'},{'1','2','3'}}; private Hashtable<Integer,Integer> crossbank; private Hashtable<Integer,Integer> knotbank;   public void startMatch() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Start?(y/n):"); char choice='y'; try { choice=br.readLine().charAt(0); } catch(Exception e) { System.out.println(e.getMessage()); } if(choice=='n'||choice=='N') { return; }   System.out.println("Use a standard numpad as an entry grid, as so:\n "); display(numpad); System.out.println("Begin"); int playerscore=0; int compscore=0; do { int result=startGame(); if(result==playerid) playerscore++; else if(result==compid) compscore++; System.out.println("Score: Player-"+playerscore+" AI-"+compscore); System.out.print("Another?(y/n):"); try { choice=br.readLine().charAt(0); } catch(Exception e) { System.out.println(e.getMessage()); }   }while(choice!='n'||choice=='N');   System.out.println("Game over."); } private void put(int cell,int player) { int i=-1,j=-1;; switch(cell) { case 1:i=2;j=0;break; case 2:i=2;j=1;break; case 3:i=2;j=2;break; case 4:i=1;j=0;break; case 5:i=1;j=1;break; case 6:i=1;j=2;break; case 7:i=0;j=0;break; case 8:i=0;j=1;break; case 9:i=0;j=2;break; default:display(overridegrid);return; } char mark='x'; if(player==0) mark='o'; grid[i][j]=mark; display(grid); } private int startGame() { init(); display(grid); int status=playingid; while(status==playingid) { put(playerMove(),0); if(override==1) { System.out.println("O wins."); return playerid; } status=checkForWin(); if(status!=playingid) break; try{Thread.sleep(1000);}catch(Exception e){System.out.print(e.getMessage());} put(compMove(),1); status=checkForWin(); } return status; } private void init() { movesPlayer=""; override=0; marks=new int[8][6]; wins=new int[][] //new int[8][3]; { {7,8,9}, {4,5,6}, {1,2,3}, {7,4,1}, {8,5,2}, {9,6,3}, {7,5,3}, {9,5,1} }; weights=new int[]{3,2,3,2,4,2,3,2,3}; grid=new char[][]{{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}}; crossbank=new Hashtable<Integer,Integer>(); knotbank=new Hashtable<Integer,Integer>(); } private void mark(int m,int player) { for(int i=0;i<wins.length;i++) for(int j=0;j<wins[i].length;j++) if(wins[i][j]==m) { marks[i][j]=1; if(player==playerid) marks[i][knotcount]++; else marks[i][crosscount]++; marks[i][totalcount]++; } } private void fixWeights() { for(int i=0;i<3;i++) for(int j=0;j<3;j++) if(marks[i][j]==1) if(weights[wins[i][j]-1]!=Integer.MIN_VALUE) weights[wins[i][j]-1]=Integer.MIN_VALUE;   for(int i=0;i<8;i++) { if(marks[i][totalcount]!=2) continue; if(marks[i][crosscount]==2) { int p=i,q=-1; if(marks[i][0]==0) q=0; else if(marks[i][1]==0) q=1; else if(marks[i][2]==0) q=2;   if(weights[wins[p][q]-1]!=Integer.MIN_VALUE) { weights[wins[p][q]-1]=6; } } if(marks[i][knotcount]==2) { int p=i,q=-1; if(marks[i][0]==0) q=0; else if(marks[i][1]==0) q=1; else if(marks[i][2]==0) q=2;   if(weights[wins[p][q]-1]!=Integer.MIN_VALUE) { weights[wins[p][q]-1]=5; } } } } private int compMove() { int cell=move(); System.out.println("Computer plays: "+cell); //weights[cell-1]=Integer.MIN_VALUE; return cell; } private int move() { int max=Integer.MIN_VALUE; int cell=0; for(int i=0;i<weights.length;i++) if(weights[i]>max) { max=weights[i]; cell=i+1; }   //This section ensures the computer never loses //Remove it for a fair match //Dirty kluge if(movesPlayer.equals("76")||movesPlayer.equals("67")) cell=9; else if(movesPlayer.equals("92")||movesPlayer.equals("29")) cell=3; else if (movesPlayer.equals("18")||movesPlayer.equals("81")) cell=7; else if(movesPlayer.equals("73")||movesPlayer.equals("37")) cell=4*((int)(Math.random()*2)+1); else if(movesPlayer.equals("19")||movesPlayer.equals("91")) cell=4+2*(int)(Math.pow(-1, (int)(Math.random()*2)));   mark(cell,1); fixWeights(); crossbank.put(cell, 0); return cell; } private int playerMove() { System.out.print("What's your move?: "); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int cell=0; int okay=0; while(okay==0) { try { cell=Integer.parseInt(br.readLine()); } catch(Exception e) { System.out.println(e.getMessage()); } if(cell==7494) { override=1; return -1; } if((cell<1||cell>9)||weights[cell-1]==Integer.MIN_VALUE) System.out.print("Invalid move. Try again:"); else okay=1; } playerMoved(cell); System.out.println(); return cell; } private void playerMoved(int cell) { movesPlayer+=cell; mark(cell,0); fixWeights(); knotbank.put(cell, 0); } private int checkForWin() { int crossflag=0,knotflag=0; for(int i=0;i<wins.length;i++) { if(crossbank.containsKey(wins[i][0])) if(crossbank.containsKey(wins[i][1])) if(crossbank.containsKey(wins[i][2])) { crossflag=1; break; } if(knotbank.containsKey(wins[i][0])) if(knotbank.containsKey(wins[i][1])) if(knotbank.containsKey(wins[i][2])) { knotflag=1; break; } } if(knotflag==1) { display(grid); System.out.println("O wins."); return playerid; } else if(crossflag==1) { display(grid); System.out.println("X wins."); return compid; }   for(int i=0;i<weights.length;i++) if(weights[i]!=Integer.MIN_VALUE) return playingid; System.out.println("Truce");   return truceid; } private void display(char[][] grid) { for(int i=0;i<3;i++) { System.out.println("\n-------"); System.out.print("|"); for(int j=0;j<3;j++) System.out.print(grid[i][j]+"|"); } System.out.println("\n-------"); } }  
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#EasyLang
EasyLang
func hanoi n src dst aux . . if n >= 1 call hanoi n - 1 src aux dst print "Move " & src & " to " & dst call hanoi n - 1 aux dst src . . call hanoi 5 1 2 3
http://rosettacode.org/wiki/Topological_sort
Topological sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort 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]
#PicoLisp
PicoLisp
(de sortDependencies (Lst) (setq Lst # Build a flat list (uniq (mapcan '((L) (put (car L) 'dep (cdr L)) # Store dependencies in 'dep' properties (copy L) ) (mapcar uniq Lst) ) ) ) # without self-dependencies (make (while Lst (ifn (find '((This) (not (: dep))) Lst) # Found non-depending lib? (quit "Can't resolve dependencies" Lst) (del (link @) 'Lst) # Yes: Store in result (for This Lst # and remove from 'dep's (=: dep (delete @ (: dep))) ) ) ) ) )
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 a machine capable of taking the definition of any other Turing machine and executing it. Of course, you will not have an infinite tape, but you should emulate this as much as is possible. The three permissible actions on the tape are "left", "right" and "stay". To test your universal Turing machine (and prove your programming language is Turing complete!), you should execute the following two Turing machines based on the following definitions. Simple incrementer States: q0, qf Initial state: q0 Terminating states: qf Permissible symbols: B, 1 Blank symbol: B Rules: (q0, 1, 1, right, q0) (q0, B, 1, stay, qf) The input for this machine should be a tape of 1 1 1 Three-state busy beaver States: a, b, c, halt Initial state: a Terminating states: halt Permissible symbols: 0, 1 Blank symbol: 0 Rules: (a, 0, 1, right, b) (a, 1, 1, left, c) (b, 0, 1, left, a) (b, 1, 1, right, b) (c, 0, 1, left, b) (c, 1, 1, stay, halt) The input for this machine should be an empty tape. Bonus: 5-state, 2-symbol probable Busy Beaver machine from Wikipedia States: A, B, C, D, E, H Initial state: A Terminating states: H Permissible symbols: 0, 1 Blank symbol: 0 Rules: (A, 0, 1, right, B) (A, 1, 1, left, C) (B, 0, 1, right, C) (B, 1, 1, right, B) (C, 0, 1, right, D) (C, 1, 0, left, E) (D, 0, 1, left, A) (D, 1, 1, left, D) (E, 0, 1, stay, H) (E, 1, 0, left, A) The input for this machine should be an empty tape. This machine runs for more than 47 millions steps.
#VBA
VBA
Option Base 1 Public Enum sett name_ = 1 initState endState blank rules End Enum Public incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant '-- Machine definitions Private Sub init() incrementer = Array("Simple incrementer", _ "q0", _ "qf", _ "B", _ Array( _ Array("q0", "1", "1", "right", "q0"), _ Array("q0", "B", "1", "stay", "qf"))) threeStateBB = Array("Three-state busy beaver", _ "a", _ "halt", _ "0", _ Array( _ Array("a", "0", "1", "right", "b"), _ Array("a", "1", "1", "left", "c"), _ Array("b", "0", "1", "left", "a"), _ Array("b", "1", "1", "right", "b"), _ Array("c", "0", "1", "left", "b"), _ Array("c", "1", "1", "stay", "halt"))) fiveStateBB = Array("Five-state busy beaver", _ "A", _ "H", _ "0", _ Array( _ Array("A", "0", "1", "right", "B"), _ Array("A", "1", "1", "left", "C"), _ Array("B", "0", "1", "right", "C"), _ Array("B", "1", "1", "right", "B"), _ Array("C", "0", "1", "right", "D"), _ Array("C", "1", "0", "left", "E"), _ Array("D", "0", "1", "left", "A"), _ Array("D", "1", "1", "left", "D"), _ Array("E", "0", "1", "stay", "H"), _ Array("E", "1", "0", "left", "A"))) End Sub   Private Sub show(state As String, headpos As Long, tape As Collection) Debug.Print " "; state; String$(7 - Len(state), " "); "| "; For p = 1 To tape.Count Debug.Print IIf(p = headpos, "[" & tape(p) & "]", " " & tape(p) & " "); Next p Debug.Print End Sub   '-- a universal turing machine Private Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0) Dim state As String: state = machine(initState) Dim headpos As Long: headpos = 1 Dim counter As Long, rule As Variant Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), "=") If Not countOnly Then Debug.Print " State | Tape [head]" & vbCrLf & "---------------------" Do While True If headpos > tape.Count Then tape.Add machine(blank) Else If headpos < 1 Then tape.Add machine(blank), Before:=1 headpos = 1 End If End If If Not countOnly Then show state, headpos, tape For i = LBound(machine(rules)) To UBound(machine(rules)) rule = machine(rules)(i) If rule(1) = state And rule(2) = tape(headpos) Then tape.Remove headpos If headpos > tape.Count Then tape.Add rule(3) Else tape.Add rule(3), Before:=headpos End If If rule(4) = "left" Then headpos = headpos - 1 If rule(4) = "right" Then headpos = headpos + 1 state = rule(5) Exit For End If Next i counter = counter + 1 If counter Mod 100000 = 0 Then Debug.Print counter DoEvents DoEvents End If If state = machine(endState) Then Exit Do Loop DoEvents If countOnly Then Debug.Print "Steps taken: ", counter Else show state, headpos, tape Debug.Print End If End Sub   Public Sub main() init Dim tap As New Collection tap.Add "1": tap.Add "1": tap.Add "1" UTM incrementer, tap Set tap = New Collection UTM threeStateBB, tap Set tap = New Collection UTM fiveStateBB, tap, countOnly:=-1 End Sub
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 positive integer   n   that are relatively prime to   n   counts the integers   k   in the range   1 ≤ k ≤ n   for which the greatest common divisor   gcd(n,k)   is equal to   1   counts numbers   ≤ n   and   prime to   n If the totient number   (for N)   is one less than   N,   then   N   is prime. Task Create a   totient   function and:   Find and display   (1 per line)   for the 1st   25   integers:   the integer   (the index)   the totient number for that integer   indicate if that integer is prime   Find and display the   count   of the primes up to          100   Find and display the   count   of the primes up to       1,000   Find and display the   count   of the primes up to     10,000   Find and display the   count   of the primes up to   100,000     (optional) Show all output here. Related task   Perfect totient numbers Also see   Wikipedia: Euler's totient function.   MathWorld: totient function.   OEIS: Euler totient function phi(n).
#zkl
zkl
fcn totient(n){ [1..n].reduce('wrap(p,k){ p + (n.gcd(k)==1) }) } fcn isPrime(n){ totient(n)==(n - 1) }
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that 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.
#MATLAB
MATLAB
function trigExample(angleDegrees)   angleRadians = angleDegrees * (pi/180);   disp(sprintf('sin(%f)= %f\nasin(%f)= %f',[angleRadians sin(angleRadians) sin(angleRadians) asin(sin(angleRadians))])); disp(sprintf('sind(%f)= %f\narcsind(%f)= %f',[angleDegrees sind(angleDegrees) sind(angleDegrees) asind(sind(angleDegrees))])); disp('-----------------------'); disp(sprintf('cos(%f)= %f\nacos(%f)= %f',[angleRadians cos(angleRadians) cos(angleRadians) acos(cos(angleRadians))])); disp(sprintf('cosd(%f)= %f\narccosd(%f)= %f',[angleDegrees cosd(angleDegrees) cosd(angleDegrees) acosd(cosd(angleDegrees))])); disp('-----------------------'); disp(sprintf('tan(%f)= %f\natan(%f)= %f',[angleRadians tan(angleRadians) tan(angleRadians) atan(tan(angleRadians))])); disp(sprintf('tand(%f)= %f\narctand(%f)= %f',[angleDegrees tand(angleDegrees) tand(angleDegrees) atand(tand(angleDegrees))])); 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.
#J
J
preorder=: ]S:0 postorder=: ([:; postorder&.>@}.) , >@{. levelorder=: ;@({::L:1 _~ [: (/: #@>) <S:1@{::) inorder=: ([:; inorder&.>@(''"_`(1&{)@.(1<#))) , >@{. , [:; inorder&.>@}.@}.
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: 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
#jq
jq
split(",") | join(".")
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: 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
#Jsish
Jsish
puts('Hello,How,Are,You,Today'.split(',').join('.'))
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Oz
Oz
declare %% returns milliseconds fun {TimeIt Proc} Before = {Now} in {Proc} {Now} - Before end   fun {Now} {Property.get 'time.total'} end in {Show {TimeIt proc {$} {FoldL {List.number 1 1000000 1} Number.'+' 4 _} end} }
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#PARI.2FGP
PARI/GP
time(foo)={ foo(); gettime(); }