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/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... | #E | E | def pi := (-1.0).acos()
def radians := pi / 4.0
def degrees := 45.0
def d2r := (pi/180).multiply
def r2d := (180/pi).multiply
println(`$\
${radians.sin()} ${d2r(degrees).sin()}
${radians.cos()} ${d2r(degrees).cos()}
${radians.tan()} ${d2r(degrees).tan()}
${def asin := radians.sin().asin()} ${r2d(asin)}
${def acos... |
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... | #jq | jq | def f:
def abs: if . < 0 then -. else . end;
def power(x): (x * log) | exp;
. as $x | abs | power(0.5) + (5 * (.*.*. ));
. as $in | split(" ") | map(tonumber)
| if length == 11 then
reverse | map(f | if . > 400 then "TOO LARGE" else . end)
else error("The number of numbers was not 11.")
end
| .[] # p... |
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... | #Julia | Julia | f(x) = √abs(x) + 5x^3
for i in reverse(split(readline()))
v = f(parse(Int, i))
println("$(i): ", v > 400 ? "TOO LARGE" : v)
end |
http://rosettacode.org/wiki/Twelve_statements | Twelve statements | This puzzle is borrowed from math-frolic.blogspot.
Given the following twelve statements, which of them are true?
1. This is a numbered list of twelve statements.
2. Exactly 3 of the last 6 statements are true.
3. Exactly 2 of the even-numbered statements are true.
4. If statement 5 is true, then statemen... | #Yabasic | Yabasic | sub s1() return len(s$)=12 end sub
sub s2() local t, i : t=0 : for i=7 to 12 : t = t + (mid$(s$, i, 1) <> "0") : next : return t=3 end sub
sub s3() local t, i : t=0 : for i=2 to 12 step 2 : t = t + (mid$(s$, i, 1) <> "0") : next : return t=2 end sub
sub s4() return mid$(s$, 5, 1) = "0" or (mid$(s$, 6, 1) <> "0" and mid... |
http://rosettacode.org/wiki/Twelve_statements | Twelve statements | This puzzle is borrowed from math-frolic.blogspot.
Given the following twelve statements, which of them are true?
1. This is a numbered list of twelve statements.
2. Exactly 3 of the last 6 statements are true.
3. Exactly 2 of the even-numbered statements are true.
4. If statement 5 is true, then statemen... | #zkl | zkl | var statements; // list of 13 Bools, statements[0] is garbage to make 1 based
fcn s0 { False } // dummy for padding
fcn s1 { True }
fcn s2 { statements[-6,*].filter().len()==3 }
fcn s3 { [2..12,2].apply(statements.get).filter().len()==2 }
fcn s4 { if(statements[5]) statements[6]==statements[7]==True else True }
fcn s5... |
http://rosettacode.org/wiki/Truth_table | Truth table | A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.
Task
Input a Boolean function from the user as a string then calculate and print a formatted truth table for the g... | #Raku | Raku | use MONKEY-SEE-NO-EVAL;
sub MAIN ($x) {
my @n = $x.comb(/<ident>/);
my &fun = EVAL "-> {('\\' «~« @n).join(',')} \{ [{ (|@n,"so $x").join(',') }] \}";
say (|@n,$x).join("\t");
.join("\t").say for map &fun, flat map { .fmt("\%0{+@n}b").comb».Int».so }, 0 ..^ 2**@n;
say '';
} |
http://rosettacode.org/wiki/Ulam_spiral_(for_primes) | Ulam spiral (for primes) | An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1), constructed on a square grid, starting at the "center".
An Ulam spiral is also known as a prime spiral.
The first grid (green) is shown with sequential integers, ... | #Ruby | Ruby | require 'prime'
def cell(n, x, y, start=1)
y, x = y - n/2, x - (n - 1)/2
l = 2 * [x.abs, y.abs].max
d = y >= x ? l*3 + x + y : l - x - y
(l - 1)**2 + d + start - 1
end
def show_spiral(n, symbol=nil, start=1)
puts "\nN : #{n}"
format = "%#{(start + n*n - 1).to_s.size}s "
n.times do |y|
n.times do |... |
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... | #Maple | Maple |
MaxTruncatablePrime := proc({left::truefalse:=FAIL, right::truefalse:=FAIL}, $)
local i, j, c, p, b, n, sdprimes, dir;
local tprimes := table();
if left = true and right = true then
error "invalid input";
elif right = true then
dir := "right";
else
dir := "left";
end if;
b ... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | LeftTruncatablePrimeQ[n_] := Times @@ IntegerDigits[n] > 0 &&
And @@ PrimeQ /@ ToExpression /@ StringJoin /@
Rest[Most[NestList[Rest, #, Length[#]] &[Characters[ToString[n]]]]]
RightTruncatablePrimeQ[n_] := Times @@ IntegerDigits[n] > 0 &&
And @@ PrimeQ /@ ToExpression /@ StringJoin /@
Rest[Most[NestL... |
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
/ ... | #C.2B.2B | C++ | #include <boost/scoped_ptr.hpp>
#include <iostream>
#include <queue>
template<typename T>
class TreeNode {
public:
TreeNode(const T& n, TreeNode* left = NULL, TreeNode* right = NULL)
: mValue(n),
mLeft(left),
mRight(right) {}
T getValue() const {
return mValue;
}
TreeNode* left() const... |
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... | #ALGOL_68 | ALGOL 68 | main:(
OP +:= = (REF FLEX[]STRING in out, STRING item)VOID:(
[LWB in out: UPB in out+1]STRING new;
new[LWB in out: UPB in out]:=in out;
new[UPB new]:=item;
in out := new
);
PROC string split = (REF STRING beetles, STRING substr)[]STRING:(
""" Split beetles where substr is found """;
F... |
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 ... | #11l | 11l | F do_work(x)
V n = x
L(i) 10000000
n += i
R n
F time_func(f)
V start = time:perf_counter()
f()
R time:perf_counter() - start
print(time_func(() -> do_work(100))) |
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... | #Bracmat | Bracmat | (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)
... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #AppleScript | AppleScript | --------------------- TOWERS OF HANOI --------------------
-- hanoi :: Int -> (String, String, String) -> [(String, String)]
on hanoi(n, abc)
script go
on |λ|(n, {x, y, z})
if n > 0 then
set m to n - 1
|λ|(m, {x, z, y}) & ¬
{{x, y}} & |λ|(m... |
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
| #CLU | CLU | % Yields an infinite Thue-Morse sequence, digit by digit
tm = iter () yields (char)
n: int := 1
s: string := "0"
while true do
while n <= string$size(s) do
yield(s[n])
n := n + 1
end
s2: array[char] := array[char]$[]
for c: char in string$chars(s) do
... |
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
| #Common_Lisp | Common Lisp | (defun bit-complement (bit-vector)
(loop with result = (make-array (length bit-vector) :element-type 'bit)
for b across bit-vector
for i from 0
do (setf (aref result i) (- 1 b))
finally (return result)))
(defun next (bit-vector)
(concatenate 'bit-vector bit-vector (bit-complement b... |
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm | Tonelli-Shanks algorithm |
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computational number theory, the Tonelli–Shanks algor... | #J | J | leg=: dyad define
x (y&|)@^ (y-1)%2
)
tosh=:dyad define
assert. 1=1 p: y [ 'y must be prime'
assert. 1=x leg y [ 'x must be square mod y'
pow=. y&|@^
if. 1=m=. {.1 q: y-1 do.
r=. x pow (y+1)%4
else.
z=. 1x while. 1>: z leg y do. z=.z+1 end.
c=. z pow q=. (y-1)%2^m
r=. x pow (q+1)%2
t=... |
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... | #D | D | import std.stdio;
void main() {
string sample = "one^|uno||three^^^^|four^^^|^cuatro|";
writeln(sample);
writeln(tokenizeString(sample, '|', '^'));
}
auto tokenizeString(string source, char seperator, char escape) {
import std.array : appender;
import std.exception : enforce;
auto output... |
http://rosettacode.org/wiki/Total_circles_area | Total circles area | Total circles area
You are encouraged to solve this task according to the task description, using any language you may know.
Example circles
Example circles filtered
Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal dig... | #Phix | Phix | with javascript_semantics
constant circles = {{ 1.6417233788, 1.6121789534, 0.0848270516},
{-1.4944608174, 1.2077959613, 1.1039549836},
{ 0.6110294452, -0.6907087527, 0.9089162485},
{ 0.3844862411, 0.2923344616, 0.2375743054},
{-0.249589... |
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
... | #E | E | def makeQueue := <elib:vat.makeQueue>
def topoSort(data :Map[any, Set[any]]) {
# Tables of nodes and edges
def forwardEdges := [].asMap().diverge()
def reverseCount := [].asMap().diverge()
def init(node) {
reverseCount[node] := 0
forwardEdges[node] := [].asSet().diverge()
}
for n... |
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 ... | #JavaScript | JavaScript | function tm(d,s,e,i,b,t,... r) {
document.write(d, '<br>')
if (i<0||i>=t.length) return
var re=new RegExp(b,'g')
write('*',s,i,t=t.split(''))
var p={}; r.forEach(e=>((s,r,w,m,n)=>{p[s+'.'+r]={w,n,m:[0,1,-1][1+'RL'.indexOf(m)]}})(... e.split(/[ .:,]+/)))
for (var n=1; s!=e; n+=1) {
with (p[s+'.'+t[i]]) t[i]=w,s=... |
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... | #Haskell | Haskell | {-# LANGUAGE BangPatterns #-}
import Control.Monad (when)
import Data.Bool (bool)
totient
:: (Integral a)
=> a -> a
totient n
| n == 0 = 1 -- by definition phi(0) = 1
| n < 0 = totient (-n) -- phi(-n) is taken to be equal to phi(n)
| otherwise = loop n n 2 --
where
loop !m !tot !i
| i * i > m ... |
http://rosettacode.org/wiki/Topswops | Topswops | Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is composed of reversing the first ... | #Picat | Picat | go ?=>
member(N,1..10),
Perm = 1..N,
Rev = Perm.reverse(),
Max = 0,
while(Perm != Rev)
next_permutation(Perm),
C = topswops(Perm),
if C > Max then
Max := C
end
end,
printf("%2d: %2d\n",N,Max),
fail,
nl.
go => true.
topswops([]) = 0 => true.
topswops([1]) = 0 => true.
topswop... |
http://rosettacode.org/wiki/Topswops | Topswops | Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is composed of reversing the first ... | #PicoLisp | PicoLisp | (de fannkuch (N)
(let (Lst (range 1 N) L Lst Max)
(recur (L) # Permute
(if (cdr L)
(do (length L)
(recurse (cdr L))
(rot L) )
(zero N) # For each permutation
(for (P (copy Lst) (> (car P) 1) (flip P (car P)))
(inc '... |
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... | #Elena | Elena | import system'math;
import extensions;
public program()
{
console.printLine("Radians:");
console.printLine("sin(π/3) = ",(Pi_value/3).sin());
console.printLine("cos(π/3) = ",(Pi_value/3).cos());
console.printLine("tan(π/3) = ",(Pi_value/3).tan());
console.printLine("arcsin(1/2) = ",0.5r.arcsin());... |
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... | #Kotlin | Kotlin | // version 1.1.2
fun f(x: Double) = Math.sqrt(Math.abs(x)) + 5.0 * x * x * x
fun main(args: Array<String>) {
val da = DoubleArray(11)
println("Please enter 11 numbers:")
var i = 0
while (i < 11) {
print(" ${"%2d".format(i + 1)}: ")
val d = readLine()!!.toDoubleOrNull()
if (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... | #Ksh | Ksh |
#!/bin/ksh
# Trabb Pardo–Knuth algorithm
# # Variables:
#
integer NUM_ELE=11
typeset -F FUNC_LIMIT=400
# # Functions:
#
# # Function _input(_arr) - Ask for user input, build array
#
function _input {
typeset _arr ; nameref _arr="$1"
typeset _i ; integer _i
clear ; print "Please input 11 numbers..."
for ((... |
http://rosettacode.org/wiki/Truth_table | Truth table | A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.
Task
Input a Boolean function from the user as a string then calculate and print a formatted truth table for the g... | #REXX | REXX | /*REXX program displays a truth table of variables and an expression. Infix notation */
/*─────────────── is supported with one character propositional constants; variables */
/*─────────────── (propositional constants) that are allowed: A──►Z, a──►z except u.*/
/*─────────────── All propositional constants a... |
http://rosettacode.org/wiki/Ulam_spiral_(for_primes) | Ulam spiral (for primes) | An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1), constructed on a square grid, starting at the "center".
An Ulam spiral is also known as a prime spiral.
The first grid (green) is shown with sequential integers, ... | #Rust | Rust | use std::fmt;
enum Direction { RIGHT, UP, LEFT, DOWN }
use ulam::Direction::*;
/// Indicates whether an integer is a prime number or not.
fn is_prime(a: u32) -> bool {
match a {
2 => true,
x if x <= 1 || x % 2 == 0 => false,
_ => {
let max = f64::sqrt(a as f64) as u32;
... |
http://rosettacode.org/wiki/Ulam_spiral_(for_primes) | Ulam spiral (for primes) | An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1), constructed on a square grid, starting at the "center".
An Ulam spiral is also known as a prime spiral.
The first grid (green) is shown with sequential integers, ... | #Scala | Scala | object Ulam extends App {
generate(9)()
generate(9)('*')
private object Direction extends Enumeration { val RIGHT, UP, LEFT, DOWN = Value }
private def generate(n: Int, i: Int = 1)(c: Char = 0) {
assert(n > 1, "n > 1")
val s = new Array[Array[String]](n).transform {_ => new Array[Str... |
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... | #MATLAB | MATLAB | function largestTruncatablePrimes(boundary)
%Helper function for checking if a prime is left of right truncatable
function [leftTruncatable,rightTruncatable] = isTruncatable(prime,checkLeftTruncatable,checkRightTruncatable)
numDigits = ceil(log10(prime)); %calculate the number of digits in the prime... |
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
/ ... | #Ceylon | Ceylon | import ceylon.collection {
ArrayList
}
shared void run() {
class Node(label, left = null, right = null) {
shared Integer label;
shared Node? left;
shared Node? right;
string => label.string;
}
void preorder(Node node) {
process.write(node.string + " ");
if(exists left = node.left) {
preorder(le... |
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... | #Amazing_Hopper | Amazing Hopper |
#include <hopper.h>
#proto splitdate(_DATETIME_)
#proto splitnumber(_N_)
#proto split(_S_,_T_)
main:
s="this string will be separated into parts with space token separator"
aS=0,let( aS :=_split(s," "))
{","}toksep // set a new token separator
{"String: ",s}
{"\nArray... |
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... | #APL | APL | '.',⍨¨ ','(≠⊆⊢)'abc,123,X' ⍝ [1] Do the split: ','(≠⊆⊢)'abc,123,X'; [2] append the periods: '.',⍨¨
abc. 123. X. ⍝ 3 strings (char vectors), each with a period at the 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 ... | #8051_Assembly | 8051 Assembly | TC EQU 8 ; number of counter registers
TSTART EQU 08h ; first register of timer counter
TEND EQU TSTART + TC - 1 ; end register of timer counter
; Note: The multi-byte value is stored in Big-endian
; Some timer reloads
_6H EQU 085h ; 6MHz
_6L EQU 0edh
_12H EQU 00bh ; 12MHz
_12L EQU 0dbh
_110592H EQU 01eh ; 11.0592MHz... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
const char *name, *id, *dept;
int sal;
} person;
person ppl[] = {
{"Tyler Bennett", "E10297", "D101", 32000},
{"John Rappl", "E21437", "D050", 47000},
{"George Woltman", "E00127", "D101", 53500},
{"Adam Smith... |
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... | #11l | 11l | UInt32 seed = 0
F nonrandom_choice(lst)
:seed = 1664525 * :seed + 1013904223
R lst[:seed % UInt32(lst.len)]
V board = Array(‘123456789’)
V wins = ([0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6])
F printboard()
print([0, 3, 6].map(x -> (:board[x .+... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #ARM_Assembly | ARM Assembly | .text
.global _start
_start: mov r0,#4 @ 4 disks,
mov r1,#1 @ from pole 1,
mov r2,#2 @ via pole 2,
mov r3,#3 @ to pole 3.
bl move
mov r0,#0 @ Exit to Linux afterwards
mov r7,#1
swi #0
@@@ Move r0 disks from r1 via r2 to r3
move: subs r0,r0,#1 @ One fewer disk in next iteration
beq show @ If last disk, ju... |
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
| #Cowgol | Cowgol | include "cowgol.coh";
# Find the N'th digit in the Thue-Morse sequence
sub tm(n: uint32): (d: uint8) is
var n2 := n;
while n2 != 0 loop
n2 := n2 >> 1;
n := n ^ n2;
end loop;
d := (n & 1) as uint8;
end sub;
# Print the first 64 digits
var i: uint32 := 0;
while i < 64 loop
print_ch... |
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
| #Crystal | Crystal | steps = 6
tmp = ""
s1 = "0"
s2 = "1"
steps.times {
tmp = s1
s1 += s2
s2 += tmp
}
puts s1 |
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm | Tonelli-Shanks algorithm |
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computational number theory, the Tonelli–Shanks algor... | #Java | Java | import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Function;
public class TonelliShanks {
private static final BigInteger ZERO = BigInteger.ZERO;
private static final BigInteger ONE = BigInteger.ONE;
private static fina... |
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... | #Dyalect | Dyalect | func String.Tokenize(separator, escape) {
var buffer = []
var escaping = false
for c in this {
if escaping {
buffer.Add(c)
escaping = false
} else if c == escape {
escaping = true
} else if c == separator {
yield buffer.Flush();
... |
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... | #Elena | Elena | import extensions;
import extensions'routines;
import system'collections;
import system'routines;
import system'text;
extension op : String
{
tokenize(separator,escape)
{
auto buffer := new TextBuilder();
auto list := new ArrayList();
bool escaping := false;
self.forEach:(ch)... |
http://rosettacode.org/wiki/Total_circles_area | Total circles area | Total circles area
You are encouraged to solve this task according to the task description, using any language you may know.
Example circles
Example circles filtered
Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal dig... | #Python | Python | from collections import namedtuple
Circle = namedtuple("Circle", "x y r")
circles = [
Circle( 1.6417233788, 1.6121789534, 0.0848270516),
Circle(-1.4944608174, 1.2077959613, 1.1039549836),
Circle( 0.6110294452, -0.6907087527, 0.9089162485),
Circle( 0.3844862411, 0.2923344616, 0.2375743054),
Ci... |
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
... | #EchoLisp | EchoLisp |
(define dependencies
'((des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee)
(dw01 ieee dw01 dware gtech) ;; bad graph add dw04
(dw02 ieee dw02 dware )
(dw03 std synopsys dware dw03 dw02 dw01 ieee gtech)
(dw04 dw04 ieee dw01 dware gtech)
(dw0... |
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 ... | #Julia | Julia | import Base.show
@enum Move Left=1 Stay Right
mutable struct MachineState
state::String
tape::Dict{Int, String}
headpos::Int
end
struct Rule
instate::String
s1::String
s2::String
move::Move
outstate::String
end
struct Program
title::String
initial::String
final::Strin... |
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... | #J | J |
nth_prime =: p: NB. 2 is the zeroth prime
totient =: 5&p:
primeQ =: 1&p:
NB. first row contains the integer
NB. second row totient
NB. third 1 iff prime
(, totient ,: primeQ) >: i. 25
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
1 1 2 2 4 2 6 ... |
http://rosettacode.org/wiki/Topswops | Topswops | Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is composed of reversing the first ... | #PL.2FI | PL/I |
(subscriptrange):
topswap: procedure options (main); /* 12 November 2013 */
declare cards(*) fixed (2) controlled, t fixed (2);
declare dealt(*) bit(1) controlled;
declare (count, i, m, n, c1, c2) fixed binary;
declare random builtin;
do n = 1 to 10;
allocate cards(n), dealt(n);
/* Take t... |
http://rosettacode.org/wiki/Topswops | Topswops | Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is composed of reversing the first ... | #Potion | Potion | range = (a, b):
i = 0, l = list(b-a+1)
while (a + i <= b):
l (i) = a + i++.
l.
fannkuch = (n):
flips = 0, maxf = 0, k = 0, m = n - 1, r = n
perml = range(0, n), count = list(n), perm = list(n)
loop:
while (r != 1):
count (r-1) = r
r--.
if (perml (0) != 0 and perml (m) != m):
... |
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... | #Elixir | Elixir | iex(61)> deg = 45
45
iex(62)> rad = :math.pi / 4
0.7853981633974483
iex(63)> :math.sin(deg * :math.pi / 180) == :math.sin(rad)
true
iex(64)> :math.cos(deg * :math.pi / 180) == :math.cos(rad)
true
iex(65)> :math.tan(deg * :math.pi / 180) == :math.tan(rad)
true
iex(66)> temp = :math.acos(:math.cos(rad))
0.785398163397448... |
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... | #Liberty_BASIC | Liberty BASIC |
' Trabb Pardo-Knuth algorithm
' Used "magic numbers" because of strict specification of the algorithm.
dim s(10)
print "Enter 11 numbers."
for i = 0 to 10
print i + 1;
input " => "; s(i)
next i
print
' Reverse
for i = 0 to 10 / 2
tmp = s(i)
s(i) = s(10 - i)
s(10 - i) = tmp
next i
'Results
for i = 0 to 10
... |
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... | #Lua | Lua | function f (x) return math.abs(x)^0.5 + 5*x^3 end
function reverse (t)
local rev = {}
for i, v in ipairs(t) do rev[#t - (i-1)] = v end
return rev
end
local sequence, result = {}
print("Enter 11 numbers...")
for n = 1, 11 do
io.write(n .. ": ")
sequence[n] = io.read()
end
for _, x in ipairs(rever... |
http://rosettacode.org/wiki/Truth_table | Truth table | A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.
Task
Input a Boolean function from the user as a string then calculate and print a formatted truth table for the g... | #Ruby | Ruby | loop do
print "\ninput a boolean expression (e.g. 'a & b'): "
expr = gets.strip.downcase
break if expr.empty?
vars = expr.scan(/\p{Alpha}+/)
if vars.empty?
puts "no variables detected in your boolean expression"
next
end
vars.each {|v| print "#{v}\t"}
puts "| #{expr}"
prefix = []
suff... |
http://rosettacode.org/wiki/Ulam_spiral_(for_primes) | Ulam spiral (for primes) | An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1), constructed on a square grid, starting at the "center".
An Ulam spiral is also known as a prime spiral.
The first grid (green) is shown with sequential integers, ... | #Sidef | Sidef | require('Imager')
var (n=512, start=1, file='ulam.png')
ARGV.getopt(
'n=i' => \n,
's=i' => \start,
'f=s' => \file,
)
func cell(n, x, y, start) {
y -= (n >> 1)
x -= (n-1 >> 1)
var l = 2*(x.abs > y.abs ? x.abs : y.abs)
var d = (y > x ? (l*3 + x + y) : (l - x - y))
(l-1)**2 + d + st... |
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... | #Nim | Nim | import sets, strutils, algorithm
proc primes(n: int64): seq[int64] =
var multiples: HashSet[int64]
for i in 2..n:
if i notin multiples:
result.add i
for j in countup(i*i, n, i.int):
multiples.incl j
proc truncatablePrime(n: int64): tuple[left, right: int64] =
var
primelist: seq[str... |
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
/ ... | #Clojure | Clojure | (defn walk [node f order]
(when node
(doseq [o order]
(if (= o :visit)
(f (:val node))
(walk (node o) f order)))))
(defn preorder [node f]
(walk node f [:visit :left :right]))
(defn inorder [node f]
(walk node f [:left :visit :right]))
(defn postorder [node f]
(walk node f [:left :ri... |
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... | #AppleScript | AppleScript | on run
intercalate(".", splitOn(",", "Hello,How,Are,You,Today"))
end run
-- splitOn :: String -> String -> [String]
on splitOn(strDelim, strMain)
set {dlm, my text item delimiters} to {my text item delimiters, strDelim}
set lstParts to text items of strMain
set my text item delimiters to dlm
return lstPar... |
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 ... | #ACL2 | ACL2 | (time$ (nthcdr 9999999 (take 10000000 nil))) |
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 ... | #Action.21 | Action! | BYTE RTCLOK1=$13
BYTE RTCLOK2=$14
BYTE PALNTSC=$D014
PROC Count(CARD max)
CARD i
FOR i=1 TO max DO OD
RETURN
CARD FUNC GetFrame()
CARD res
BYTE lsb=res,msb=res+1
lsb=RTCLOK2
msb=RTCLOK1
RETURN (res)
CARD FUNC FramesToMs(CARD frames)
CARD res
IF PALNTSC=15 THEN
res=frames*60
ELSE
re... |
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... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
class Employee
{
public Employee(string name, string id, int salary, string department)
{
Name = name;
Id = id;
Salary = salary;
Department = department;
... |
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... | #Ada | Ada | with Ada.Text_IO, Ada.Numerics.Discrete_Random;
-- can play human-human, human-computer, computer-human or computer-computer
-- the computer isn't very clever: it just chooses a legal random move
procedure Tic_Tac_Toe is
type The_Range is range 1 .. 3;
type Board_Type is array (The_Range, The_Range) of Ch... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Arturo | Arturo | hanoi: function [n f dir via][
if n>0 [
hanoi n-1 f via dir
print ["Move disk" n "from" f "to" dir]
hanoi n-1 via dir f
]
]
hanoi 3 'L 'M 'R |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #D | D | import std.range;
import std.stdio;
struct TM {
private char[] sequence = ['0'];
private char[] inverse = ['1'];
private char[] buffer;
enum empty = false;
auto front() {
return sequence;
}
auto popFront() {
buffer = sequence;
sequence ~= inverse;
inve... |
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
| #Delphi | Delphi | /* Find the N'th digit in the Thue-Morse sequence */
proc nonrec tm(word n) byte:
word n2;
n2 := n;
while n2 ~= 0 do
n2 := n2 >> 1;
n := n >< n2
od;
n & 1
corp
/* Print the first 64 digits */
proc nonrec main() void:
byte i;
for i from 0 upto 63 do
write(tm(i):1)
... |
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm | Tonelli-Shanks algorithm |
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computational number theory, the Tonelli–Shanks algor... | #Julia | Julia | module TonelliShanks
legendre(a, p) = powermod(a, (p - 1) ÷ 2, p)
function solve(n::T, p::T) where T <: Union{Int, Int128, BigInt}
legendre(n, p) != 1 && throw(ArgumentError("$n not a square (mod $p)"))
local q::T = p - one(p)
local s::T = 0
while iszero(q % 2)
q ÷= 2
s += one(s)
... |
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm | Tonelli-Shanks algorithm |
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computational number theory, the Tonelli–Shanks algor... | #Kotlin | Kotlin | // version 1.1.3
import java.math.BigInteger
data class Solution(val root1: BigInteger, val root2: BigInteger, val exists: Boolean)
val bigZero = BigInteger.ZERO
val bigOne = BigInteger.ONE
val bigTwo = BigInteger.valueOf(2L)
val bigFour = BigInteger.valueOf(4L)
val bigTen = BigInteger.TEN
fun ts(n: Long, p:... |
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... | #F.23 | F# | open System
open System.Text.RegularExpressions
(*
.NET regexes have unlimited look-behind, so we can look for separators
which are preceeded by an even number of (or no) escape characters
*)
let split esc sep s =
Regex.Split (
s,
String.Format("(?<=(?:\b|[^{0}])(?:{0}{0})*){1}", Regex.Esc... |
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping | Tokenize a string with escaping | Task[edit]
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
It should accept three input parameters:
The string
The separator character
The escape character
It should output a list of strings.
Details
Rules for splitting:
The fields that were s... | #Factor | Factor | USING: accessors kernel lists literals namespaces
parser-combinators prettyprint sequences strings ;
SYMBOLS: esc sep ;
: set-chars ( m n -- ) [ sep set ] [ esc set ] bi* ;
: escape ( -- parser ) esc get 1token ;
: escaped ( -- parser ) escape any-char-parser &> ;
: separator ( -- parser ) sep get 1token ;
: char... |
http://rosettacode.org/wiki/Total_circles_area | Total circles area | Total circles area
You are encouraged to solve this task according to the task description, using any language you may know.
Example circles
Example circles filtered
Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal dig... | #Racket | Racket | class Point {
has Real $.x;
has Real $.y;
has Int $!cbits; # bitmap of circle membership
method cbits { $!cbits //= set_cbits(self) }
method gist { $!x ~ "\t" ~ $!y }
}
multi infix:<to>(Point $p1, Point $p2) {
sqrt ($p1.x - $p2.x) ** 2 + ($p1.y - $p2.y) ** 2;
}
multi infix:<mid>(Point $p1,... |
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
... | #Elixir | Elixir | defmodule Topological do
def sort(library) do
g = :digraph.new
Enum.each(library, fn {l,deps} ->
:digraph.add_vertex(g,l) # noop if library already added
Enum.each(deps, fn d -> add_dependency(g,l,d) end)
end)
if t = :digraph_utils.topsort(g) do
print_path(t)
else
... |
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 ... | #Kotlin | Kotlin | // version 1.2.10
enum class Dir { LEFT, RIGHT, STAY }
class Rule(
val state1: String,
val symbol1: Char,
val symbol2: Char,
val dir: Dir,
val state2: String
)
class Tape(
var symbol: Char,
var left: Tape? = null,
var right: Tape? = null
)
class Turing(
val states: List<Strin... |
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... | #Java | Java |
public class TotientFunction {
public static void main(String[] args) {
computePhi();
System.out.println("Compute and display phi for the first 25 integers.");
System.out.printf("n Phi IsPrime%n");
for ( int n = 1 ; n <= 25 ; n++ ) {
System.out.printf("%2d %2d %b%... |
http://rosettacode.org/wiki/Topswops | Topswops | Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is composed of reversing the first ... | #Python | Python | >>> from itertools import permutations
>>> def f1(p):
i = 0
while True:
p0 = p[0]
if p0 == 1: break
p[:p0] = p[:p0][::-1]
i += 1
return i
>>> def fannkuch(n):
return max(f1(list(p)) for p in permutations(range(1, n+1)))
>>> for n in range(1, 11): print(n,fannkuch(n))
1 0
2 1
3 2
4 4
5 7
6 10
7 16
8 ... |
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... | #Erlang | Erlang |
Deg=45.
Rad=math:pi()/4.
math:sin(Deg * math:pi() / 180)==math:sin(Rad).
|
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... | #M2000_Interpreter | M2000 Interpreter |
Module Input11 {
Flush ' empty stack
For I=1 to 11 {
Input "Give me a number ", a
Data a ' add to bottom of stack, use: Push a to add to top, to get reverse order here
}
}
Module Run {
Print "Trabb Pardo–Knuth algorithm"
Print "f(x)=Sqrt(Abs(x))+5*x^3"
if ... |
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... | #Maple | Maple | seqn := ListTools:-Reverse([parse(Maplets[Display](Maplets:-Elements:-Maplet(Maplets:-Elements:-InputDialog['ID1']("Enter a sequence of numbers separated by comma", 'onapprove' = Maplets:-Elements:-Shutdown(['ID1']), 'oncancel' = Maplets:-Elements:-Shutdown())))[1])]):
f:= x -> abs(x)^0.5 + 5*x^3:
for item in seqn do
... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | numbers=RandomReal[{-2,6},11]
tpk[numbers_,overflowVal_]:=Module[{revNumbers},
revNumbers=Reverse[numbers];
f[x_]:=Abs[x]^0.5+5 x^3;
Do[
If[f[i]>overflowVal,
Print["f[",i,"]= Overflow"]
,
Print["f[",i,"]= ",f[i]]
]
,
{i,revNumbers}
]
]
tpk[numbers,400] |
http://rosettacode.org/wiki/Truth_table | Truth table | A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.
Task
Input a Boolean function from the user as a string then calculate and print a formatted truth table for the g... | #Rust | Rust | use std::{
collections::HashMap,
fmt::{Display, Formatter},
iter::FromIterator,
};
// Generic expression evaluation automaton and expression formatting support
#[derive(Clone, Debug)]
pub enum EvaluationError<T> {
NoResults,
TooManyResults,
OperatorFailed(T),
}
pub trait Operator<T> {
... |
http://rosettacode.org/wiki/Ulam_spiral_(for_primes) | Ulam spiral (for primes) | An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1), constructed on a square grid, starting at the "center".
An Ulam spiral is also known as a prime spiral.
The first grid (green) is shown with sequential integers, ... | #Tcl | Tcl | proc is_prime {n} {
if {$n == 1} {return 0}
if {$n in {2 3 5}} {return 1}
for {set i 2} {$i*$i <= $n} {incr i} {
if {$n % $i == 0} {return 0}
}
return 1
}
proc spiral {w h} {
yield [info coroutine]
set x [expr {$w / 2}]
set y [expr {$h / 2}]
set n 1
set dir 0
set st... |
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... | #ooRexx | ooRexx |
-- find largest left- & right-truncatable primes < 1 million.
-- an initial set of primes (not, at this time, we leave out 2 because
-- we'll automatically skip the even numbers. No point in doing a needless
-- test each time through
primes = .array~of(3, 5, 7, 11)
-- check all of the odd numbers up to 1,000,000
l... |
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
/ ... | #CLU | CLU | bintree = cluster [T: type] is leaf, node,
pre_order, post_order, in_order, level_order
branch = struct[left, right: bintree[T], val: T]
rep = oneof[br: branch, leaf: null]
leaf = proc () returns (cvt)
return(rep$make_leaf(nil))
end leaf
node = proc (val: T... |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Me... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program strTokenize.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ NBPOSTESECLAT, 20
/* Initialized da... |
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 ... | #Ada | Ada | with Ada.Calendar; use Ada.Calendar;
with Ada.Text_Io; use Ada.Text_Io;
procedure Query_Performance is
type Proc_Access is access procedure(X : in out Integer);
function Time_It(Action : Proc_Access; Arg : Integer) return Duration is
Start_Time : Time := Clock;
Finis_Time : Time;
Func_Arg : In... |
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 ... | #Aime | Aime | integer
identity(integer x)
{
x;
}
integer
sum(integer c)
{
integer s;
s = 0;
while (c) {
s += c;
c -= 1;
}
s;
}
real
time_f(integer (*fp)(integer), integer fa)
{
date f, s;
time t;
s.now;
fp(fa);
f.now;
t.ddiff(f, s);
t.microsecond / 1000000r;... |
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... | #C.2B.2B | C++ | #include <string>
#include <set>
#include <list>
#include <map>
#include <iostream>
struct Employee
{
std::string Name;
std::string ID;
unsigned long Salary;
std::string Department;
Employee(std::string _Name = "", std::string _ID = "", unsigned long _Salary = 0, std::string _Department = "")
... |
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... | #ALGOL_W | ALGOL W | begin
string(10) board;
% initialise the board %
procedure initBoard ; board := " 123456789";
% display the board %
procedure showBoard ;
begin
s_w := 0;
write... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #AutoHotkey | AutoHotkey | move(n, from, to, via) ;n = # of disks, from = start pole, to = end pole, via = remaining pole
{
if (n = 1)
{
msgbox , 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)
}
}
move(64, 1, 3, 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
| #Draco | Draco | /* Find the N'th digit in the Thue-Morse sequence */
proc nonrec tm(word n) byte:
word n2;
n2 := n;
while n2 ~= 0 do
n2 := n2 >> 1;
n := n >< n2
od;
n & 1
corp
/* Print the first 64 digits */
proc nonrec main() void:
byte i;
for i from 0 upto 63 do
write(tm(i):1)
... |
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
| #Elena | Elena | import extensions;
import system'text;
sequence(int steps)
{
var sb1 := TextBuilder.load("0");
var sb2 := TextBuilder.load("1");
for(int i := 0, i < steps, i += 1)
{
var tmp := sb1.Value;
sb1.write(sb2);
sb2.write(tmp)
};
console.printLine(sb1).readLine()
}
public pr... |
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
| #Elixir | Elixir | Enum.reduce(0..6, '0', fn _,s ->
IO.puts s
s ++ Enum.map(s, fn c -> if c==?0, do: ?1, else: ?0 end)
end)
# or
Stream.iterate('0', fn s -> s ++ Enum.map(s, fn c -> if c==?0, do: ?1, else: ?0 end) end)
|> Enum.take(7)
|> Enum.each(&IO.puts/1) |
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm | Tonelli-Shanks algorithm |
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computational number theory, the Tonelli–Shanks algor... | #Nim | Nim | proc pow*[T: SomeInteger](x, n, p: T): T =
var t = x mod p
var e = n
result = 1
while e > 0:
if (e and 1) == 1:
result = result * t mod p
t = t * t mod p
e = e shr 1
proc legendre*[T: SomeInteger](a, p: T): T = pow(a, (p-1) shr 1, p)
proc tonelliShanks*[T: SomeInteger](n, p: T): ... |
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm | Tonelli-Shanks algorithm |
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computational number theory, the Tonelli–Shanks algor... | #OCaml | OCaml | let tonelli n p =
let open Z in
let two = ~$2 in
let pp = pred p in
let pph = pred p / two in
let pow_mod_p a e = powm a e p in
let legendre_p a = pow_mod_p a pph in
if legendre_p n <> one then None
else
let s = trailing_zeros pp in
if s = 1 then
let r = pow_mod_p n (succ p / ~$4) in
... |
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... | #Forth | Forth | variable 'src
variable #src
variable offset
: advance 1 offset +! ;
: chr@ offset @ 'src @ + c@ ;
: nextchr advance chr@ ;
: bound offset @ #src @ u< ;
: separator? dup [char] | = if drop cr else emit then ;
: escape? dup [char] ^ = if drop nextchr emit else separator... |
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... | #Fortran | Fortran | SUBROUTINE SPLIT(TEXT,SEP,ESC) !Identifies and prints tokens from within a text.
CHARACTER*(*) TEXT !To be scanned.
CHARACTER*(1) SEP !The only separator for tokens.
CHARACTER*(1) ESC !Miscegnator.
CHARACTER*(LEN(TEXT)) TOKEN !Surely sufficient space.
INTEGER N !Counts the token... |
http://rosettacode.org/wiki/Total_circles_area | Total circles area | Total circles area
You are encouraged to solve this task according to the task description, using any language you may know.
Example circles
Example circles filtered
Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal dig... | #Raku | Raku | class Point {
has Real $.x;
has Real $.y;
has Int $!cbits; # bitmap of circle membership
method cbits { $!cbits //= set_cbits(self) }
method gist { $!x ~ "\t" ~ $!y }
}
multi infix:<to>(Point $p1, Point $p2) {
sqrt ($p1.x - $p2.x) ** 2 + ($p1.y - $p2.y) ** 2;
}
multi infix:<mid>(Point $p1,... |
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
... | #Erlang | Erlang |
-module(topological_sort).
-compile(export_all).
-define(LIBRARIES,
[{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, synop... |
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 ... | #Lambdatalk | Lambdatalk |
{require lib_H} // associative arrays library
{def tm
{def tm.r
{lambda {:data :rules :state :end :blank :i :N}
{if {or {W.equal? :state :end} {> :N 400}} // recursion limited to 400
then :data
else {let { {:data :data} {:rules :rules}
{:state {H.get :state :rules... |
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... | #jq | jq |
# jq optimizes the recursive call of _gcd in the following:
def gcd(a;b):
def _gcd:
if .[1] != 0 then [.[1], .[0] % .[1]] | _gcd else .[0] end;
[a,b] | _gcd ;
def count(s): reduce s as $x (0; .+1);
def totient:
. as $n
| count( range(0; .) | select( gcd($n; .) == 1) );
# input: determines the maximu... |
http://rosettacode.org/wiki/Topswops | Topswops | Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is composed of reversing the first ... | #R | R |
topswops <- function(x){
i <- 0
while(x[1] != 1){
first <- x[1]
if(first == length(x)){
x <- rev(x)
} else{
x <- c(x[first:1], x[(first+1):length(x)])
}
i <- i + 1
}
return(i)
}
library(iterpc)
result <- NULL
for(i in 1:10){
I <- iterpc(i, labels = 1:i, ordered = T)
... |
http://rosettacode.org/wiki/Topswops | Topswops | Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is composed of reversing the first ... | #Racket | Racket |
#lang racket
(define (all-misplaced? l)
(for/and ([x (in-list l)] [n (in-naturals 1)]) (not (= x n))))
(define (topswops n)
(for/fold ([m 0]) ([p (in-permutations (range 1 (add1 n)))]
#:when (all-misplaced? p))
(let loop ([p p] [n 0])
(if (= 1 (car p))
(max n m)
... |
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.