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/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... | #BASIC256 | BASIC256 | function Sum (x, y)
Sum = x + y # using name of function
end function
function SumR (x, y)
return x + y # using Return keyword which always returns immediately
end function
print Sum (1, 2)
print SumR(2, 3) |
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... | #Clojure | Clojure |
user=> 3
3
user=> (Math/pow *1 2)
9.0
user=> (Math/pow *2 0.5)
1.7320508075688772
|
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... | #Erlang | Erlang | 7> 1 + 2.
3
8> v(-1).
3
|
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... | #Forth | Forth | : myloop 11 1 do i . loop cr ; myloop |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #11l | 11l | F hanoi(ndisks, startPeg = 1, endPeg = 3) -> N
I ndisks
hanoi(ndisks - 1, startPeg, 6 - startPeg - endPeg)
print(‘Move disk #. from peg #. to peg #.’.format(ndisks, startPeg, endPeg))
hanoi(ndisks - 1, 6 - startPeg - endPeg, endPeg)
hanoi(ndisks' 3) |
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... | #11l | 11l | T Circle
Float x, y, r
F (x, y, r)
.x = x
.y = y
.r = r
V 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),
Circle(... |
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 ... | #CLU | CLU | % Bidirectional 'infinite' tape
tape = cluster [T: type] is make, left, right, get_cell, set_cell,
elements, get_size
rep = record[
blank: T,
loc: int,
data: array[T]
]
% Make a new tape with a given blank value and initial value
make = proc (blank:... |
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... | #APL | APL | task←{
totient ← 1+.=⍳∨⊢
prime ← totient=-∘1
⎕←'Index' 'Totient' 'Prime',(⊢⍪totient¨,[÷2]prime¨)⍳25
{⎕←'There are' (+/prime¨⍳⍵) 'primes below' ⍵}¨100 1000 10000
} |
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 ... | #Eiffel | Eiffel |
class
TOPSWOPS
create
make
feature
make (n: INTEGER)
-- Topswop game.
local
perm, ar: ARRAY [INTEGER]
tcount, count: INTEGER
do
create perm_sol.make_empty
create solution.make_empty
across
1 |..| n as c
loop
create ar.make_filled (0, 1, c.item)
across
1 |..| c.item 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... | #Autolisp | Autolisp |
(defun rad_to_deg (rad)(* 180.0 (/ rad PI)))
(defun deg_to_rad (deg)(* PI (/ deg 180.0)))
(defun asin (x)
(cond
((and(> x -1.0)(< x 1.0)) (atan (/ x (sqrt (- 1.0 (* x x))))))
((= x -1.0) (* -1.0 (/ pi 2)))
((= x 1) (/ pi 2))
)
)
(defun acos (x)
(cond
((and(>= x -1.0)(<= x 1.0)) (-(* pi 0.5... |
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... | #BASIC256 | BASIC256 | dim s(11)
print 'enter 11 numbers'
for i = 0 to 10
input i + ">" , s[i]
next i
for i = 10 to 0 step -1
print "f(" + s[i] + ")=";
x = f(s[i])
if x > 400 then
print "-=< overflow >=-"
else
print x
endif
next i
end
function f(n)
return sqrt(abs(n))+5*n^3
end function |
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... | #C | C |
#include<math.h>
#include<stdio.h>
int
main ()
{
double inputs[11], check = 400, result;
int i;
printf ("\nPlease enter 11 numbers :");
for (i = 0; i < 11; i++)
{
scanf ("%lf", &inputs[i]);
}
printf ("\n\n\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :");
for (i = 10; i >... |
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... | #Nim | Nim | import bitops, sequtils, strformat, strutils, sugar
type Bools = array[1..12, bool]
const Predicates = [1: (b: Bools) => b.len == 12,
2: (b: Bools) => b[7..12].count(true) == 3,
3: (b: Bools) => toSeq(countup(2, 12, 2)).mapIt(b[it]).count(true) == 2,
4:... |
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... | #Pascal | Pascal | PROGRAM TwelveStatements;
{
This program searches through the 4095 possible sets
of 12 statements for any which may be self-consistent.
}
CONST
max12b = 4095; { Largest 12 byte number. }
TYPE
statnum = 1..12; { statement numbers }
statset = set of statnum; { sets of statements }
VAR { global va... |
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... | #Liberty_BASIC | Liberty BASIC |
print
print " TRUTH TABLES"
print
print " Input a valid Boolean expression for creating the truth table "
print " Use lowercase 'and', 'or', 'xor', '(', 'not(' and ')'."
print
print " Take special care to precede closing bracket with a space."
print
print " You can use any alphanumeric... |
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, ... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[iCCWSpiralEast]
iCCWSpiralEast[n_Integer]:=Table[(1/2 (-1)^# ({1,-1} (Abs[#^2-t]-#)+#^2-t-Mod[#,2])&)[Round[Sqrt[t]]],{t,0,n-1}]
n=20
start=1;
pts=iCCWSpiralEast[n^2];
pts=Pick[pts,PrimeQ[start+Range[n^2]-1],True];
grid=Table[({i,j}/.(Alternatives@@pts)->"#")/.{_,_}->" ",{j,Round[n/2],-Round[n/2],-1},{i,-Round... |
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... | #Elixir | Elixir | defmodule Prime do
defp left_truncatable?(n, prime) do
func = fn i when i<=9 -> 0
i -> to_string(i) |> String.slice(1..-1) |> String.to_integer end
truncatable?(n, prime, func)
end
defp right_truncatable?(n, prime) do
truncatable?(n, prime, fn i -> div(i, 10) end)
end
d... |
http://rosettacode.org/wiki/Truncate_a_file | Truncate a file | Task
Truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes).
Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced... | #XPL0 | XPL0 | int I, Size, FD;
char C, FN(80), Array;
[I:= 0; \get file name from command line
loop [C:= ChIn(8);
if C = $20 \space\ then quit;
FN(I):= C;
I:= I+1;
];
FN(I):= 0;
Size:= IntIn(8); \get number of bytes from command line
if Size = 0 then [Text(0, "Length n... |
http://rosettacode.org/wiki/Truncate_a_file | Truncate a file | Task
Truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes).
Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 CLEAR 29999
20 INPUT "Which file do you want to truncate?";f$
30 PRINT "Start tape to load file to truncate."
40 LOAD f$ CODE 30000
50 "Input how many bytes do you want to keep?";n
60 PRINT "Please rewind the tape and press record."
70 SAVE f$ CODE 30000,n
80 STOP |
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
/ ... | #ACL2 | ACL2 | (defun flatten-preorder (tree)
(if (endp tree)
nil
(append (list (first tree))
(flatten-preorder (second tree))
(flatten-preorder (third tree)))))
(defun flatten-inorder (tree)
(if (endp tree)
nil
(append (flatten-inorder (second tree))
(l... |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' Three different ways of returning a value from a function
Function Sum (x As Integer, y As Integer) As Integer
Sum = x + y '' using name of function
End Function
Function Sum2 (x As Integer, y As Integer) As Integer
Function = x + y '' using Function keyword
End Function
Function Sum3 ... |
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... | #Go | Go | package main
import (
"math"
"os"
"strconv"
"text/template"
)
func sqr(x string) string {
f, err := strconv.ParseFloat(x, 64)
if err != nil {
return "NA"
}
return strconv.FormatFloat(f*f, 'f', -1, 64)
}
func sqrt(x string) string {
f, err := strconv.ParseFloat(x, 64)
... |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #360_Assembly | 360 Assembly | * Towers of Hanoi 08/09/2015
HANOITOW CSECT
USING HANOITOW,R12 r12 : base register
LR R12,R15 establish base register
ST R14,SAVE14 save r14
BEGIN LH R2,=H'4' n <===
L R3,=C'123 ' stating position
... |
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... | #Arturo | Arturo | circles: @[
@[ 1.6417233788 1.6121789534 0.0848270516]
@[neg 1.4944608174 1.2077959613 1.1039549836]
@[ 0.6110294452 neg 0.6907087527 0.9089162485]
@[ 0.3844862411 0.2923344616 0.2375743054]
@[neg 0.2495892950 neg 0.3832854473 1.0845181219]
@[ 1.7813504266 1.617823703... |
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 ... | #Common_Lisp | Common Lisp | (defun turing (initial terminal blank rules tape &optional (verbose NIL))
(labels ((combine (front back)
(if front
(combine (cdr front) (cons (car front) back))
back))
(update-tape (old-front old-back new-content move)
(cond ((eq move 'right)
... |
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... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI or android with termux */
/* program totient.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 se... |
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 ... | #Elixir | Elixir | defmodule Topswops do
def get_1_first( [1 | _t] ), do: 0
def get_1_first( list ), do: 1 + get_1_first( swap(list) )
defp swap( [n | _t]=list ) do
{swaps, remains} = Enum.split( list, n )
Enum.reverse( swaps, remains )
end
def task do
IO.puts "N\ttopswaps"
Enum.map(1..10, fn n -> {n, permut... |
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 ... | #Erlang | Erlang |
-module( topswops ).
-export( [get_1_first/1, swap/1, task/0] ).
get_1_first( [1 | _T] ) -> 0;
get_1_first( List ) -> 1 + get_1_first( swap(List) ).
swap( [N | _T]=List ) ->
{Swaps, Remains} = lists:split( N, List ),
lists:reverse( Swaps ) ++ Remains.
task() ->
Permutations = [{X, permute:permute(lists:seq... |
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... | #AWK | AWK | # tan(x) = tangent of x
function tan(x) {
return sin(x) / cos(x)
}
# asin(y) = arcsine of y, domain [-1, 1], range [-pi/2, pi/2]
function asin(y) {
return atan2(y, sqrt(1 - y * y))
}
# acos(x) = arccosine of x, domain [-1, 1], range [0, pi]
function acos(x) {
return atan2(sqrt(1 - x * x), x)
}
# atan(y) = arct... |
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... | #C.2B.2B | C++ |
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <iomanip>
int main( ) {
std::vector<double> input( 11 ) , results( 11 ) ;
std::cout << "Please enter 11 numbers!\n" ;
for ( int i = 0 ; i < input.size( ) ; i++ )
std::cin >> input[i];
std::transform( input.begi... |
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... | #Perl | Perl | use List::Util 'sum';
my @condition = (
sub { 0 }, # dummy sub for index 0
sub { 13==@_ },
sub { 3==sum @_[7..12] },
sub { 2==sum @_[2,4,6,8,10,12] },
sub { $_[5] ? ($_[6] and $_[7]) : 1 },
sub { !$_[2] and !$_[3] a... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | VariableNames[data_] := Module[ {TokenRemoved},
TokenRemoved = StringSplit[data,{"~And~","~Or~","~Xor~","!","(",")"}];
Union[Select[Map[StringTrim,TokenRemoved] , Not[StringMatchQ[#,""]]&]]
]
TruthTable[BooleanEquation_] := Module[ {TestDataSet},
TestDataSet = MapThread[Rule,{ToExpression@VariableNames[BooleanEqu... |
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, ... | #Nim | Nim | import strutils
const N = 51 # Grid width and height.
type
Vec2 = tuple[x, y: int]
Grid = array[N, array[N, string]]
const Deltas: array[4, Vec2] = [(0, 1), (-1, 0), (0, -1), (1, 0)]
proc `+`(v1, v2: Vec2): Vec2 =
## Vector addition.
(v1.x + v2.x, v1.y + v2.y)
proc isPrime(n: Positive): bool =
... |
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... | #Factor | Factor | USING: formatting fry grouping.extras kernel literals math
math.parser math.primes sequences ;
IN: rosetta-code.truncatable-primes
CONSTANT: primes $[ 1,000,000 primes-upto reverse ]
: number>digits ( n -- B{} ) number>string string>digits ;
: no-zeros? ( seq -- ? ) [ zero? not ] all? ;
: all-prime? ( seq -- ? ... |
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
/ ... | #Action.21 | Action! | SET EndProg=* |
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... | #Haskell | Haskell |
Prelude> [1..10]
[1,2,3,4,5,6,7,8,9,10]
Prelude> map (^2) it
[1,4,9,16,25,36,49,64,81,100]
|
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... | #J | J | example=: *:, %: NB. *: is square, %: is square root
example 3
9 1.73205 |
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... | #jq | jq | julia> 3
3
julia> ans * ans, ans - 1
(9, 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... | #Julia | Julia | julia> 3
3
julia> ans * ans, ans - 1
(9, 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... | #Kotlin | Kotlin | // version 1.1.2
fun main(args: Array<String>) {
3.let {
println(it)
println(it * it)
println(Math.sqrt(it.toDouble()))
}
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #8080_Assembly | 8080 Assembly | org 100h
lhld 6 ; Top of CP/M usable memory
sphl ; Put the stack there
lxi b,0401h ; Set up first arguments to move()
lxi d,0203h
call move ; move(4, 1, 2, 3)
rst 0 ; quit program
;;; Move B disks from C via D to E.
move: dcr b ; One fewer disk in next iteration
jz mvout ; If this was the last disk, print mo... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <stdbool.h>
typedef double Fp;
typedef struct { Fp x, y, r; } Circle;
Circle circles[] = {
{ 1.6417233788, 1.6121789534, 0.0848270516},
{-1.4944608174, 1.2077959613, 1.1039549836},
{ 0.6110294452, -0.6907087527, 0.9089... |
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 ... | #Cowgol | Cowgol | include "cowgol.coh";
include "strings.coh";
include "malloc.coh";
###############################################################################
########################## Turing machine definition ##########################
###############################################################################
typedef Sym... |
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... | #AWK | AWK |
# syntax: GAWK -f TOTIENT_FUNCTION.AWK
BEGIN {
print(" N Phi isPrime")
for (n=1; n<=1000000; n++) {
tot = totient(n)
if (n-1 == tot) {
count++
}
if (n <= 25) {
printf("%2d %3d %s\n",n,tot,(n-1==tot)?"true":"false")
if (n == 25) {
printf("\n Limit Prim... |
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 ... | #Factor | Factor | USING: formatting kernel math math.combinatorics math.order
math.ranges sequences ;
FROM: sequences.private => exchange-unsafe ;
IN: rosetta-code.topswops
! Reverse a subsequence in-place from 0 to n.
: head-reverse! ( seq n -- seq' )
dupd [ 2/ ] [ ] bi rot
[ [ over - 1 - ] dip exchange-unsafe ] 2curry each-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 ... | #Fortran | Fortran | module top
implicit none
contains
recursive function f(x) result(m)
integer :: n, m, x(:),y(size(x)), fst
fst = x(1)
if (fst == 1) then
m = 0
else
y(1:fst) = x(fst:1:-1)
y(fst+1:) = x(fst+1:)
m = 1 + f(y)
end if
end function
recursive function perms(x) result(p)
integer, pointer :: p(:,... |
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... | #Axe | Axe | Disp sin(43)▶Dec,i
Disp cos(43)▶Dec,i
Disp tan⁻¹(10,10)▶Dec,i |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of... | #Commodore_BASIC | Commodore BASIC |
10 REM TRABB PARDO-KNUTH ALGORITHM
20 REM USED "MAGIC NUMBERS" BECAUSE OF STRICT SPECIFICATION OF THE ALGORITHM.
30 DEF FNF(N)=SQR(ABS(N))+5*N*N*N
40 DIM S(10)
50 PRINT "ENTER 11 NUMBERS."
60 FOR I=0 TO 10
70 PRINT STR$(I+1);
80 INPUT S(I)
90 NEXT I
100 PRINT
110 REM REVERSE
120 FOR I=0 TO 10/2
130 TMP=S(I)
140 S(I)=... |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of... | #Common_Lisp | Common Lisp | (defun read-numbers ()
(princ "Enter 11 numbers (space-separated): ")
(let ((numbers '()))
(dotimes (i 11 numbers)
(push (read) numbers))))
(defun trabb-pardo-knuth (func overflowp)
(let ((S (read-numbers)))
(format T "~{~a~%~}"
(substitute-if "Overflow!" overflowp (mapcar func 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... | #Phix | Phix | function s1(string s) return length(s)=12 end function
function s2(string s) return sum(sq_eq(s[7..12],'1'))=3 end function
function s3(string s) return sum(sq_eq(extract(s,tagset(12,2,2)),'1'))=2 end function
function s4(string s) return s[5]='0' or s[6..7]="11" end function
function s5(string s) return s[2..4]="000" ... |
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... | #Maxima | Maxima | /* Maxima already has the following logical operators
=, # (not equal), not, and, or
define some more and set 'binding power' (operator
precedence) for them
*/
infix("xor", 60)$
"xor"(A,B):= (A or B) and not(A and B)$
infix("=>", 59)$
"=>"(A,B):= not A or B$
/*
Substitute variables `r' in `e' with values ... |
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, ... | #PARI.2FGP | PARI/GP |
\\ Ulam spiral (plotting/printing)
\\ 4/19/16 aev
plotulamspir(n,pflg=0)={
my(n=if(n%2==0,n++,n),M=matrix(n,n),x,y,xmx,ymx,cnt,dir,n2=n*n,pch,sz=#Str(n2),pch2=srepeat(" ",sz));
if(pflg<0||pflg>2,pflg=0);
print(" *** Ulam spiral: ",n,"x",n," matrix, p-flag=",pflg);
x=y=n\2+1; xmx=ymx=cnt=1; dir="R";
for(i=1,n2,
if... |
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... | #Forth | Forth | : prime? ( n -- ? ) here + c@ 0= ;
: notprime! ( n -- ) here + 1 swap c! ;
: sieve ( n -- )
here over erase
0 notprime!
1 notprime!
2
begin
2dup dup * >
while
dup prime? if
2dup dup * do
i notprime!
dup +loop
then
1+
repeat
2drop ;
: left_truncatable_prime? ( n --... |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ ... | #Ada | Ada | with Ada.Text_Io; use Ada.Text_Io;
with Ada.Unchecked_Deallocation;
with Ada.Containers.Doubly_Linked_Lists;
procedure Tree_Traversal is
type Node;
type Node_Access is access Node;
type Node is record
Left : Node_Access := null;
Right : Node_Access := null;
Data : Integer;
end record;
... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | In[1]:= 3
Out[1]= 3
In[2]:= %1^2
Out[2]= 9
In[3]:= Sqrt[%%]
Out[3]= Sqrt[3]
In[4]:= N[Out[-1]] (* for floating point *)
Out[4]= 1.73205 |
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... | #Nim | Nim | for _ in 1..10:
echo "Hello World!" |
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... | #Oforth | Oforth | 3 dup sq swap sqrt |
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... | #PARI.2FGP | PARI/GP | 3
[sqrt(%),%^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... | #Perl | Perl | print sqrt . " " for (4, 16, 64) |
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... | #Phix | Phix | with javascript_semantics
object _
_ = 3
?_
?_*_
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #8086_Assembly | 8086 Assembly | cpu 8086
bits 16
org 100h
section .text
mov bx,0402h ; Set up first arguments to move()
mov cx,0103h ; Registers chosen s.t. CX contains output
;;; Move BH disks from CH via BL to CL
move: dec bh ; One fewer disk in next iteration
jz .out ; If this was last disk, just print move
push bx ; Save the registers ... |
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... | #11l | 11l | F token_with_escape(a, escape = ‘^’, separator = ‘|’)
[String] result
V token = ‘’
V state = 0
L(c) a
I state == 0
I c == escape
state = 1
E I c == separator
result.append(token)
token = ‘’
E
token ‘’= c
E I state == 1
... |
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... | #D | D | import std.stdio, std.math, std.algorithm, std.typecons, std.range;
alias Fp = real;
struct Circle { Fp x, y, r; }
void removeInternalDisks(ref Circle[] circles) pure nothrow @safe {
static bool isFullyInternal(in Circle c1, in Circle c2)
pure nothrow @safe @nogc {
if (c1.r > c2.r) // Quick exit.
... |
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 ... | #D | D | import std.stdio, std.algorithm, std.string, std.conv, std.array,
std.exception, std.traits, std.math, std.range;
struct UTM(State, Symbol, bool doShow=true)
if (is(State == enum) && is(Symbol == enum)) {
static assert(is(typeof({ size_t x = State.init; })),
"State must to be usable as ar... |
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... | #BQN | BQN | GCD ← {𝕨(|𝕊⍟(>⟜0)⊣)𝕩}
Totient ← +´1=⊢GCD¨1+↕ |
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 ... | #Go | Go | // Adapted from http://www-cs-faculty.stanford.edu/~uno/programs/topswops.w
// at Donald Knuth's web site. Algorithm credited there to Pepperdine
// and referenced to Mathematical Gazette 73 (1989), 131-133.
package main
import "fmt"
const ( // array sizes
maxn = 10 // max number of cards
maxl = 50 // uppe... |
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... | #BaCon | BaCon | ' Trigonometric functions in BaCon use Radians for input values
' The RAD() function converts from degrees to radians
FOR v$ IN "0, 10, 45, 90, 190.5"
d = VAL(v$) * 1.0
r = RAD(d) * 1.0
PRINT "Sine: ", d, " degrees (or ", r, " radians) is ", SIN(r)
PRINT "Cosine: ", d, " degrees (or ", r, " radians)... |
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... | #D | D | import std.stdio, std.math, std.conv, std.algorithm, std.array;
double f(in double x) pure nothrow {
return x.abs.sqrt + 5 * x ^^ 3;
}
void main() {
double[] data;
while (true) {
"Please enter eleven numbers on a line: ".write;
data = readln.split.map!(to!double).array;
if (dat... |
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... | #EchoLisp | EchoLisp |
(define (trabb-fun n)
(+ (* 5 n n n) (sqrt(abs n))))
(define (check-trabb n)
(if (number? n)
(if (<= (trabb-fun n) 400)
(printf "🌱 f(%d) = %d" n (trabb-fun n))
(printf "❌ f(%d) = %d" n (trabb-fun n)))
(error "not a number" n)))
(define (trabb (numlist null))
(while (< (length numlist) 11)
(set! num... |
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... | #Picat | Picat | % {{trans|Prolog}}
go ?=>
puzzle,
fail, % check for more answers
nl.
go => true.
puzzle =>
% 1. This is a numbered list of twelve statements.
L = [A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12],
L :: 0..1,
element(1, L, 1),
% 2. Exactly 3 of the last 6 statements are true.
A2 #<=> 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... | #Prolog | Prolog | puzzle :-
% 1. This is a numbered list of twelve statements.
L = [A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12],
L ins 0..1,
element(1, L, 1),
% 2. Exactly 3 of the last 6 statements are true.
A2 #<==> A7 + A8 + A9 + A10 + A11 + A12 #= 3,
% 3. Exactly 2 of the even-numbered stateme... |
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... | #Nim | Nim | import sequtils, strutils, sugar
# List of possible variables names.
const VarChars = {'A'..'E', 'G'..'S', 'U'..'Z'}
type
Expression = object
names: seq[char] # List of variables names.
values: seq[bool] # Associated values.
formula: string # Formula as a string.
proc initExpression(str... |
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, ... | #Pascal | Pascal |
Program Ulam; Uses crt;
{Concocted by R.N.McLean (whom God preserve), ex Victoria university, NZ.}
{$B- evaluate boolean expressions only so far as necessary.}
{$R+ range checking...}
FUNCTION Trim(S : string) : string;
var L1,L2 : integer;
BEGIN
L1 := 1;
WHILE (L1 <= LENGTH(S)) AND (S[L1] = ' ') DO INC(L1)... |
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... | #Fortran | Fortran | module primes_mod
implicit none
logical, allocatable :: primes(:)
contains
subroutine Genprimes(parr)
logical, intent(in out) :: parr(:)
integer :: i
! Prime sieve
parr = .true.
parr (1) = .false.
parr (4 : size(parr) : 2) = .false.
do i = 3, int (sqrt (real (size(parr)))), 2
if (parr(i)) parr... |
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
/ ... | #Agda | Agda | open import Data.List using (List; _∷_; []; concat)
open import Data.Nat using (ℕ; suc; zero)
open import Level using (Level)
open import Relation.Binary.PropositionalEquality using (_≡_; refl)
data Tree {a} (A : Set a) : Set a where
leaf : Tree A
node : A → Tree A → Tree A → Tree A
variable
a : Level
A : S... |
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... | #PicoLisp | PicoLisp | PicoLisp sets the value of the variable (symbol) '@' to the result of
conditional and controlling expressions in flow- and logic-functions (cond, if,
and, when, while, etc.).
Within a function or method '@' behaves like a local variable, i.e. its value is
automatically saved upon function entry and restored at exit.
... |
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... | #PowerShell | PowerShell |
65..67 | ForEach-Object {$_ * 2} # Multiply the numbers by 2
65..67 | ForEach-Object {[char]$_ } # ASCII values of the numbers
|
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... | #Python | Python | >>> 3
3
>>> _*_, _**0.5
(9, 1.7320508075688772)
>>> |
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... | #Racket | Racket |
#lang racket
(module topic1 racket
;; define $ as a "parameter", but make it look like a plain identifier
(provide $ (rename-out [$if if] [$#%app #%app]))
(define current-value (make-parameter #f))
(define-syntax $
(syntax-id-rules (set!)
[(_ x ...) ((current-value) x ...)]
[(set! _ val) (cu... |
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... | #Raku | Raku | $_ = 'Outside';
for <3 5 7 10> {
print $_;
.³.map: { say join "\t", '', $_, .², .sqrt, .log(2), OUTER::<$_>, UNIT::<$_> }
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #8th | 8th |
5 var, disks
var sa
var sb
var sc
: save sc ! sb ! sa ! disks ! ;
: get sa @ sb @ sc @ ;
: get2 get swap ;
: hanoi
save disks @ not if ;; then
disks @ get
disks @ n:1- get2 hanoi save
cr
" move a ring from " . sa @ . " to " . sb @ .
disks @ n:1- get2 rot hanoi
;
" Tower of Hanoi, with " . disks @ . " ring... |
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... | #8080_Assembly | 8080 Assembly | org 100h
jmp demo
;;; Routine to split a 0-terminated string
;;; Input: B=separator, C=escape, HL=string pointer.
;;; Output: DE=end of list of strings
;;; The split strings are stored in place.
split: mov d,h ; Set DE = output pointer
mov e,l
snext: mov a,m ; Get current input character
inx h ; Advance input 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... | #Action.21 | Action! | DEFINE PTR="CARD"
TYPE Tokens=[
PTR buf ;BYTE ARRAY
PTR arr ;CARD ARRAY
PTR endPtr
BYTE count]
PROC Init(Tokens POINTER t BYTE ARRAY b PTR ARRAY a)
t.buf=b
t.arr=a
t.endPtr=b
t.count=0
RETURN
PROC AddToken(Tokens POINTER t CHAR ARRAY s)
PTR ARRAY a
CHAR ARRAY tmp
a=t.arr
tmp=t.endPtr... |
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... | #EchoLisp | EchoLisp |
(lib 'math)
(define (make-circle x0 y0 r)
(vector x0 y0 r ))
(define-syntax-id _.radius (_ 2))
(define-syntax-id _.x0 (_ 0))
(define-syntax-id _.y0 (_ 1))
;; to sort circles
(define (cmp-circles a b) (> a.radius b.radius))
(define (included? circle: a circles)
(for/or ((b circles))
#:conti... |
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
... | #11l | 11l | V data = [
‘des_system_lib’ = Set(‘std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee’.split(‘ ’)),
‘dw01’ = Set(‘ieee dw01 dware gtech’.split(‘ ’)),
‘dw02’ = Set(‘ieee dw02 dware’.split(‘ ’)),
‘dw03’ = Set(‘std synopsys dware dw03 dw02 dw01 ieee gtech’.split(‘ ’)),... |
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 ... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | transitions(:
local :t {}
while /= ) dup:
set-to t swap & rot & rot rot &
t drop
take-from tape:
if tape:
pop-from tape
else:
:B
paste-together a h b:
push-to b h
while a:
push-to b pop-from a
b
universal-turing-machine transitions initial final tape:
local :tape-left []
local :state initial
... |
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 | C |
/*Abhishek Ghosh, 7th December 2018*/
#include<stdio.h>
int totient(int n){
int tot = n,i;
for(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)
tot-=tot/n;
return tot;
}
int main()
{
int count = 0,n,tot;
printf(" n %c prime",237);... |
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 ... | #Haskell | Haskell | import Data.List (permutations)
topswops :: Int -> Int
topswops n = maximum $ map tops $ permutations [1 .. n]
where
tops (1:_) = 0
tops xa@(x:_) = 1 + tops reordered
where
reordered = reverse (take x xa) ++ drop x xa
main =
mapM_ (putStrLn . ((++) <$> show <*> (":\t" ++) . show . topswops... |
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... | #BASIC | BASIC | pi = 3.141592653589793#
radians = pi / 4 'a.k.a. 45 degrees
degrees = 45 * pi / 180 'convert 45 degrees to radians once
PRINT SIN(radians) + " " + SIN(degrees) 'sine
PRINT COS(radians) + " " + COS(degrees) 'cosine
PRINT TAN(radians) + " " + TAN (degrees) 'tangent
'arcsin
thesin = SIN(radians)
arcsin = ATN(thesin / SQR(... |
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... | #Ela | Ela | open monad io number string
:::IO
take_numbers 0 xs = do
return $ iter xs
where f x = sqrt (toSingle x) + 5.0 * (x ** 3.0)
p x = x < 400.0
iter [] = return ()
iter (x::xs)
| p res = do
putStrLn (format "f({0}) = {1}" x res)
iter xs
| else ... |
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... | #Elena | Elena | import extensions;
import extensions'math;
public program()
{
real[] inputs := new real[](11);
console.printLine("Please enter 11 numbers :");
for(int i := 0, i < 11, i += 1)
{
inputs[i] := console.readLine().toReal()
};
console.printLine("Evaluating f(x) = |x|^0.5 + 5x^3 for the giv... |
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... | #Python | Python |
from itertools import product
#from pprint import pprint as pp
constraintinfo = (
(lambda st: len(st) == 12 ,(1, 'This is a numbered list of twelve statements')),
(lambda st: sum(st[-6:]) == 3 ,(2, 'Exactly 3 of the last 6 statements are true')),
(lambda st: sum(st[1::2]) == 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... | #PARI.2FGP | PARI/GP | vars(P)={
my(v=List(),x);
while(type(P)=="t_POL",
x=variable(P);
listput(v,x);
P=subst(P,x,1)
);
Vec(v)
};
truthTable(P)={
my(var=vars(P),t,b);
for(i=0,2^#var-1,
t=eval(P);
for(j=1,#var,
b=bittest(i,j-1);
t=subst(t,var[j],b);
... |
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, ... | #Perl | Perl | use ntheory qw/is_prime/;
use Imager;
my $n = shift || 512;
my $start = shift || 1;
my $file = "ulam.png";
sub cell {
my($n, $x, $y, $start) = @_;
$y -= $n>>1;
$x -= ($n-1)>>1;
my $l = 2*(abs($x) > abs($y) ? abs($x) : abs($y));
my $d = ($y > $x) ? $l*3 + $x + $y : $l-$x-$y;
($l-1)**2 + $d + $start - ... |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function isPrime(n As Integer) As Boolean
If n Mod 2 = 0 Then Return n = 2
If n Mod 3 = 0 Then Return n = 3
Dim d As Integer = 5
While d * d <= n
If n Mod d = 0 Then Return False
d += 2
If n Mod d = 0 Then Return False
d += 4
Wend
Return True
End Function
Dim As UIntege... |
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
/ ... | #ALGOL_68 | ALGOL 68 | MODE VALUE = INT;
PROC value repr = (VALUE value)STRING: whole(value, 0);
MODE NODES = STRUCT ( VALUE value, REF NODES left, right);
MODE NODE = REF NODES;
PROC tree = (VALUE value, NODE left, right)NODE:
HEAP NODES := (value, left, right);
PROC preorder = (NODE node, PROC (VALUE)VOID action)VOID:
IF node ISN... |
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... | #REXX | REXX | /*REXX program shows something close to a "topic variable" (for functions/subroutines).*/
parse arg N /*obtain a variable from the cmd line. */
call squareIt N /*invoke a function to square da number*/
say result ' ◄───' ... |
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... | #Ring | Ring |
see "sum1 = " + sum1(1,2) + nl
see "sum2 = " + sum2(2,3) + nl
func sum1 (x, y)
sum = x + y
return sum
func sum2 (x, y)
return x + y
|
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... | #Ruby | Ruby | while DATA.gets # assigns to $_ (local scope)
print # If no arguments are given, prints $_
end
__END__
This is line one
This is line two
This is line three |
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... | #Scala | Scala | object TopicVar extends App {
class SuperString(val org: String){
def it(): Unit = println(org)
}
new SuperString("FvdB"){it()}
new SuperString("FvdB"){println(org)}
Seq(1).foreach {println}
Seq(2).foreach {println(_)}
Seq(4).foreach { it => println(it)}
Seq(8).foreach { it => println(it + it)}
... |
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.