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/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
... | #Java | Java | import java.util.*;
public class TopologicalSort {
public static void main(String[] args) {
String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05,"
+ "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys";
Graph g = new Graph(s, new int[][]{
{2, 0}... |
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 ... | #Phix | Phix | with javascript_semantics
enum name, initState, endState, blank, rules
-- Machine definitions
constant incrementer = {
/*name =*/ "Simple incrementer",
/*initState =*/ "q0",
/*endState =*/ "qf",
/*blank =*/ "B",
/*rules =*/ {
{"q0", "1", "1", "right", "q0"},
{"q0", "B", "1", "stay"... |
http://rosettacode.org/wiki/Totient_function | Totient function | The totient function is also known as:
Euler's totient function
Euler's phi totient function
phi totient function
Φ function (uppercase Greek phi)
φ function (lowercase Greek phi)
Definitions (as per number theory)
The totient function:
counts the integers up to a given positiv... | #PicoLisp | PicoLisp | (gc 32)
(de gcd (A B)
(until (=0 B)
(let M (% A B)
(setq A B B M) ) )
(abs A) )
(de totient (N)
(let C 0
(for I N
(and (=1 (gcd N I)) (inc 'C)) )
(cons C (= C (dec N))) ) )
(de p? (N)
(let C 0
(for A N
(and
(cdr (totient A))
(inc 'C)... |
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that i... | #HicEst | HicEst | pi = 4.0 * ATAN(1.0)
dtor = pi / 180.0
rtod = 180.0 / pi
radians = pi / 4.0
degrees = 45.0
WRITE(ClipBoard) SIN(radians), SIN(degrees*dtor)
WRITE(ClipBoard) COS(radians), COS(degrees*dtor)
WRITE(ClipBoard) TAN(radians), TAN(degrees*dtor)
WRITE(ClipBoard) ASIN(SIN(radians)), ASIN(SIN(degrees*dtor))*rtod
WRITE(ClipBoar... |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of... | #REXX | REXX | /*REXX program implements the Trabb─Pardo-Knuth algorithm for N numbers (default is 11).*/
numeric digits 200 /*the number of digits precision to use*/
parse arg N .; if N=='' | N=="," then N=11 /*Not specified? Then use the default.*/
maxValue= 400 ... |
http://rosettacode.org/wiki/Truncatable_primes | Truncatable primes | A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.
Examples
The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.
The number 7393 is a right-truncatable prime as the numbers 7393, 7... | #Quackery | Quackery | 1000000 eratosthenes
[ false swap
number$ witheach
[ char 0 =
if [ conclude not ] ] ] is haszero ( n --> b )
[ 10 / ] is truncright ( n --> n )
[ number$
behead drop $->n drop ] is truncleft ( n --> n )
[ dup isprime not iff
[ drop false... |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ ... | #Elixir | Elixir | defmodule Tree_Traversal do
defp tnode, do: {}
defp tnode(v), do: {:node, v, {}, {}}
defp tnode(v,l,r), do: {:node, v, l, r}
defp preorder(_,{}), do: :ok
defp preorder(f,{:node,v,l,r}) do
f.(v)
preorder(f,l)
preorder(f,r)
end
defp inorder(_,{}), do: :ok
defp inorder(f,{:node,v,l,r}) do
... |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Me... | #Common_Lisp | Common Lisp | (defun comma-split (string)
(loop for start = 0 then (1+ finish)
for finish = (position #\, string :start start)
collecting (subseq string start finish)
until (null finish)))
(defun write-with-periods (strings)
(format t "~{~A~^.~}" strings)) |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Me... | #Cowgol | Cowgol | include "cowgol.coh";
include "strings.coh";
# Tokenize a string. Note: the string is modified in place.
sub tokenize(sep: uint8, str: [uint8], out: [[uint8]]): (length: intptr) is
length := 0;
loop
[out] := str;
out := @next out;
length := length + 1;
while [str] != 0 and [str... |
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 ... | #Elena | Elena | import system'calendar;
import system'routines;
import system'threading;
import system'math;
import extensions;
someProcess()
{
threadControl.sleep(1000);
new Range(0,10000).filterBy:(x => x.mod:2 == 0).summarize();
}
public program()
{
var start := now;
someProcess();
var end := now;
... |
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 ... | #Elixir | Elixir | iex(10)> :timer.tc(fn -> Enum.each(1..100000, fn x -> x*x end) end)
{236000, :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... | #Erlang | Erlang | <-module( top_rank_per_group ).
-export( [employees/0, employees_in_department/2, highest_payed/2, task/1] ).
-record( employee, {name, id, salery, department} ).
employees() ->
[#employee{name="Tyler Bennett", id="E10297", salery=32000, department="D101"},
#employee{name="John Rappl", id="E21437", s... |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedi... | #C.2B.2B | C++ |
#include <windows.h>
#include <iostream>
#include <string>
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------------------------------------
enum players { Computer, Human, ... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Bracmat | Bracmat | ( ( move
= n from to via
. !arg:(?n,?from,?to,?via)
& ( !n:>0
& move$(!n+-1,!from,!via,!to)
& out$("Move disk from pole " !from " to pole " !to)
& move$(!n+-1,!via,!to,!from)
|
)
)
& move$(4,1,2,3)
); |
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
| #NewLISP | NewLISP | (define (Thue-Morse loops)
(setf TM '(0))
(println TM)
(for (i 1 (-- loops))
(setf tmp TM)
(replace '0 tmp '_)
(replace '1 tmp '0)
(replace '_ tmp '1)
(setf TM (append TM tmp))
(println TM)
)
)
(Thue-Morse 5)
(exit)
|
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
| #Nim | Nim | import sequtils, strutils
iterator thueMorse(maxSteps = int.high): string =
var val = @[0]
var count = 0
while true:
yield val.join()
inc count
if count == maxSteps: break
val &= val.mapIt(1 - it)
for bits in thueMorse(6):
echo bits |
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping | Tokenize a string with escaping | Task[edit]
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
It should accept three input parameters:
The string
The separator character
The escape character
It should output a list of strings.
Details
Rules for splitting:
The fields that were s... | #OCaml | OCaml | let split_with_escaping ~esc ~sep s =
let len = String.length s in
let buf = Buffer.create 16 in
let rec loop i =
if i = len then [Buffer.contents buf]
else if s.[i] = esc && i + 1 < len then begin
Buffer.add_char buf s.[i + 1];
loop (i + 2)
end else if s.[i] = sep then begin
let s =... |
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
... | #JavaScript | JavaScript | const libs =
`des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
d... |
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 ... | #PHL | PHL | module turing;
extern printf;
struct @Command {
field @Integer tape {get:tape,set:stape};
field @Integer move {get:move,set:smove};
field @Integer next {get:next,set:snext};
@Command init(@Integer tape, @Integer move, @Integer next) [
this.stape(tape);
this.smove(move);
this.snext(next);
return this;
... |
http://rosettacode.org/wiki/Totient_function | Totient function | The totient function is also known as:
Euler's totient function
Euler's phi totient function
phi totient function
Φ function (uppercase Greek phi)
φ function (lowercase Greek phi)
Definitions (as per number theory)
The totient function:
counts the integers up to a given positiv... | #Python | Python | from math import gcd
def φ(n):
return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)
if __name__ == '__main__':
def is_prime(n):
return φ(n) == n - 1
for n in range(1, 26):
print(f" φ({n}) == {φ(n)}{', is prime' if is_prime(n) else ''}")
count = 0
for n in range(1, 10_000 ... |
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that i... | #IDL | IDL | deg = 35 ; arbitrary number of degrees
rad = !dtor*deg ; system variables !dtor and !radeg convert between rad and deg |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of... | #Ring | Ring |
# Project : Trabb Pardo–Knuth algorithm
decimals(3)
x = list(11)
for n=1 to 11
x[n] = n
next
s = [-5, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6]
for i = 1 to 11
see string(i) + " => " + s[i] + nl
next
see copy("-", 20) + nl
i = i - 1
while i > 0
see "f(" + string(s[i]) + ") = "
x = f(s[i])
... |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of... | #Ruby | Ruby | def f(x) x.abs ** 0.5 + 5 * x ** 3 end
puts "Please enter 11 numbers:"
nums = 11.times.map{ gets.to_f }
nums.reverse_each do |n|
print "f(#{n}) = "
res = f(n)
puts res > 400 ? "Overflow!" : res
end |
http://rosettacode.org/wiki/Truncatable_primes | Truncatable primes | A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.
Examples
The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.
The number 7393 is a right-truncatable prime as the numbers 7393, 7... | #Racket | Racket |
#lang racket
(require math/number-theory)
(define (truncate-right n)
(quotient n 10))
(define (truncate-left n)
(define s (number->string n))
(string->number (substring s 1 (string-length s))))
(define (contains-zero? n)
(member #\0 (string->list (number->string n))))
(define (truncatable? truncate n)... |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ ... | #Erlang | Erlang | -module(tree_traversal).
-export([main/0]).
-export([preorder/2, inorder/2, postorder/2, levelorder/2]).
-export([tnode/0, tnode/1, tnode/3]).
-define(NEWLINE, io:format("~n")).
tnode() -> {}.
tnode(V) -> {node, V, {}, {}}.
tnode(V,L,R) -> {node, V, L, R}.
preorder(_,{}) -> ok;
preorder(F,{node,V,L,R}) ->
F(... |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Me... | #Crystal | Crystal | puts "Hello,How,Are,You,Today".split(',').join('.') |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Me... | #D | D | void main() {
import std.stdio, std.string;
"Hello,How,Are,You,Today".split(',').join('.').writeln;
} |
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 ... | #Erlang | Erlang |
5> {Time,Result} = timer:tc(fun () -> lists:foreach(fun(X) -> X*X end, lists:seq(1,100000)) end).
{226391,ok}
6> Time/1000000. % Time is in microseconds.
0.226391
7> % Time is in microseconds.
|
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 ... | #Euphoria | Euphoria | atom t
t = time()
some_procedure()
t = time() - t
printf(1,"Elapsed %f seconds.\n",t) |
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... | #F.23 | F# | let data =
[
"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,... |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedi... | #Common_Lisp | Common Lisp |
(defun generate-board ()
(loop repeat 9 collect nil))
(defparameter *straights* '((1 2 3) (4 5 6) (7 8 9) (1 4 7) (2 5 8) (3 6 9) (1 5 9) (3 5 7)))
(defparameter *current-player* 'x)
(defun get-board-elt (n board)
(nth (1- n) board))
(defun legal-p (n board)
(null (get-board-elt n board)))
(defun set-bo... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Brainf.2A.2A.2A | Brainf*** | [
This implementation is recursive and uses
a stack, consisting of frames that are 8
bytes long. The layout is as follows:
Byte Description
0 recursion flag
(the program stops if the flag is
zero)
1 the step which is currently
executed
4 means a call to
move(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
| #OASYS_Assembler | OASYS Assembler | ; Thue-Morse sequence
[*'A] ; Ensure the vocabulary is not empty
[&] ; Declare the initialization procedure
%#1> ; Initialize length counter
%@*> ; Create first object
,#1> ; Initialize loop counter
: ; Begin loop
%@<.#<PI ... |
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
| #Objeck | Objeck | class ThueMorse {
function : Main(args : String[]) ~ Nil {
Sequence(6);
}
function : Sequence(steps : Int) ~ Nil {
sb1 := "0";
sb2 := "1";
for(i := 0; i < steps; i++;) {
tmp := String->New(sb1);
sb1 += sb2;
sb2 += tmp;
};
sb1->PrintLine();
}
}
|
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping | Tokenize a string with escaping | Task[edit]
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
It should accept three input parameters:
The string
The separator character
The escape character
It should output a list of strings.
Details
Rules for splitting:
The fields that were s... | #Perl | Perl | sub tokenize {
my ($string, $sep, $esc) = (shift, quotemeta shift, quotemeta shift);
my @fields = split /$esc . (*SKIP)(*FAIL) | $sep/sx, $string, -1;
return map { s/$esc(.)/$1/gsr } @fields;
} |
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
... | #jq | jq | # independent/0 emits an array of the dependencies that have no dependencies
# Input: an object representing a normalized dependency graph
def independent:
. as $G
| reduce keys[] as $key
([];
. + ((reduce $G[$key][] as $node
([];
if ($G[$node] == null or ($G[$node]|len... |
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 ... | #PicoLisp | PicoLisp | # Finite state machine
(de turing (Tape Init Halt Blank Rules Verbose)
(let
(Head 1
State Init
Rule NIL
S 'start
C (length Tape))
(catch NIL
(loop
(state 'S
(start 'print
(when (=0 C)
(setq Ta... |
http://rosettacode.org/wiki/Totient_function | Totient function | The totient function is also known as:
Euler's totient function
Euler's phi totient function
phi totient function
Φ function (uppercase Greek phi)
φ function (lowercase Greek phi)
Definitions (as per number theory)
The totient function:
counts the integers up to a given positiv... | #Quackery | Quackery | [ [ dup while
tuck mod again ]
drop abs ] is gcd ( n n --> n )
[ 0 swap dup times
[ i over gcd
1 = rot + swap ]
drop ] is totient ( n --> n )
[ 0 temp put
times
[ i dup 1+ totient
= temp tally ]
temp take ] ... |
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that i... | #Icon_and_Unicon | Icon and Unicon | invocable all
procedure main()
d := 30 # degrees
r := dtor(d) # convert to radians
every write(f := !["sin","cos","tan"],"(",r,")=",y := f(r)," ",fi := "a" || f,"(",y,")=",x := fi(y)," rad = ",rtod(x)," deg")
end |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of... | #Rust | Rust |
use std::io::{self, BufRead};
fn op(x: f32) -> Option<f32> {
let y = x.abs().sqrt() + 5.0 * x * x * x;
if y < 400.0 {
Some(y)
} else {
None
}
}
fn main() {
println!("Please enter 11 numbers (one number per line)");
let stdin = io::stdin();
let xs = stdin
.lock... |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of... | #Scala | Scala | object TPKa extends App {
final val numbers = scala.collection.mutable.MutableList[Double]()
final val in = new java.util.Scanner(System.in)
while (numbers.length < CAPACITY) {
print("enter a number: ")
try {
numbers += in.nextDouble()
}
catch {
case _... |
http://rosettacode.org/wiki/Truncatable_primes | Truncatable primes | A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.
Examples
The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.
The number 7393 is a right-truncatable prime as the numbers 7393, 7... | #Raku | Raku | constant ltp = $[2, 3, 5, 7], -> @ltp {
$[ grep { .&is-prime }, ((1..9) X~ @ltp) ]
} ... *;
constant rtp = $[2, 3, 5, 7], -> @rtp {
$[ grep { .&is-prime }, (@rtp X~ (1..9)) ]
} ... *;
say "Highest ltp = ", ltp[5][*-1];
say "Highest rtp = ", rtp[5][*-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
/ ... | #Euphoria | Euphoria | constant VALUE = 1, LEFT = 2, RIGHT = 3
constant tree = {1,
{2,
{4,
{7, 0, 0},
0},
{5, 0, 0}},
{3,
{6,
{8, 0, 0},
... |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Me... | #Delphi | Delphi |
program Tokenize_a_string;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
var
Words: TArray<string>;
begin
Words := 'Hello,How,Are,You,Today'.Split([',']);
Writeln(string.Join(#10, Words));
Readln;
end.
|
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Me... | #Dyalect | Dyalect | var str = "Hello,How,Are,You,Today"
var strings = str.Split(',')
print(values: strings, separator: ".") |
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 ... | #F.23 | F# |
open System.Diagnostics
let myfunc data =
let timer = new Stopwatch()
timer.Start()
let result = data |> expensive_processing
timer.Stop()
printf "elapsed %d ms" timer.ElapsedMilliseconds
result
|
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 ... | #Factor | Factor | USING: kernel sequences tools.time ;
[ 10000 <iota> sum drop ] time |
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... | #Factor | Factor | USING: accessors assocs fry io kernel math.parser sequences
sorting ;
IN: top-rank
TUPLE: employee name id salary department ;
CONSTANT: employees {
T{ employee f "Tyler Bennett" "E10297" 32000 "D101" }
T{ employee f "John Rappl" "E21437" 47000 "D050" }
T{ employee f "George Woltman" "E00127... |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedi... | #D | D | import std.stdio, std.string, std.algorithm, std.conv, std.random,
std.ascii, std.array, std.range, std.math;
struct GameBoard {
dchar[9] board = "123456789";
enum : dchar { human = 'X', computer = 'O' }
enum Game { going, humanWins, computerWins, draw }
const pure nothrow @safe @nogc invaria... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #C | C | #include <stdio.h>
void move(int n, int from, int via, int to)
{
if (n > 1) {
move(n - 1, from, to, via);
printf("Move disk from pole %d to pole %d\n", from, to);
move(n - 1, via, from, to);
} else {
printf("Move disk from pole %d to pole %d\n", from, to);
}
}
int main()
{
move(4, 1,2,3);
re... |
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
| #OCaml | OCaml | (* description: Counts the number of bits set to 1
input: the number to have its bit counted
output: the number of bits set to 1 *)
let count_bits v =
let rec aux c v =
if v <= 0 then c
else aux (c + (v land 1)) (v lsr 1)
in
aux 0 v
let () =
for i = 0 to pred 256 do
print_char (
... |
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
| #Pascal | Pascal | Program ThueMorse;
function fThueMorse(maxLen: NativeInt):AnsiString;
//double by appending the flipped original 0 -> 1;1 -> 0
//Flipping between two values:x oszillating A,B,A,B -> x_next = A+B-x
//Beware A+B < High(Char), the compiler will complain ...
const
cVal0 = '^';cVal1 = 'v';// cVal0 = '0';cVal1 = '1';
... |
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping | Tokenize a string with escaping | Task[edit]
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
It should accept three input parameters:
The string
The separator character
The escape character
It should output a list of strings.
Details
Rules for splitting:
The fields that were s... | #Phix | Phix | function tokenize(string s, integer sep, integer esc)
sequence ret = {}
string word = ""
integer skip = 0
if length(s)!=0 then
for i=1 to length(s) do
integer si = s[i]
if skip then
word &= si
skip = 0
elsif si=esc then
sk... |
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
... | #Julia | Julia | function toposort(data::Dict{T,Set{T}}) where T
data = copy(data)
for (k, v) in data
delete!(v, k)
end
extraitems = setdiff(reduce(∪, values(data)), keys(data))
for item in extraitems
data[item] = Set{T}()
end
rst = Vector{T}()
while true
ordered = Set(item for (i... |
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 ... | #Prolog | Prolog | turing(Config, Rules, TapeIn, TapeOut) :-
call(Config, IS, _, _, _, _),
perform(Config, Rules, IS, {[], TapeIn}, {Ls, Rs}),
reverse(Ls, Ls1),
append(Ls1, Rs, TapeOut).
perform(Config, Rules, State, TapeIn, TapeOut) :-
call(Config, _, FS, RS, B, Symbols),
( memberchk(State, FS) ->
TapeO... |
http://rosettacode.org/wiki/Totient_function | Totient function | The totient function is also known as:
Euler's totient function
Euler's phi totient function
phi totient function
Φ function (uppercase Greek phi)
φ function (lowercase Greek phi)
Definitions (as per number theory)
The totient function:
counts the integers up to a given positiv... | #Racket | Racket | #lang racket
(require math/number-theory)
(define (prime*? n) (= (totient n) (sub1 n)))
(for ([n (in-range 1 26)])
(printf "φ(~a) = ~a~a~a\n"
n
(totient n)
(if (prime*? n) " is prime" "")
(if (prime? n) " (confirmed)" "")))
(for/fold ([count 0] #:result (void)) ([n (in-... |
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that i... | #J | J | (1&o. , 2&o. ,: 3&o.) (4 %~ o. 1) , 180 %~ o. 45
0.707107 0.707107
0.707107 0.707107
1 1 |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of... | #Sidef | Sidef | var nums; do {
nums = Sys.readln("Please type 11 space-separated numbers: ").nums
} while(nums.len != 11)
nums.reverse.each { |n|
var r = (n.abs.sqrt + (5 * n**3));
say "#{n}\t#{ r > 400 ? 'Urk!' : r }";
} |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of... | #Sinclair_ZX81_BASIC | Sinclair ZX81 BASIC | 10 DIM A(11)
20 PRINT "ENTER ELEVEN NUMBERS:"
30 FOR I=1 TO 11
40 INPUT A(I)
50 NEXT I
60 FOR I=11 TO 1 STEP -1
70 LET Y=SQR ABS A(I)+5*A(I)**3
80 IF Y<=400 THEN GOTO 110
90 PRINT A(I),"TOO LARGE"
100 GOTO 120
110 PRINT A(I),Y
120 NEXT I |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of... | #Swift | Swift | import Foundation
print("Enter 11 numbers for the Trabb─Pardo─Knuth algorithm:")
let f: (Double) -> Double = { sqrt(fabs($0)) + 5 * pow($0, 3) }
(1...11)
.generate()
.map { i -> Double in
print("\(i): ", terminator: "")
guard let s = readLine(), let n = Double(s) else { return 0 }
... |
http://rosettacode.org/wiki/Truncatable_primes | Truncatable primes | A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.
Examples
The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.
The number 7393 is a right-truncatable prime as the numbers 7393, 7... | #REXX | REXX | /*REXX program finds largest left─ and right─truncatable primes ≤ 1m (or argument 1).*/
parse arg hi .; if hi=='' then hi= 1000000 /*Not specified? Then use default of 1m*/
call genP /*generate some primes, about hi ÷ 2 */
... |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ ... | #F.23 | F# | open System
open System.IO
type Tree<'a> =
| Tree of 'a * Tree<'a> * Tree<'a>
| Empty
let rec inorder tree =
seq {
match tree with
| Tree(x, left, right) ->
yield! inorder left
yield x
yield! inorder right
| Empty -> ()
}
let ... |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Me... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | !print join "." split "Hello,How,Are,You,Today" "," |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Me... | #E | E | ".".rjoin("Hello,How,Are,You,Today".split(",")) |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could ... | #Forth | Forth | : time: ( "word" -- )
utime 2>R ' EXECUTE
utime 2R> D-
<# # # # # # # [CHAR] . HOLD #S #> TYPE ." seconds" ;
1000 time: MS \ 1.000081 seconds ok |
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 ... | #Fortran | Fortran |
c The subroutine to analyze
subroutine do_something()
c For testing we just do nothing for 3 seconds
call sleep(3)
return
end
c Main Program
program timing
integer(kind=8) start,finish,rate
call system_clock(count_rate=rate)
call system_clock(start)
c Here co... |
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... | #Forth | Forth |
\ Written in ANS-Forth; tested under VFX.
\ Requires the novice package: http://www.forth.org/novice.html
\ The following should already be done:
\ include novice.4th
\ include list.4th
marker TopRank.4th
\ This demonstrates how I typically use lists. A program such as this does not need any explicit iteration, s... |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedi... | #EasyLang | EasyLang | len f[] 9
state = 0
textsize 14
#
func init . .
linewidth 2
clear
color 666
move 34 4
line 34 80
move 62 4
line 62 80
move 10 28
line 86 28
move 10 56
line 86 56
linewidth 2.5
for i range 9
f[i] = 0
.
if state = 1
timer 0.2
.
.
func draw ind . .
c = ind mod 3
r = ind div 3
... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #C.23 | C# | public void move(int n, int from, int to, int via) {
if (n == 1) {
System.Console.WriteLine("Move disk from pole " + from + " to pole " + to);
} else {
move(n - 1, from, via, to);
move(1, from, to, via);
move(n - 1, via, to, from);
}
} |
http://rosettacode.org/wiki/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
| #Perl | Perl | sub complement
{
my $s = shift;
$s =~ tr/01/10/;
return $s;
}
my $str = '0';
for (0..6) {
say $str;
$str .= complement($str);
}
|
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
| #Phix | Phix | string tm = "0"
for i=1 to 8 do
printf(1,"%s\n",tm)
tm &= sq_sub('0'+'1',tm)
end for
|
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping | Tokenize a string with escaping | Task[edit]
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
It should accept three input parameters:
The string
The separator character
The escape character
It should output a list of strings.
Details
Rules for splitting:
The fields that were s... | #PicoLisp | PicoLisp | (de tokenize (Str Sep Esc)
(split
(make
(for (L (chop Str) L)
(let C (pop 'L)
(cond
((= C Esc) (link (pop 'L)))
((= C Sep) (link 0))
(T (link C)) ) ) ) )
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 s... | #PowerShell | PowerShell |
function Split-String ([string]$String, [char]$Separator, [char]$Escape)
{
if ($String -notmatch "\$Separator|\$Escape") {return $String}
[bool]$escaping = $false
[string]$output = ""
for ($i = 0; $i -lt $String.Length; $i++)
{
[char]$character = $String.Substring($i,1)
if (... |
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
... | #Kotlin | Kotlin | // version 1.1.51
val s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05, " +
"dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys"
val deps = mutableListOf(
2 to 0, 2 to 14, 2 to 13, 2 to 4, 2 to 3, 2 to 12, 2 to 1,
3 to 1, 3 to 10, 3 to 11,
4 to 1, 4 to 10,
5 to 0, 5 to ... |
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 ... | #Python | Python | from __future__ import print_function
def run_utm(
state = None,
blank = None,
rules = [],
tape = [],
halt = None,
pos = 0):
st = state
if not tape: tape = [blank]
if pos < 0: pos += len(tape)
if pos >= len(tape) or pos < 0: raise Error( "bad init positi... |
http://rosettacode.org/wiki/Totient_function | Totient function | The totient function is also known as:
Euler's totient function
Euler's phi totient function
phi totient function
Φ function (uppercase Greek phi)
φ function (lowercase Greek phi)
Definitions (as per number theory)
The totient function:
counts the integers up to a given positiv... | #Raku | Raku | use Prime::Factor;
my \𝜑 = 0, |(1..*).hyper.map: -> \t { t * [*] t.&prime-factors.squish.map: { 1 - 1/$_ } }
printf "𝜑(%2d) = %3d %s\n", $_, 𝜑[$_], $_ - 𝜑[$_] - 1 ?? '' !! 'Prime' for 1 .. 25;
(1e2, 1e3, 1e4, 1e5).map: -> $limit {
say "\nCount of primes <= $limit: " ~ +(^$limit).grep: {$_ == 𝜑[$_] + 1}
} |
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that i... | #Java | Java | public class Trig {
public static void main(String[] args) {
//Pi / 4 is 45 degrees. All answers should be the same.
double radians = Math.PI / 4;
double degrees = 45.0;
//sine
System.out.println(Math.sin(radians) + " " + Math.sin(M... |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of... | #Symsyn | Symsyn |
|Trabb Pardo–Knuth algorithm
a : 11 0
i
if i LE 10
[] $s
~ $s w
w a.i
+ i
goif
endif
10 i
if i GE 0
call f
if x GT 400
'too large' $s
else
~ x $s
endif
~ i $r
+ ' ' $r
+ $r $s.1
$s []
- i
goif
endif
stop
f a.i t
* t t x
* x t x
... |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of... | #Tcl | Tcl | # Helper procedures
proc f {x} {expr {abs($x)**0.5 + 5*$x**3}}
proc overflow {y} {expr {$y > 400}}
# Read in 11 numbers, with nice prompting
fconfigure stdout -buffering none
for {set n 1} {$n <= 11} {incr n} {
puts -nonewline "number ${n}: "
lappend S [scan [gets stdin] "%f"]
}
# Process and print results ... |
http://rosettacode.org/wiki/Truncatable_primes | Truncatable primes | A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.
Examples
The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.
The number 7393 is a right-truncatable prime as the numbers 7393, 7... | #Ring | Ring |
# Project : Truncatable primes
for n = 1000000 to 1 step -1
flag = 1
flag2 = 1
strn = string(n)
for nr = 1 to len(strn)
if strn[nr] = "0"
flag2 = 0
ok
next
if flag2 = 1
for m = 1 to len(strn)
strp = right(strn, m)
if isprime(number(strp... |
http://rosettacode.org/wiki/Truncatable_primes | Truncatable primes | A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.
Examples
The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.
The number 7393 is a right-truncatable prime as the numbers 7393, 7... | #Ruby | Ruby | def left_truncatable?(n)
truncatable?(n) {|i| i.to_s[1..-1].to_i}
end
def right_truncatable?(n)
truncatable?(n) {|i| i/10}
end
def truncatable?(n, &trunc_func)
return false if n.to_s.include? "0"
loop do
n = trunc_func.call(n)
return true if n.zero?
return false unless Prime.prime?(n)
end
en... |
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
/ ... | #Factor | Factor | USING: accessors combinators deques dlists fry io kernel
math.parser ;
IN: rosetta.tree-traversal
TUPLE: node data left right ;
CONSTANT: example-tree
T{ node f 1
T{ node f 2
T{ node f 4
T{ node f 7 f f }
f
}
T{ node f 5 f f }
}... |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Me... | #Elena | Elena | import system'routines;
import extensions;
public program()
{
var string := "Hello,How,Are,You,Today";
string.splitBy:",".forEach:(s)
{
console.print(s,".")
}
} |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Me... | #Elixir | Elixir |
tokens = String.split("Hello,How,Are,You,Today", ",")
IO.puts Enum.join(tokens, ".")
|
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 ... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function sumToLimit(limit As UInteger) As UInteger
Dim sum As UInteger = 0
For i As UInteger = 1 To limit
sum += i
Next
Return sum
End Function
Dim As Double start = timer
Dim limit As UInteger = 100000000
Dim result As UInteger = sumToLimit(limit)
Dim ms As UInteger = Int(1000 * (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 ... | #GAP | GAP | # Return the time passed in last function
time; |
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... | #Fortran | Fortran | DATA EMPLOYEE(1:3)/
1 GRIST("Tyler Bennett","E10297",32000,"D101"),
2 GRIST("John Rappl","E21437",47000,"D050"),
3 GRIST("George Woltman","E00127",53500,"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.
Wikipedi... | #Erlang | Erlang |
-module(tic_tac_toe).
-export( [task/0] ).
task() -> io:fwrite( "Result: ~p.~n", [turn(player(random:uniform()), board())] ).
board() -> [{X, erlang:integer_to_list(X)} || X <- lists:seq(1, 9)].
board_tuples( Selections, Board ) -> [lists:keyfind(X, 1, Board) || X <- Selections].
computer_move( Player, ... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #C.2B.2B | C++ | void move(int n, int from, int to, int via) {
if (n == 1) {
std::cout << "Move disk from pole " << from << " to pole " << to << std::endl;
} else {
move(n - 1, from, via, to);
move(1, from, to, via);
move(n - 1, via, to, from);
}
} |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #Phixmonti | Phixmonti | def inverte
dup len
for
var i
i get not i set
endfor
enddef
0 1 tolist
8 for
.
dup print nl nl
inverte chain
endfor |
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
| #PHP | PHP | <?php
function thueMorseSequence($length) {
$sequence = '';
for ($digit = $n = 0 ; $n < $length ; $n++) {
$x = $n ^ ($n - 1);
if (($x ^ ($x >> 1)) & 0x55555555) {
$digit = 1 - $digit;
}
$sequence .= $digit;
}
return $sequence;
}
for ($n = 10 ; $n <= 100 ; ... |
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping | Tokenize a string with escaping | Task[edit]
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
It should accept three input parameters:
The string
The separator character
The escape character
It should output a list of strings.
Details
Rules for splitting:
The fields that were s... | #Python | Python | def token_with_escape(a, escape = '^', separator = '|'):
'''
Issue python -m doctest thisfile.py to run the doctests.
>>> print(token_with_escape('one^|uno||three^^^^|four^^^|^cuatro|'))
['one|uno', '', 'three^^', 'four^|cuatro', '']
'''
result = []
token = ''
state = 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 s... | #Racket | Racket | #lang racket/base
(require racket/match)
;; Returns a tokenising function based on sep and esc
(define ((tokenise-with-escape sep esc) str)
(define tsil->string (compose list->string reverse))
(define (inr rem l-acc acc)
(match rem
['() (if (and (null? acc) (null? l-acc)) null (reverse (cons (tsil->stri... |
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
... | #M2000_Interpreter | M2000 Interpreter | Module testthis {
\\ empty stack
Flush
inventory LL
append LL, "des_system_lib":=(List:="std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee")
REM append LL, "dw01":=(List:="dw04","ieee", "dw01", "dware", "gtech")
append LL, "dw01":=(List:="ieee", "dw01", "dware", "gtech")
append ... |
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 ... | #Racket | Racket |
#lang racket
;;;=============================================================
;;; Due to heavy use of pattern matching we define few macros
;;;=============================================================
(define-syntax-rule (define-m f m ...)
(define f (match-lambda m ... (x x))))
(define-syntax-rule (define-m... |
http://rosettacode.org/wiki/Totient_function | Totient function | The totient function is also known as:
Euler's totient function
Euler's phi totient function
phi totient function
Φ function (uppercase Greek phi)
φ function (lowercase Greek phi)
Definitions (as per number theory)
The totient function:
counts the integers up to a given positiv... | #REXX | REXX | /*REXX program calculates the totient numbers for a range of numbers, and count primes. */
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 25 /*Not specified? Then use the default.*/
tell= N>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 i... | #JavaScript | JavaScript | var
radians = Math.PI / 4, // Pi / 4 is 45 degrees. All answers should be the same.
degrees = 45.0,
sine = Math.sin(radians),
cosine = Math.cos(radians),
tangent = Math.tan(radians),
arcsin = Math.asin(sine),
arccos = Math.acos(cosine),
arctan = Math.atan(tangent);
// sine
window.alert(sine + " " + Math.sin(d... |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of... | #VBScript | VBScript |
Function tpk(s)
arr = Split(s," ")
For i = UBound(arr) To 0 Step -1
n = fx(CDbl(arr(i)))
If n > 400 Then
WScript.StdOut.WriteLine arr(i) & " = OVERFLOW"
Else
WScript.StdOut.WriteLine arr(i) & " = " & n
End If
Next
End Function
Function fx(x)
fx = Sqr(Abs(x))+5*x^3
End Function
'testing the func... |
http://rosettacode.org/wiki/Truncatable_primes | Truncatable primes | A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.
Examples
The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.
The number 7393 is a right-truncatable prime as the numbers 7393, 7... | #Rust | Rust | fn is_prime(n: u32) -> bool {
if n < 2 {
return false;
}
if n % 2 == 0 {
return n == 2;
}
if n % 3 == 0 {
return n == 3;
}
let mut p = 5;
while p * p <= n {
if n % p == 0 {
return false;
}
p += 2;
if n % p == 0 {
... |
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
/ ... | #Fantom | Fantom |
class Tree
{
readonly Int label
readonly Tree? left
readonly Tree? right
new make (Int label, Tree? left := null, Tree? right := null)
{
this.label = label
this.left = left
this.right = right
}
Void preorder(|Int->Void| func)
{
func(label)
left?.preorder(func) // ?. will not ca... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.