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/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #ActionScript | ActionScript | public function move(n:int, from:int, to:int, via:int):void
{
if (n > 0)
{
move(n - 1, from, via, to);
trace("Move disk from pole " + from + " to pole " + to);
move(n - 1, via, to, from);
}
} |
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... | #11l | 11l | F legendre(a, p)
R pow(a, (p - 1) I/ 2, p)
F tonelli(n, p)
assert(legendre(n, p) == 1, ‘not a square (mod p)’)
V q = p - 1
V s = 0
L q % 2 == 0
q I/= 2
s++
I s == 1
R pow(n, (p + 1) I/ 4, p)
V z = 2
L
I p - 1 == legendre(z, p)
L.break
z++
V c = pow(z, ... |
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... | #Ada | Ada | with Ada.Text_Io;
with Ada.Containers.Indefinite_Vectors;
with Ada.Strings.Unbounded;
procedure Tokenize is
package String_Vectors is
new Ada.Containers.Indefinite_Vectors (Positive, String);
use String_Vectors;
function Split (Text : String;
Separator : Character := '|';
... |
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... | #FreeBASIC | FreeBASIC | #define dx 0.0001
'read in the data; I reordered them in descending order of radius
'This maximises our chance of being able to break early, saving run time,
'and we needn't bother finding out which circles are entirely inside others
data -0.5263668798,1.7315156631,1.4428514068
data -0.1403562064,0.2437382535,1.38049... |
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
... | #Ada | Ada | with Ada.Containers.Vectors; use Ada.Containers;
package Digraphs is
type Node_Idx_With_Null is new Natural;
subtype Node_Index is Node_Idx_With_Null range 1 .. Node_Idx_With_Null'Last;
-- a Node_Index is a number from 1, 2, 3, ... and the representative of a node
type Graph_Type is tagged private;
... |
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 ... | #EchoLisp | EchoLisp |
(require 'struct)
(struct TM (read-only: name states symbs final rules mem state-values: tape pos state))
(define-syntax-rule (rule-idx state symb numstates)
(+ state (* symb numstates)))
(define-syntax-rule (make-TM name states symbs rules)
(_make-TM name 'states 'symbs 'rules))
;; a rule is (stat... |
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... | #C.23 | C# | using static System.Console;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
for (int i = 1; i <= 25; i++) {
int t = Totient(i);
WriteLine(i + "\t" + t + (t == i - 1 ? "\tprime" : ""));
}
WriteLine();
for (int i = 100; i ... |
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 ... | #Icon_and_Unicon | Icon and Unicon | procedure main()
every n := 1 to 10 do {
ts := 0
every (ts := 0) <:= swop(permute([: 1 to n :]))
write(right(n, 3),": ",right(ts,4))
}
end
procedure swop(A)
count := 0
while A[1] ~= 1 do {
A := reverse(A[1+:A[1]]) ||| A[(A[1]+1):0]
count +:= 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... | #bc | bc | /* t(x) = tangent of x */
define t(x) {
return s(x) / c(x)
}
/* y(y) = arcsine of y, domain [-1, 1], range [-pi/2, pi/2] */
define y(y) {
/* Handle angles with no tangent. */
if (y == -1) return -2 * a(1) /* -pi/2 */
if (y == 1) return 2 * a(1) /* pi/2 */
/* Tangent of angle is y / x, where x^2 + y^2 = 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... | #Elixir | Elixir | defmodule Trabb_Pardo_Knuth do
def task do
Enum.reverse( get_11_numbers )
|> Enum.each( fn x -> perform_operation( &function(&1), 400, x ) end )
end
defp alert( n ), do: IO.puts "Operation on #{n} overflowed"
defp get_11_numbers do
ns = IO.gets( "Input 11 integers. Space delimited, please: " )
... |
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... | #Erlang | Erlang |
-module( trabb_pardo_knuth ).
-export( [task/0] ).
task() ->
Sequence = get_11_numbers(),
S = lists:reverse( Sequence ),
[perform_operation( fun function/1, 400, X) || X <- S].
alert( N ) -> io:fwrite( "Operation on ~p overflowed~n", [N] ).
get_11_numbers() ->
{ok, Ns} = io:fread( "Input 11 integers. ... |
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... | #Racket | Racket |
#lang racket
;; A quick `amb' implementation
(define failures null)
(define (fail)
(if (pair? failures) ((first failures)) (error "no more choices!")))
(define (amb/thunks choices)
(let/cc k (set! failures (cons k failures)))
(if (pair? choices)
(let ([choice (first choices)]) (set! choices (rest choices)... |
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... | #Raku | Raku | sub infix:<→> ($protasis, $apodosis) { !$protasis or $apodosis }
my @tests =
{ .end == 12 and all(.[1..12]) === any(True, False) },
{ 3 == [+] .[7..12] },
{ 2 == [+] .[2,4...12] },
{ .[5] → all .[6,7] },
{ none .[2,3,4] },
{ 4 == [+] .[1,3...11] },
{ one .[2,3] },
{ .[7] → all .[5,6] }... |
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... | #Pascal | Pascal |
program TruthTables;
const
StackSize = 80;
type
TVariable = record
Name: Char;
Value: Boolean;
end;
TStackOfBool = record
Top: Integer;
Elements: array [0 .. StackSize - 1] of Boolean;
end;
var
Expression: string;
Variables: array [0 .. 23] of TVariable;
VariablesLength: Integer;... |
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, ... | #Phix | Phix | with javascript_semantics
function spiral(integer w, h, x, y)
return iff(y?w+spiral(h-1,w,y-1,w-x-1):x)
end function
integer w = 9, h = 9
for i=h-1 to 0 by -1 do
for j=w-1 to 0 by -1 do
integer p = w*h-spiral(w,h,j,i)
puts(1,"o "[2-is_prime(p)])
end for
puts(1,'\n')
end for
|
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... | #Go | Go | package main
import "fmt"
func main() {
sieve(1e6)
if !search(6, 1e6, "left", func(n, pot int) int { return n % pot }) {
panic("997?")
}
if !search(6, 1e6, "right", func(n, _ int) int { return n / 10 }) {
panic("7393?")
}
}
var c []bool
func sieve(ss int) {
c = make([]boo... |
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
/ ... | #APL | APL | preorder ← {l r←⍺ ⍵⍵ ⍵ ⋄ (⊃r)∇⍨⍣(×≢r)⊢(⊃l)∇⍨⍣(×≢l)⊢⍺ ⍺⍺ ⍵}
inorder ← {l r←⍺ ⍵⍵ ⍵ ⋄ (⊃r)∇⍨⍣(×≢r)⊢⍵ ⍺⍺⍨(⊃l)∇⍨⍣(×≢l)⊢⍺}
postorder← {l r←⍺ ⍵⍵ ⍵ ⋄ ⍵ ⍺⍺⍨(⊃r)∇⍨⍣(×≢r)⊢(⊃l)∇⍨⍣(×≢l)⊢⍺}
lvlorder ← {0=⍴⍵:⍺ ⋄ (⊃⍺⍺⍨/(⌽⍵),⊂⍺)∇⊃∘(,/)⍣2⊢⍺∘⍵⍵¨⍵} |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate h... | #Sidef | Sidef | say [9,16,25].map {.sqrt}; # prints: [3, 4, 5] |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate h... | #Standard_ML | Standard ML | - 3.0;
val it = 3.0 : real
- it * it;
val it = 9.0 : real
- Math.sqrt it;
val it = 3.0 : real
- |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate h... | #Tailspin | Tailspin |
3 -> \($-1! $+1!\) -> $*$ -> [$-1..$+1] -> '$;
' -> !OUT::write
|
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate h... | #UNIX_Shell | UNIX Shell | multiply 3 4 # We assume this user defined function has been previously defined
echo $? # This will output 12, but $? will now be zero indicating a successful echo |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate h... | #VBA | VBA | var T // global scope
var doSomethingWithT = Fn.new { [T * T, T.sqrt] }
T = 3
System.print(doSomethingWithT.call()) |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate h... | #Wren | Wren | var T // global scope
var doSomethingWithT = Fn.new { [T * T, T.sqrt] }
T = 3
System.print(doSomethingWithT.call()) |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Ada | Ada | with Ada.Text_Io; use Ada.Text_Io;
procedure Towers is
type Pegs is (Left, Center, Right);
procedure Hanoi (Ndisks : Natural; Start_Peg : Pegs := Left; End_Peg : Pegs := Right; Via_Peg : Pegs := Center) is
begin
if Ndisks > 0 then
Hanoi(Ndisks - 1, Start_Peg, Via_Peg, End_Peg);
Put_Li... |
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... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program tonshan64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../inc... |
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... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI or android 32 bits */
/* program tonshan.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see tas... |
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... | #ALGOL_68 | ALGOL 68 | BEGIN
# returns s parsed according to delimiter and escape #
PROC parse with escapes = ( STRING s, CHAR delimiter, escape )[]STRING:
IF ( UPB s - LWB s ) + 1 < 1 THEN
# empty string #
[ 1 : 0 ]STRING empty a... |
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... | #Go | Go | package main
import (
"flag"
"fmt"
"math"
"runtime"
"sort"
)
// Note, the standard "image" package has Point and Rectangle but we
// can't use them here since they're defined using int rather than
// float64.
type Circle struct{ X, Y, R, rsq float64 }
func NewCircle(x, y,... |
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
... | #Bracmat | Bracmat | ( ("des_system_lib".std synopsys "std_cell_lib" "des_system_lib" dw02 dw01 ramlib ieee)
(dw01.ieee dw01 dware gtech)
(dw02.ieee dw02 dware)
(dw03.std synopsys dware dw03 dw02 dw01 ieee gtech)
(dw04.dw04 ieee dw01 dware gtech)
(dw05.dw05 ieee dware)
(dw06.dw06 ieee dware)
(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 ... | #EDSAC_order_code | EDSAC order code |
[Attempt at Turing machine for Rosetta Code.]
[EDSAC program, Initial Orders 2.]
[Library subroutine M3 prints header and is then overwritten.]
PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF
*!!NR!STEPS@&#..PZ [..PZ marks end of header]
T48K [& (delta) parameter: Turing machine tape.]
... |
http://rosettacode.org/wiki/Totient_function | Totient function | The totient function is also known as:
Euler's totient function
Euler's phi totient function
phi totient function
Φ function (uppercase Greek phi)
φ function (lowercase Greek phi)
Definitions (as per number theory)
The totient function:
counts the integers up to a given positiv... | #C.2B.2B | C++ | #include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
class totient_calculator {
public:
explicit totient_calculator(int max) : totient_(max + 1) {
for (int i = 1; i <= max; ++i)
totient_[i] = i;
for (int i = 2; i <= max; ++i) {
if (totient_[i] < i)
... |
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 ... | #J | J | swops =: ((|.@:{. , }.)~ {.)^:a: |
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... | #BQN | BQN | ⟨sin, cos, tan⟩ ← •math
Sin 0
0
Sin π÷2
1
Cos 0
1
Cos π÷2
6.123233995736766e¯17
Tan 0
0
Tan π÷2
16331239353195370
Sin⁼ 0
0
Sin⁼ 1
1.5707963267948966
Cos⁼ 1
0
Cos⁼ 0
1.5707963267948966
Tan⁼ 0
0
Tan⁼ ∞
1.5707963267948966 |
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... | #ERRE | ERRE |
!Trabb Pardo-Knuth algorithm
PROGRAM TPK
!VAR I%,Y
DIM A[10]
FUNCTION F(T)
F=SQR(ABS(T))+5*T^3
END FUNCTION
BEGIN
DATA(10,-1,1,2,3,4,4.3,4.305,4.303,4.302,4.301)
FOR I%=0 TO 10 DO
READ(A[I%])
END FOR
FOR I%=10 TO 0 STEP -1 DO
Y=F(A[I%])
PRINT("F(";A[I%];")=";)
IF Y>400 THEN ... |
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... | #F.23 | F# |
module ``Trabb Pardo - Knuth``
open System
let f (x: float) = sqrt(abs x) + (5.0 * (x ** 3.0))
Console.WriteLine "Enter 11 numbers:"
[for _ in 1..11 -> Convert.ToDouble(Console.ReadLine())]
|> List.rev |> List.map f |> List.iter (function
| n when n <= 400.0 -> Console.WriteLine(n)
| _ -> Console.... |
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... | #REXX | REXX | /*REXX program solves the "Twelve Statement Puzzle". */
q=12; @stmt=right('statement',20) /*number of statements in the puzzle. */
m=0 /*[↓] statement one is TRUE by fiat.*/
do pass=1 for 2 ... |
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... | #Perl | Perl | #!/usr/bin/perl
sub truth_table {
my $s = shift;
my (%seen, @vars);
for ($s =~ /([a-zA-Z_]\w*)/g) {
$seen{$_} //= do { push @vars, $_; 1 };
}
print "\n", join("\t", @vars, $s), "\n", '-' x 40, "\n";
@vars = map("\$$_", @vars);
$s =~ s/([a-zA-Z_]\w*)/\$$1/g;
$s = "print(".jo... |
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, ... | #PicoLisp | PicoLisp | (load "@lib/simul.l")
(de ceil (A)
(/ (+ A 1) 2) )
(de prime? (N)
(or
(= N 2)
(and
(> N 1)
(bit? 1 N)
(let S (sqrt N)
(for (D 3 T (+ D 2))
(T (> D S) T)
(T (=0 (% N D)) NIL) ) ) ) ) )
(de ulam (N)
(let
(G (grid N N)
... |
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... | #Haskell | Haskell | import Data.Numbers.Primes(primes, isPrime)
import Data.List
import Control.Arrow
primes1e6 = reverse. filter (notElem '0'. show) $ takeWhile(<=1000000) primes
rightT, leftT :: Int -> Bool
rightT = all isPrime. takeWhile(>0). drop 1. iterate (`div`10)
leftT x = all isPrime. takeWhile(<x).map (x`mod`) $ iterate (*10... |
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
/ ... | #AppleScript | AppleScript | on run
-- Sample tree of integers
set tree to node(1, ¬
{node(2, ¬
{node(4, {node(7, {})}), ¬
node(5, {})}), ¬
node(3, ¬
{node(6, {node(8, {}), ¬
node(9, {})})})})
-- Output of AppleScript code at Rosetta Code task
-... |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate h... | #zkl | zkl | a,_,c:=List(1,2,3,4,5,6) //-->a=1, c=3, here _ is used as "ignore"
3.0 : _.sqrt() : println(_) //-->"1.73205", _ (and :) is used to "explode" a computation
// as syntactic sugar
1.0 + 2 : _.sqrt() : _.pow(4) // no variables used, the compiler "implodes" the computation
// --> 9
|
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... | #11l | 11l | V 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, ‘D101’)... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Agena | Agena | move := proc(n::number, src::number, dst::number, via::number) is
if n > 0 then
move(n - 1, src, via, dst)
print(src & ' to ' & dst)
move(n - 1, via, dst, src)
fi
end
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
| #11l | 11l | F thue_morse_digits(digits)
R (0 .< digits).map(n -> bin(n).count(‘1’) % 2)
print(thue_morse_digits(20)) |
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... | #C | C | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t modpow(uint64_t a, uint64_t b, uint64_t n) {
uint64_t x = 1, y = a;
while (b > 0) {
if (b % 2 == 1) {
x = (x * y) % n; // multiplying with base
}
y = (y * y) % n; // squaring the base
b /= 2;
}... |
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... | #AppleScript | AppleScript | ------------------ TOKENIZE WITH ESCAPING ----------------
-- tokenize :: String -> Character -> Character -> [String]
on tokenize(str, delimChar, chrEsc)
script charParse
-- Record: {esc:Bool, token:String, tokens:[String]}
-- charParse :: Record -> Character -> Record
on |λ|(a, x)
... |
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... | #Haskell | Haskell | data Circle = Circle { cx :: Double, cy :: Double, cr :: Double }
isInside :: Double -> Double -> Circle -> Bool
isInside x y c = (x - cx c) ^ 2 + (y - cy c) ^ 2 <= (cr c ^ 2)
isInsideAny :: Double -> Double -> [Circle] -> Bool
isInsideAny x y = any (isInside x y)
approximatedArea :: [Circle] -> Int -> Double
app... |
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
... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char input[] =
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee ... |
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 ... | #Erlang | Erlang | #!/usr/bin/env escript
-module(turing).
-mode(compile).
-export([main/1]).
% Incrementer definition:
% States: a | halt
% Initial state: a
% Halting states: halt
% Symbols: b | '1'
% Blank symbol: b
incrementer_config() -> {a, [halt], b}.
incrementer(a, '1') -> {'1', right, a};
incrementer(a, 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... | #D | D | import std.stdio;
int totient(int n) {
int tot = n;
for (int i = 2; i * i <= n; i += 2) {
if (n % i == 0) {
while (n % i == 0) {
n /= i;
}
tot -= tot / i;
}
if (i==2) {
i = 1;
}
}
if (n > 1) {
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 ... | #Java | Java | public class Topswops {
static final int maxBest = 32;
static int[] best;
static private void trySwaps(int[] deck, int f, int d, int n) {
if (d > best[n])
best[n] = d;
for (int i = n - 1; i >= 0; i--) {
if (deck[i] == -1 || deck[i] == i)
break;
... |
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... | #C | C | #include <math.h>
#include <stdio.h>
int main() {
double pi = 4 * atan(1);
/*Pi / 4 is 45 degrees. All answers should be the same.*/
double radians = pi / 4;
double degrees = 45.0;
double temp;
/*sine*/
printf("%f %f\n", sin(radians), sin(degrees * pi / 180));
/*cosine*/
printf("%f %f\n", cos(radian... |
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... | #Factor | Factor | USING: formatting io kernel math math.functions math.parser
prettyprint sequences splitting ;
IN: rosetta-code.trabb-pardo-knuth
CONSTANT: threshold 400
CONSTANT: prompt "Please enter 11 numbers: "
: fn ( x -- y ) [ abs 0.5 ^ ] [ 3 ^ 5 * ] bi + ;
: overflow? ( x -- ? ) threshold > ;
: get-input ( -- seq )
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... | #Forth | Forth | : f(x) fdup fsqrt fswap 3e f** 5e f* f+ ;
4e2 fconstant f-too-big
11 Constant #Elements
: float-array ( compile: n -- / run: n -- addr )
create
floats allot
does>
swap floats + ;
#Elements float-array vec
: get-it ( -- )
." Enter " #Elements . ." numbers:" cr
#Elements 0 DO
... |
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... | #Ruby | Ruby | constraints = [
->(st) { st.size == 12 },
->(st) { st.last(6).count(true) == 3 },
->(st) { st.each_slice(2).map(&:last).count(true) == 2 },
->(st) { st[4] ? (st[5] & st[6]) : true },
->(st) { st[1..3].none? },
->(st) { st.each_slice(2).map(&:first).count(true) == 4 },
->(st) { st[1] ^ st[2] },
->(st) {... |
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... | #Phix | Phix | sequence opstack = {}
object token
object op = 0 -- 0 = none
string s -- the expression being parsed
integer sidx -- idx to ""
integer ch -- s[sidx]
procedure err(string msg)
printf(1,"%s\n%s^ %s\n\nPressEnter...",{s,repeat(' ',sidx-1),msg})
{} = wait_key()
abort(0)
end procedure
proced... |
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, ... | #PowerShell | PowerShell |
function New-UlamSpiral ( [int]$N )
{
# Generate list of primes
$Primes = @( 2 )
For ( $X = 3; $X -le $N*$N; $X += 2 )
{
If ( -not ( $Primes | Where { $X % $_ -eq 0 } | Select -First 1 ) ) { $Primes += $X }
}
# Initialize variables
$X = 0
$Y = -1
$i = $N * $... |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main(arglist)
N := 0 < integer(\arglist[1]) | 1000000 # primes to generator 1 to ... (1M or 1st arglist)
D := (0 < integer(\arglist[2]) | 10) / 2 # primes to display (10 or 2nd arglist)
P := sieve(N) # from sieve task (modified)
... |
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
/ ... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program deftree2.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ READ, 3
.equ WRITE, 4
.equ NBVAL, 9
/*******************************************/
/* Structures ... |
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... | #Action.21 | Action! | DEFINE PTR="CARD"
DEFINE ENTRY_SIZE="8"
TYPE Employee=[
PTR name,id,dep ;CHAR ARRAY
CARD salary]
BYTE ARRAY data(200)
BYTE count=[0]
PTR FUNC GetItemAddr(INT index)
PTR addr
addr=data+index*ENTRY_SIZE
RETURN (addr)
PROC Append(CHAR ARRAY n,i CARD s CHAR ARRAY d)
Employee POINTER dst
dst=GetItemA... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #ALGOL_60 | ALGOL 60 | begin
procedure movedisk(n, f, t);
integer n, f, t;
begin
outstring (1, "Move disk from");
outinteger(1, f);
outstring (1, "to");
outinteger(1, t);
outstring (1, "\n");
end;
procedure dohanoi(n, f, t, u);
integer n, f, t, u;
begin
if n < 2 then
movedisk(1, f, t)
else
... |
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
| #8080_Assembly | 8080 Assembly | org 100h
;;; Write 256 bytes of ASCII '0' starting at address 200h
lxi h,200h ; The array is page-aligned so L starts at 0
mvi a,'0' ; ASCII 0
zero: mov m,a ; Write it to memory at address HL
inr l ; Increment low byte of pointer,
jnz zero ; until it wraps to zero.
;;; Generate the first 256 elements of the Thu... |
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
| #Action.21 | Action! | PROC Next(CHAR ARRAY s)
BYTE i,len
CHAR c
IF s(0)=0 THEN
s(0)=1 s(1)='0
RETURN
FI
FOR i=1 TO s(0)
DO
IF s(i)='0 THEN
c='1
ELSE
c='0
FI
s(s(0)+i)=c
OD
s(0)==*2
RETURN
PROC Main()
BYTE i
CHAR ARRAY s(256)
s(0)=0
FOR i=0 TO 7
DO
Next(s)
PrintF("... |
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
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Thue_Morse is
function Replace(S: String) return String is
-- replace every "0" by "01" and every "1" by "10"
(if S'Length = 0 then ""
else (if S(S'First) = '0' then "01" else "10") &
Replace(S(S'First+1 .. S'Last)));
function Sequence (N: Na... |
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... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Numerics;
namespace TonelliShanks {
class Solution {
private readonly BigInteger root1, root2;
private readonly bool exists;
public Solution(BigInteger root1, BigInteger root2, bool exists) {
this.root1 = root1;
... |
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... | #Arturo | Arturo | tokenize: function [s sep esc][
escaping: 0
loop 0..(size s)-1 [i][
chr: get split s i
if? escaping=1 [
prints chr
escaping: 0
]
else [
case [chr]
when? [=sep] [print ""]
when? [=esc] [escaping: 1]
else [prints chr]
]
]
print ""
]
str: "one^|uno||three^^^^|four^^^|^cuatro|"
tok... |
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... | #J | J | NB. check points on a regular grid within the bounding box
N=: 400 NB. grids in each dimension. Controls accuracy.
'X Y R'=: |: XYR=: (_&".;._2~ LF&=)0 :0
1.6417233788 1.6121789534 0.0848270516
-1.4944608174 1.2077959613 1.1039549836
0.6110294452 -0.6907087527 0.9089162485
0.3844862411 0.2923344616 0.23... |
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
... | #C.23 | C# |
namespace Algorithms
{
using System;
using System.Collections.Generic;
using System.Linq;
public class TopologicalSorter<ValueType>
{
private class Relations
{
public int Dependencies = 0;
public HashSet<ValueType> Dependents = new HashSet<ValueType>();
... |
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 ... | #Fortran | Fortran | 1 State 1
1,-1, 3
1,+1, 2
2 State 2
1,+1, 2
1,-1, 1
|
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... | #Delphi | Delphi | func totient(n) {
var tot = n
var i = 2
while i * i <= n {
if n % i == 0 {
while n % i == 0 {
n /= i
}
tot -= tot / i
}
if i == 2 {
i = 1
}
i += 2
}
if n > 1 {
tot -= tot / n
}
ret... |
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 ... | #jq | jq | # "while" as defined here is included in recent versions (>1.4) of jq:
def until(cond; next):
def _until:
if cond then . else (next|_until) end;
_until;
# Generate a stream of permutations of [1, ... n].
# This implementation uses arity-0 filters for speed.
def permutations:
# Given a single array, insert g... |
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 ... | #Julia | Julia | function fannkuch(n)
n == 1 && return 0
n == 2 && return 1
p = [1:n]
q = copy(p)
s = copy(p)
sign = 1; maxflips = sum = 0
while true
q0 = p[1]
if q0 != 1
for i = 2:n
q[i] = p[i]
end
flips = 1
while true
qq = q[q0] #??
if qq == 1
sum += sign*flips
flips > maxflips && (maxflip... |
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... | #C.23 | C# | using System;
namespace RosettaCode {
class Program {
static void Main(string[] args) {
Console.WriteLine("=== radians ===");
Console.WriteLine("sin (pi/3) = {0}", Math.Sin(Math.PI / 3));
Console.WriteLine("cos (pi/3) = {0}", Math.Cos(Math.PI / 3));
Console.... |
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... | #Fortran | Fortran | program tpk
implicit none
real, parameter :: overflow = 400.0
real :: a(11), res
integer :: i
write(*,*) "Input eleven numbers:"
read(*,*) a
a = a(11:1:-1)
do i = 1, 11
res = f(a(i))
write(*, "(a, f0.3, a)", advance = "no") "f(", a(i), ") = "
if(res > overflow) then
write(*, "(a)... |
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... | #Scala | Scala | class LogicPuzzle {
val s = new Array[Boolean](13)
var count = 0
def check2: Boolean = {
var count = 0
for (k <- 7 to 12) if (s(k)) count += 1
s(2) == (count == 3)
}
def check3: Boolean = {
var count = 0
for (k <- 2 to 12 by 2) if (s(k)) count += 1
s(3) == (count == 2)
}
... |
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... | #PicoLisp | PicoLisp | (de truthTable (Expr)
(let Vars
(uniq
(make
(setq Expr
(recur (Expr) # Convert infix to prefix notation
(cond
((atom Expr) (link Expr))
((== 'not (car Expr))
(list 'not (recurse (cadr Expr))... |
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, ... | #Python | Python | # coding=UTF-8
from __future__ import print_function, division
from math import sqrt
def cell(n, x, y, start=1):
d, y, x = 0, y - n//2, x - (n - 1)//2
l = 2*max(abs(x), abs(y))
d = (l*3 + x + y) if y >= x else (l - x - y)
return (l - 1)**2 + d + start - 1
def show_spiral(n, symbol='# ', start=1, spa... |
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... | #J | J | selPrime=: #~ 1&p:
seed=: selPrime digits=: 1+i.9
step=: selPrime@,@:(,&.":/&>)@{@; |
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
/ ... | #ATS | ATS | #include
"share/atspre_staload.hats"
//
(* ****** ****** *)
//
datatype
tree (a:t@ype) =
| tnil of ()
| tcons of (tree a, a, tree a)
//
(* ****** ****** *)
symintr ++
infixr (+) ++
overload ++ with list_append
(* ****** ****** *)
#define sing list_sing
(* ****** ****** *)
fun{
a:t@ype
} preorder
(t0: tr... |
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... | #11l | 11l | V text = ‘Hello,How,Are,You,Today’
V tokens = text.split(‘,’)
print(tokens.join(‘.’)) |
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... | #Ada | Ada | with Ada.Containers.Vectors;
with Ada.Text_IO;
procedure Top is
type Departments is (D050, D101, D190, D202);
type Employee_Data is record
Name : String (1 .. 15);
ID : String (1 .. 6);
Salary : Positive;
Department : Departments;
end record;
package Employee_Ve... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #ALGOL_68 | ALGOL 68 | PROC move = (INT n, from, to, via) VOID:
IF n > 0 THEN
move(n - 1, from, via, to);
printf(($"Move disk from pole "g" to pole "gl$, from, to));
move(n - 1, via, to, from)
FI
;
main: (
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
| #ALGOL_68 | ALGOL 68 | # "flips" the "bits" in a string (assumed to contain only "0" and "1" characters) #
OP FLIP = ( STRING s )STRING:
BEGIN
STRING result := s;
FOR char pos FROM LWB result TO UPB result DO
result[ char pos ] := IF result[ char pos ] = "0" THEN "1" ELSE "0" FI
OD;
result
... |
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
| #AppleScript | AppleScript | ------------------------ THUE MORSE ----------------------
-- thueMorse :: Int -> String
on thueMorse(nCycles)
script concatBinaryInverse
on |λ|(xs)
script binaryInverse
on |λ|(x)
1 - x
end |λ|
end script
xs & map(bi... |
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... | #Clojure | Clojure |
(defn find-first
" Finds first element of collection that satisifies predicate function pred "
[pred coll]
(first (filter pred coll)))
(defn modpow
" b^e mod m (using Java which solves some cases the pure clojure method has to be modified to tackle--i.e. with large b & e and
calculation simplications whe... |
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... | #AutoHotkey | AutoHotkey | Tokenize(s,d,e){
for i,v in x:=StrSplit(StrReplace(StrReplace(StrReplace(s,e e,Chr(0xFFFE)),e d,Chr(0xFFFF)),e),d)
x[i]:=StrReplace(StrReplace(v,Chr(0xFFFE),e),Chr(0xFFFF),d)
return x
} |
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... | #BBC_BASIC | BBC BASIC | REM >tokenizer
PROC_tokenize("one^|uno||three^^^^|four^^^|^cuatro|", "|", "^")
END
:
DEF PROC_tokenize(src$, sep$, esc$)
LOCAL field%, char$, escaping%, i%
field% = 1
escaping% = FALSE
PRINT field%; " ";
FOR i% = 1 TO LEN src$
char$ = MID$(src$, i%, 1)
IF escaping% THEN
PRINT char$;
escaping% = FALSE
ELSE... |
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... | #Java | Java |
public class CirclesTotalArea {
/*
* Rectangles are given as 4-element arrays [tx, ty, w, h].
* Circles are given as 3-element arrays [cx, cy, r].
*/
private static double distSq(double x1, double y1, double x2, double y2) {
return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
... |
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
... | #C.2B.2B | C++ | #include <map>
#include <set>
template<typename Goal>
class topological_sorter {
protected:
struct relations {
std::size_t dependencies;
std::set<Goal> dependents;
};
std::map<Goal, relations> map;
public:
void add_goal(Goal const &goal) {
map[goal];
}
void add_dependen... |
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 ... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package turing
type Symbol byte
type Motion byte
const (
Left Motion = 'L'
Right Motion = 'R'
Stay Motion = 'N'
)
type Tape struct {
data []Symbol
pos, left int
blank Symbol
}
// NewTape returns a new tape filled with 'data' and position set to 'start... |
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... | #Dyalect | Dyalect | func totient(n) {
var tot = n
var i = 2
while i * i <= n {
if n % i == 0 {
while n % i == 0 {
n /= i
}
tot -= tot / i
}
if i == 2 {
i = 1
}
i += 2
}
if n > 1 {
tot -= tot / n
}
ret... |
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 ... | #Kotlin | Kotlin | // version 1.1.2
val best = IntArray(32)
fun trySwaps(deck: IntArray, f: Int, d: Int, n: Int) {
if (d > best[n]) best[n] = d
for (i in n - 1 downTo 0) {
if (deck[i] == -1 || deck[i] == i) break
if (d + best[i] <= best[n]) return
}
val deck2 = deck.copyOf()
for (i in 1 until n) {
... |
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... | #C.2B.2B | C++ | #include <iostream>
#include <cmath>
#ifdef M_PI // defined by all POSIX systems and some non-POSIX ones
double const pi = M_PI;
#else
double const pi = 4*std::atan(1);
#endif
double const degree = pi/180;
int main()
{
std::cout << "=== radians ===\n";
std::cout << "sin(pi/3) = " << std::sin(pi/3) << "\n";
... |
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... | #FreeBASIC | FreeBASIC | ' version 22-07-2017
' compile with: fbc -s console
Function f(n As Double) As Double
return Sqr(Abs(n)) + 5 * n ^ 3
End Function
' ------=< MAIN >=------
Dim As Double x, s(1 To 11)
Dim As Long i
For i = 1 To 11
Print Str(i);
Input " => ", s(i)
Next
Print
Print String(20,"-")
i -= 1
Do
Pri... |
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... | #Go | Go | package main
import (
"fmt"
"log"
"math"
)
func main() {
// prompt
fmt.Print("Enter 11 numbers: ")
// accept sequence
var s [11]float64
for i := 0; i < 11; {
if n, _ := fmt.Scan(&s[i]); n > 0 {
i++
}
}
// reverse sequence
for i, item := range s... |
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... | #Sidef | Sidef | var conditions = [
{ false },
{|a| a.len == 13 },
{|a| [a[7..12]].count(true) == 3 },
{|a| [a[2..12 `by` 2]].count(true) == 2 },
{|a| a[5] ? (a[6] && a[7]) : true },
{|a| !a[2] && !a[3] && !a[4] },
{|a| [a[1..11 `by` 2]].count(true) == 4 },
{|a| a[2] == true^a[3] },
{|a| a[7] ? (a[5]... |
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... | #Prolog | Prolog | /*
To evaluate the truth table a line of text is inputted and then there are three steps
Let's say the expression is:
'not a and (b or c)'
Step 1: tokenize into atoms and brackets
eg: Tokenized = [ not, a, and, '(', b, or, c, ')' ].
Step 2: convert to a term that can be evaluated, and get o... |
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, ... | #R | R |
## Plotting Ulam spiral (for primes) 2/12/17 aev
## plotulamspirR(n, clr, fn, ttl, psz=600), where: n - initial size;
## clr - color; fn - file name; ttl - plot title; psz - picture size.
##
require(numbers);
plotulamspirR <- function(n, clr, fn, ttl, psz=600) {
cat(" *** START:", date(), "n=",n, "clr=",clr, "psz=... |
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... | #Java | Java | import java.util.BitSet;
public class Main {
public static void main(String[] args){
final int MAX = 1000000;
//Sieve of Eratosthenes (using BitSet only for odd numbers)
BitSet primeList = new BitSet(MAX>>1);
primeList.set(0,primeList.size(),true);
int sqroot = (int) Math.sqrt(MAX);
primeList.... |
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
/ ... | #AutoHotkey | AutoHotkey | AddNode(Tree,1,2,3,1) ; Build global Tree
AddNode(Tree,2,4,5,2)
AddNode(Tree,3,6,0,3)
AddNode(Tree,4,7,0,4)
AddNode(Tree,5,0,0,5)
AddNode(Tree,6,8,9,6)
AddNode(Tree,7,0,0,7)
AddNode(Tree,8,0,0,8)
AddNode(Tree,9,0,0,9)
MsgBox % "Preorder: " PreOrder(Tree,1) ; 1 2 4 7 5 3 6 8 9
MsgBox % "Inorder: " InOrder(Tree,1... |
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.