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/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, ... | #Haskell | Haskell | import Data.List
import Data.Numbers.Primes
ulam n representation = swirl n . map representation |
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... | #C.2B.2B | C++ | #include <iostream>
#include "prime_sieve.hpp"
bool is_left_truncatable(const prime_sieve& sieve, int p) {
for (int n = 10, q = p; p > n; n *= 10) {
if (!sieve.is_prime(p % n) || q == p % n)
return false;
q = p % n;
}
return true;
}
bool is_right_truncatable(const prime_sieve... |
http://rosettacode.org/wiki/Unbias_a_random_generator | Unbias a random generator |
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
Task details
Use your language's random number generator to create a function/method/sub... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Dim random As New Random()
Function RandN(n As Integer) As Boolean
Return random.Next(0, n) = 0
End Function
Function Unbiased(n As Integer) As Boolean
Dim flip1 As Boolean
Dim flip2 As Boolean
Do
flip1 = RandN(n)
flip2 = RandN... |
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... | #PicoLisp | PicoLisp | (de truncate (File Len)
(native "@" "truncate" 'I File Len) ) |
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... | #PL.2FI | PL/I |
/* Parameters to be read in by the program are: */
/* 1. the name of the file to be truncated, and */
/* 2. the size of file after truncation. */
truncate_file: procedure options (main); /* 12 July 2012 */
declare (i, n) fixed binary (31);
declare filename character(50) varying;
declare in fil... |
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 ... | #APL | APL | :Namespace Turing
⍝ Run Turing machine until it halts
∇r←RunTuring (rules init halts blank itape);state;rt;lt;next
state←init
lt←⍬
rt←,blank
:If 0≠≢itape ⋄ rt←itape ⋄ :EndIf
:While ~(⊂state)∊halts
next←((⊂state(⊃rt))≡¨↓rules[... |
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... | #ActionScript | ActionScript | trace("Radians:");
trace("sin(Pi/4) = ", Math.sin(Math.PI/4));
trace("cos(Pi/4) = ", Math.cos(Math.PI/4));
trace("tan(Pi/4) = ", Math.tan(Math.PI/4));
trace("arcsin(0.5) = ", Math.asin(0.5));
trace("arccos(0.5) = ", Math.acos(0.5));
trace("arctan(0.5) = ", Math.atan(0.5));
trace("arctan2(-1,-2) = ", Math.atan2(-1,-2));... |
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... | #Agena | Agena | scope # TPK algorithm in Agena
local y;
local a := [];
local f := proc( t :: number ) is return sqrt(abs(t))+5*t*t*t end;
for i from 0 to 10 do a[i] := tonumber( io.read() ) od;
for i from 10 to 0 by - 1 do
y:=f(a[i]);
if y > 400
then print( "TOO LARGE" )
else printf( "%10.4f\n", y )... |
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... | #ALGOL_60 | ALGOL 60 | begin
integer i; real y; real array a[0:10];
real procedure f(t); value t; real t;
f:=sqrt(abs(t))+5*t^3;
for i:=0 step 1 until 10 do inreal(0, a[i]);
for i:=10 step -1 until 0 do
begin
y:=f(a[i]);
if y > 400 then outstring(1, "TOO LARGE")
else outreal(1,y);
outch... |
http://rosettacode.org/wiki/Tree_from_nesting_levels | Tree from nesting levels | Given a flat list of integers greater than zero, representing object nesting
levels, e.g. [1, 2, 4],
generate a tree formed from nested lists of those nesting level integers where:
Every int appears, in order, at its depth of nesting.
If the next level int is greater than the previous then it appears in a sub-list o... | #Phix | Phix | function test(sequence s, integer level=1, idx=1)
sequence res = {}, part
while idx<=length(s) do
switch compare(s[idx],level) do
case +1: {idx,part} = test(s,level+1,idx)
res = append(res,part)
case 0: res &= s[idx]
case -1: idx -= 1 exit
... |
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... | #Go | Go | package main
import "fmt"
// its' not too much more work to check all the permutations concurrently
var solution = make(chan int)
var nearMiss = make(chan int)
var done = make(chan bool)
func main() {
// iterate and use the bits as the permutation
for i := 0; i < 4096; i++ {
go checkPerm(i)
}
... |
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... | #Go | Go | package main
import (
"bufio"
"errors"
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"reflect"
)
func main() {
in := bufio.NewScanner(os.Stdin)
for {
fmt.Print("Expr: ")
in.Scan()
if err := in.Err(); err != nil {
fmt.Println(err)
... |
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, ... | #J | J | spiral =: ,~ $ [: /: }.@(2 # >:@i.@-) +/\@# <:@+: $ (, -)@(1&,) |
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... | #Clojure | Clojure | (use '[clojure.contrib.lazy-seqs :only [primes]])
(def prime?
(let [mem (ref #{})
primes (ref primes)]
(fn [n]
(dosync
(if (< n (first @primes))
(@mem n)
(let [[mems ss] (split-with #(<= % n) @primes)]
(ref-set primes ss)
((commute mem into mems) n)))))))
(defn drop-lefts [n]
(let ... |
http://rosettacode.org/wiki/Unbias_a_random_generator | Unbias a random generator |
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
Task details
Use your language's random number generator to create a function/method/sub... | #Wren | Wren | import "random" for Random
import "/fmt" for Fmt
var rand = Random.new()
var biased = Fn.new { |n| rand.float() < 1 / n }
var unbiased = Fn.new { |n|
while (true) {
var a = biased.call(n)
var b = biased.call(n)
if (a != b) return a
}
}
var m = 50000
var f = "$d: $2.2f\% $2.2f\%"... |
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... | #PowerBASIC | PowerBASIC | SUB truncateFile (file AS STRING, length AS DWORD)
IF LEN(DIR$(file)) THEN
DIM f AS LONG
f = FREEFILE
OPEN file FOR BINARY AS f
IF length > LOF(f) THEN
CLOSE f
ERROR 62 'Input past end
ELSE
SEEK f, length + 1
SETEOF f
... |
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... | #Powershell | Powershell | Function Truncate-File(fname) {
$null | Set-Content -Path "$fname"
}
|
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... | #PureBasic | PureBasic | Procedure SetFileSize(File$, length.q)
Protected fh, pos, i
If FileSize(File$) < length
Debug "File to small, is a directory or does not exist."
ProcedureReturn #False
Else
fh = OpenFile(#PB_Any, File$)
FileSeek(fh, length)
TruncateFile(fh)
CloseFile(fh)
EndIf
ProcedureReturn #True
En... |
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 ... | #AutoHotkey | AutoHotkey | ; By Uberi, http://www.autohotkey.com/board/topic/58599-turing-machine/
SetBatchLines, -1
OnExit, Exit
SaveFilePath := A_ScriptFullPath ".ini"
; Defaults are for a 2-state_3-symbol turning machine. Format:
; machine state symbol on tape, symbol on tape | tape shift (- is left, + is right, 0 is halt) | machine state
, R... |
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... | #Ada | Ada | with Ada.Numerics.Elementary_Functions;
use Ada.Numerics.Elementary_Functions;
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
with Ada.Text_IO; use Ada.Text_IO;
procedure Trig is
Degrees_Cycle : constant Float := 360.0;
Radians_Cycle : constant Float := 2.0 * Ada.Numerics.Pi;
Angle_Degrees : constant Float :... |
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... | #ALGOL_68 | ALGOL 68 | [ 0 : 10 ]REAL a;
PROC f = ( REAL t )REAL:
sqrt(ABS t)+5*t*t*t;
FOR i FROM LWB a TO UPB a DO read( ( a[ i ] ) ) OD;
FOR i FROM UPB a BY -1 TO LWB a DO
REAL y=f(a[i]);
IF y > 400 THEN print( ( "TOO LARGE", newline ) )
ELSE print( ( fixed( y, -9, 4 ), newline ) )
FI
OD |
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... | #ALGOL_W | ALGOL W | begin
real y; real array a( 0 :: 10 );
real procedure f( real value t );
sqrt(abs(t))+5*t*t*t;
for i:=0 until 10 do read( a(i) );
r_format := "A"; r_w := 9; r_d := 4;
for i:=10 step -1 until 0 do
begin
y:=f(a(i));
if y > 400 then write( "TOO LARGE" )
else write( y );
... |
http://rosettacode.org/wiki/Tree_from_nesting_levels | Tree from nesting levels | Given a flat list of integers greater than zero, representing object nesting
levels, e.g. [1, 2, 4],
generate a tree formed from nested lists of those nesting level integers where:
Every int appears, in order, at its depth of nesting.
If the next level int is greater than the previous then it appears in a sub-list o... | #Python | Python | def to_tree(x, index=0, depth=1):
so_far = []
while index < len(x):
this = x[index]
if this == depth:
so_far.append(this)
elif this > depth:
index, deeper = to_tree(x, index, depth + 1)
so_far.append(deeper)
else: # this < depth:
index -=1
... |
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... | #Groovy | Groovy | enum Rule {
r01( 1, { r()*.num == (1..12) }),
r02( 2, { r(7..12).count { it.truth } == 3 }),
r03( 3, { r(2..12, 2).count { it.truth } == 2 }),
r04( 4, { r(5).truth ? r(6).truth && r(7).truth : true }),
r05( 5, { r(2..4).count { it.truth } == 0 }),
r06( 6, { r(1..11, 2).count { it.truth } == 4 })... |
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... | #Haskell | Haskell | import Control.Monad (mapM, foldM, forever)
import Data.List (unwords, unlines, nub)
import Data.Maybe (fromJust)
truthTable expr = let
tokens = words expr
operators = ["&", "|", "!", "^", "=>"]
variables = nub $ filter (not . (`elem` operators)) tokens
table = zip variables <$> mapM (const [True,Fals... |
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, ... | #Java | Java | import java.util.Arrays;
public class Ulam{
enum Direction{
RIGHT, UP, LEFT, DOWN;
}
private static String[][] genUlam(int n){
return genUlam(n, 1);
}
private static String[][] genUlam(int n, int i){
String[][] spiral = new String[n][n];
Direction dir = Direction.RIGHT;
int j = i;
int y = n / 2;
... |
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... | #CoffeeScript | CoffeeScript | # You could have symmetric algorithms for max right and left
# truncatable numbers, but they lend themselves to slightly
# different optimizations.
max_right_truncatable_number = (n, f) ->
# This algorithm only evaluates 37 numbers for primeness to
# get the max right truncatable prime < 1000000. Its
# optimiz... |
http://rosettacode.org/wiki/Unbias_a_random_generator | Unbias a random generator |
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
Task details
Use your language's random number generator to create a function/method/sub... | #zkl | zkl | fcn randN(N){ (not (0).random(N)).toInt() }
fcn unbiased(randN){ while((a:=randN())==randN()){} a } |
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... | #Python | Python |
def truncate_file(name, length):
if not os.path.isfile(name):
return False
if length >= os.path.getsize(name):
return False
with open(name, 'ab') as f:
f.truncate(length)
return True
|
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... | #R | R |
truncate_file <- function(filename, n_bytes) {
# check file exists and size is greater than n_bytes
stopifnot(
"file does not exist"= file.exists(filename),
"not enough bytes in file"= file.size(filename) >= n_bytes
)
# read bytes from input file
input.con <- file(filename, "rb")
bindata <- re... |
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... | #Racket | Racket |
#lang racket
(define (truncate file size)
(unless (file-exists? file) (error 'truncat "missing file: ~a" file))
(when (> size (file-size file)) (printf "Warning: extending file size.\n"))
(call-with-output-file* file #:exists 'update
(λ(o) (file-truncate o size))))
|
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 ... | #BASIC | BASIC | • R$(), an array of rules;
• T$, an input tape (where an empty string stands for a blank tape);
• B$, a character to use as a blank;
• S$, an initial state;
• H$, a halting state.
|
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... | #11l | 11l | F f(n)
R sum((1..n).filter(k -> gcd(@n, k) == 1).map(k -> 1))
F is_prime(n)
R f(n) == n - 1
L(n) 1..25
print(‘ f(#.) == #.’.format(n, f(n))‘’(I is_prime(n) {‘, is prime’} E ‘’))
V count = 0
L(n) 1..10'000
count += is_prime(n)
I n C (100, 1000, 10'000)
print(‘Primes up to #.: #.’.format(n, count... |
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 ... | #11l | 11l | V best = [0] * 16
F try_swaps(&deck, f, =s, d, n)
I d > :best[n]
:best[n] = d
V i = 0
V k = 1 << s
L s != 0
k >>= 1
s--
I deck[s] == -1 | deck[s] == s
L.break
i [|]= k
I (i [&] f) == i & d + :best[s] <= :best[n]
R d
s++
V deck2 = copy(deck)
... |
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... | #ALGOL_68 | ALGOL 68 | main:(
REAL pi = 4 * arc tan(1);
# Pi / 4 is 45 degrees. All answers should be the same. #
REAL radians = pi / 4;
REAL degrees = 45.0;
REAL temp;
# sine #
print((sin(radians), " ", sin(degrees * pi / 180), new line));
# cosine #
print((cos(radians), " ", cos(degrees * pi / 180), new line));
# tangen... |
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... | #APL | APL | ∇ {res}←Trabb;f;S;i;a;y ⍝ define a function Trabb
f←{(0.5*⍨|⍵)+5×⍵*3} ⍝ define a function f
S←,⍎{⍞←⍵ ⋄ (≢⍵)↓⍞}'Please, enter 11 numbers: '
:For i a :InEach (⌽⍳≢S)(⌽S) ⍝ loop through N..1 and reversed S
:If 400<y←f(a)
⎕←'Too large: ',⍕i
:Else
⎕←i,y... |
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... | #Arturo | Arturo | proc: function [x]->
((abs x) ^ 0.5) + 5 * x ^ 3
ask: function [msg][
to [:floating] first.n: 11 split.words strip input msg
]
loop reverse ask "11 numbers: " 'n [
result: proc n
print [n ":" (result > 400)? -> "TOO LARGE!" -> result]
] |
http://rosettacode.org/wiki/Tree_from_nesting_levels | Tree from nesting levels | Given a flat list of integers greater than zero, representing object nesting
levels, e.g. [1, 2, 4],
generate a tree formed from nested lists of those nesting level integers where:
Every int appears, in order, at its depth of nesting.
If the next level int is greater than the previous then it appears in a sub-list o... | #Quackery | Quackery | [ stack ] is prev ( --> s )
[ temp take
swap join
temp put ] is add$ ( x --> )
[ dup [] = if done
0 prev put
$ "' " temp put
witheach
[ dup prev take -
over prev put
dup 0 > iff
[ times
[ $ "... |
http://rosettacode.org/wiki/Tree_from_nesting_levels | Tree from nesting levels | Given a flat list of integers greater than zero, representing object nesting
levels, e.g. [1, 2, 4],
generate a tree formed from nested lists of those nesting level integers where:
Every int appears, in order, at its depth of nesting.
If the next level int is greater than the previous then it appears in a sub-list o... | #Raku | Raku | sub new_level ( @stack --> Nil ) {
my $e = [];
push @stack.tail, $e;
push @stack, $e;
}
sub to_tree_iterative ( @xs --> List ) {
my $nested = [];
my @stack = $nested;
for @xs -> Int $x {
new_level(@stack) while $x > @stack;
pop @stack while $x < @stack;
pus... |
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... | #Haskell | Haskell | import Data.List (findIndices)
tf :: [[Int] -> Bool] -> [[Int]]
tf = traverse (const [1, 0])
wrongness :: [Int] -> [[Int] -> Bool] -> [Int]
wrongness ns ps = findIndices id (zipWith (/=) ns (map (fromEnum . ($ ns)) ps))
statements :: [[Int] -> Bool]
statements =
[ (== 12) . length
, 3 ⊂ [length statements - 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... | #J | J | truthTable=:3 :0
assert. -. 1 e. 'data expr names table' e.&;: y
names=. ~. (#~ _1 <: nc) ;:expr=. y
data=. #:i.2^#names
(names)=. |:data
(' ',;:inv names,<expr),(1+#@>names,<expr)":data,.".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, ... | #JavaScript | JavaScript |
<!-- UlamSpiral.html -->
<html>
<head><title>Ulam Spiral</title>
<script src="VOE.js"></script>
<script>
// http://rosettacode.org/wiki/User:AnatolV/Helper_Functions
// Use v.2.0
var pst;
// ***** Additional helper functions
// Pad number from left
function padLeft(n,ns) {
return (" " + n).slice(-ns);
}
... |
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... | #Common_Lisp | Common Lisp |
(defun start ()
(format t "Largest right-truncatable ~a~%" (max-right-truncatable))
(format t "Largest left-truncatable ~a~%" (max-left-truncatable)))
(defun max-right-truncatable ()
(loop for el in (6-digits-R-truncatables)
maximizing el into max
finally (return max)))
(defun 6-digits-R-tr... |
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... | #Raku | Raku | use NativeCall;
sub truncate(Str, int32 --> int32) is native {*}
sub MAIN (Str $file, Int $to) {
given $file.IO {
.e or die "$file doesn't exist";
.w or die "$file isn't writable";
.s >= $to or die "$file is not big enough to truncate";
}
truncate($file, $to) == 0 ... |
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... | #REXX | REXX | /*REXX program truncates a file to a specified (and smaller) number of bytes. */
parse arg siz FID /*obtain required arguments from the CL*/
FID=strip(FID) /*elide FID leading/trailing blanks. */
if siz=='' then call ser "No trunca... |
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 ... | #C | C | #include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
enum {
LEFT,
RIGHT,
STAY
};
typedef struct {
int state1;
int symbol1;
int symbol2;
int dir;
int state2;
} transition_t;
typedef struct tape_t tape_t;
struct tape_t {
int symbol;
tape_t *left;
... |
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... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program totient.s */
/************************************/
/* Constantes */
/************************************/
.include "../includeConstantesARM64.inc"
.equ MAXI, 25
/*********************************/
/* Initialized data ... |
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 ... | #360_Assembly | 360 Assembly | * Topswops optimized 12/07/2016
TOPSWOPS CSECT
USING TOPSWOPS,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) " <-
ST R15,8(R13) ... |
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 ... | #Ada | Ada | with Ada.Integer_Text_IO, Generic_Perm;
procedure Topswaps is
function Topswaps(Size: Positive) return Natural is
package Perms is new Generic_Perm(Size);
P: Perms.Permutation;
Done: Boolean;
Max: Natural;
function Swapper_Calls(P: Perms.Permutation) return Natural is
Q: Perms.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... | #ALGOL_W | ALGOL W | begin
% Algol W only supplies sin, cos and arctan as standard. We can define %
% arcsin, arccos and tan functions using these. The standard functions %
% use radians so we also provide versions that use degrees %
% convert degrees to radians %
real procedure toRadians( real ... |
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... | #ASIC | ASIC |
REM Trabb Pardo-Knuth algorithm
REM Used "magic numbers" because of strict specification of the algorithm.
DIM S@(10)
PRINT "Enter 11 numbers."
FOR I = 0 TO 10
I1= I + 1
PRINT I1;
PRINT " => ";
INPUT TMP@
S@(I) = TMP@
NEXT I
PRINT
REM Reverse
HALFIMAX = 10 / 2
FOR I = 0 TO HALFIMAX
IREV = 10 - I
TMP@ = ... |
http://rosettacode.org/wiki/Tree_from_nesting_levels | Tree from nesting levels | Given a flat list of integers greater than zero, representing object nesting
levels, e.g. [1, 2, 4],
generate a tree formed from nested lists of those nesting level integers where:
Every int appears, in order, at its depth of nesting.
If the next level int is greater than the previous then it appears in a sub-list o... | #Wren | Wren | import "/seq" for Stack
import "/fmt" for Fmt
var toTree = Fn.new { |list|
var nested = []
var s = Stack.new()
s.push(nested)
for (n in list) {
while (n != s.count) {
if (n > s.count) {
var inner = []
s.peek().add(inner)
s.push(inner)... |
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... | #J | J | apply
128!:2
NB. example
'*:' apply 1 2 3
1 4 9 |
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... | #Java | Java |
public class LogicPuzzle
{
boolean S[] = new boolean[13];
int Count = 0;
public boolean check2 ()
{
int count = 0;
for (int k = 7; k <= 12; k++)
if (S[k]) count++;
return S[2] == (count == 3);
}
public boolean check3 ()
{
int count = 0;
... |
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... | #Java | Java | import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
public class TruthTable {
public static void main( final String... args ) {
System.out.println( new Tr... |
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, ... | #jq | jq | def array($init): [range(0; .) | $init];
# Test if input is a one-character string holding a digit
def isDigit:
type=="string" and length==1 and explode[0] as $c | (48 <= $c and $c <= 57);
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
def generate($n; $i; $c):
if $n <= 1 then "'n' mu... |
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... | #D | D | import std.stdio, std.math, std.string, std.conv, std.algorithm,
std.range;
bool isPrime(in int n) pure nothrow {
if (n <= 1)
return false;
foreach (immutable i; 2 .. cast(int)sqrt(real(n)) + 1)
if (!(n % i))
return false;
return true;
}
bool isTruncatablePrime(bool le... |
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... | #Ring | Ring |
file = "C:\Ring\ReadMe.txt"
fp = read(file)
fpstr = left(fp, 100)
see fpstr + nl
write(file, fpstr)
|
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... | #Ruby | Ruby | # Open a file for writing, and truncate it to 1234 bytes.
File.open("file", "ab") do |f|
f.truncate(1234)
f << "Killroy was here" # write to file
end # file is closed now.
# Just truncate a file to 567 bytes.
File.truncate("file", 567) |
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... | #Rust | Rust | use std::path::Path;
use std::fs;
fn truncate_file<P: AsRef<Path>>(filename: P, filesize: usize) -> Result<(), Error> {
use Error::*;
let file = fs::read(&filename).or(Err(NotFound))?;
if filesize > file.len() {
return Err(FilesizeTooSmall)
}
fs::write(&filename, &file[..filesize]).or(... |
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 ... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
public class TuringMachine
{
public static async Task Main() {
var fiveStateBusyBeaver = new TuringMachine("A", '0', "H").WithTransitions(
... |
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... | #Ada | Ada | with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Totient is
function Totient (N : in Integer) return Integer is
Tot : Integer := N;
I : Integer;
N2 : Integer := N;
begin
I := 2;
while I * I <= N2 loop
if N2 mod I = 0 then
while N2 mod I = 0 loop
... |
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 ... | #AutoHotkey | AutoHotkey | Topswops(Obj, n){
R := []
for i, val in obj{
if (i <=n)
res := val (A_Index=1?"":",") res
else
res .= "," val
}
Loop, Parse, res, `,
R[A_Index]:= A_LoopField
return R
} |
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 ... | #C | C | #include <stdio.h>
#include <string.h>
typedef struct { char v[16]; } deck;
typedef unsigned int uint;
uint n, d, best[16];
void tryswaps(deck *a, uint f, uint s) {
# define A a->v
# define B b.v
if (d > best[n]) best[n] = d;
while (1) {
if ((A[s] == s || (A[s] == -1 && !(f & 1U << s)))
&& (d + best[s] >= ... |
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... | #Arturo | Arturo | pi: 4*atan 1.0
radians: pi/4
degrees: 45.0
print "sine"
print [sin radians, sin degrees*pi/180]
print "cosine"
print [cos radians, cos degrees*pi/180]
print "tangent"
print [tan radians, tan degrees*pi/180]
print "arcsine"
print [asin sin radians, (asin sin radians)*180/pi]
print "arccosine"
print [acos cos... |
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... | #AutoIt | AutoIt | ; Trabb Pardo–Knuth algorithm
; by James1337 (autoit.de)
; AutoIt Version: 3.3.8.1
Local $S, $i, $y
Do
$S = InputBox("Trabb Pardo–Knuth algorithm", "Please enter 11 numbers:", "1 2 3 4 5 6 7 8 9 10 11")
If @error Then Exit
$S = StringSplit($S, " ")
Until ($S[0] = 11)
For $i = 11 To 1 Step -1
$y = f($S[$i])
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... | #jq | jq | def indexed(filter):
. as $in
| reduce range(0;length) as $i ([]; if ($i | filter) then . + [$in[$i]] else . end);
def count(value): map(select(. == value)) | length;
# The truth or falsity of the 12 statements can be captured in an array of size 12:
def generate(k):
if k == 1 then [true], [false]
else gene... |
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... | #Julia | Julia | using Printf
function showflaggedbits{T<:BitArray{1}}(a::T, f::T)
tf = map(x->x ? "T" : "F", a)
flg = map(x->x ? "*" : " ", f)
join(tf .* flg, " ")
end
const props = [s -> length(s) == 12,
s -> sum(s[7:12]) == 3,
s -> sum(s[2:2:end]) == 2,
s -> !s[5] || (s[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... | #JavaScript | JavaScript | <!DOCTYPE html><html><head><title>Truth table</title><script>
var elem,expr,vars;
function isboolop(chr){return "&|!^".indexOf(chr)!=-1;}
function varsindexof(chr){
var i;
for(i=0;i<vars.length;i++){if(vars[i][0]==chr)return i;}
return -1;
}
function printtruthtable(){
var i,str;
elem=document.creat... |
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, ... | #Julia | Julia | using Primes
function ulamspiral(ord::Int)
# Possible directions
dirs = [[0, 1], [-1, 0], [0, -1], [1, 0]]
# fdir = ["→", "↑", "←", "↓"] # for debug pourpose
cur = maxsteps = 1 # starting direction & starting max steps
steps = n = 0 # starting steps & starting number in cell
pos = [... |
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... | #EchoLisp | EchoLisp |
;; does p include a 0 in its decimal representation ?
(define (nozero? n) (= -1 (string-index (number->string n) "0")))
;; right truncate : p and successive quotients by 10 (integer division) must be primes
(define (right-trunc p) (unless (zero? p)
(and (prime? p) (right-trunc (quotient p 10)))))
(remember 'right... |
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... | #Scala | Scala | import java.io.FileOutputStream
object TruncFile extends App {
if (args.length < 2) println("Usage: java TruncFile fileName newSize")
else { //turn on "append" so it doesn't clear the file
val outChan = new FileOutputStream(args(0), true).getChannel()
val newSize = args(1).toLong
outChan.truncate(newS... |
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... | #Sidef | Sidef | func truncate(filename, len) {
var file = File(filename);
len > file.size ->
&& die "The provided length is greater than the length of the file";
file.truncate(len);
}
# truncate "file.ext" to 1234 bytes
truncate("file.ext", 1234); |
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 ... | #C.2B.2B | C++ |
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <iomanip>
//--------------------------------------------------------------------------------------------------
typedef unsigned int uint;
using namespace std;
const uint TAPE_MAX_LEN = 49152;
//-------------------... |
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... | #ALGOL_68 | ALGOL 68 | BEGIN
# returns the number of integers k where 1 <= k <= n that are mutually prime to n #
PROC totient = ( INT n )INT:
IF n < 3 THEN 1
ELIF n = 3 THEN 2
ELSE
INT result := n;
INT v := n;
INT i := 2;
WHILE i * i <= v DO
... |
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 ... | #C.2B.2B | C++ |
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
int topswops(int n) {
std::vector<int> list(n);
std::iota(std::begin(list), std::end(list), 1);
int max_steps = 0;
do {
auto temp_list = list;
for (int steps = 1; temp_list[0] != 1; ++steps) {
std::reverse(std::begin... |
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... | #Asymptote | Asymptote | real pi = 4 * atan(1);
real radian = pi / 4.0;
real angulo = 45.0 * pi / 180;
write("Radians : ", radian);
write("Degrees : ", angulo / pi * 180);
write();
write("Sine : ", sin(radian), sin(angulo));
write("Cosine : ", cos(radian), cos(angulo));
write("Tangent : ", tan(radian), tan(angulo));
... |
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... | #AWK | AWK |
# syntax: GAWK -f TRABB_PARDO-KNUTH_ALGORITHM.AWK
BEGIN {
printf("enter 11 numbers: ")
getline S
n = split(S,arr," ")
if (n != 11) {
printf("%d numbers entered; S/B 11\n",n)
exit(1)
}
for (i=n; i>0; i--) {
x = f(arr[i])
printf("f(%s) = %s\n",arr[i],(x>400) ? "too large"... |
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... | #Kotlin | Kotlin | // version 1.1.3
typealias Predicate = (String) -> Boolean
val predicates = listOf<Predicate>(
{ it.length == 13 }, // indexing starts at 0 but first bit ignored
{ (7..12).count { i -> it[i] == '1' } == 3 },
{ (2..12 step 2).count { i -> it[i] == '1' } == 2 },
{ it[5] == '0' || (it[6] == '1' && it... |
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... | #Julia | Julia | module TruthTable
using Printf
using MacroTools
isvariablename(::Any) = false
isvariablename(s::Symbol) = all(x -> isletter(x) || x == '_', string(s))
function table(expr)
if !isvariablename(expr) && !Meta.isexpr(expr, :call)
throw(ArgumentError("expr must be a boolean expression"))
end
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, ... | #Kotlin | Kotlin | object Ulam {
fun generate(n: Int, i: Int = 1, c: Char = '*') {
require(n > 1)
val s = Array(n) { Array(n, { "" }) }
var dir = Direction.RIGHT
var y = n / 2
var x = if (n % 2 == 0) y - 1 else y // shift left for even n's
for (j in i..n * n - 1 + i) {
s[y][... |
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... | #Eiffel | Eiffel |
class
APPLICATION
create
make
feature
make
do
io.put_string ("Largest right truncatable prime: " + find_right_truncatable_primes.out)
io.new_line
io.put_string ("Largest left truncatable prime: " + find_left_truncatable_primes.out)
end
find_right_truncatable_primes: INTEGER
-- Largest righ... |
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... | #Standard_ML | Standard ML | local
open Posix.FileSys
val perm = S.flags [S.irusr, S.iwusr, S.irgrp, S.iwgrp, S.iroth, S.iwoth]
in
fun truncate (path, len) =
let
val fd = createf (path, O_WRONLY, O.noctty, perm)
in
ftruncate (fd, len); Posix.IO.close fd
end
end |
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... | #Tcl | Tcl | package require Tcl 8.5
set f [open "file" r+]; # Truncation is done on channels
chan truncate $f 1234; # Truncate at a particular length (in bytes)
close $f |
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... | #UNIX_Shell | UNIX Shell | # Truncate a file named "myfile" to 1440 kilobytes.
ls myfile >/dev/null &&
dd if=/dev/null of=myfile bs=1 seek=1440k |
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
/ ... | #11l | 11l | T Node
Int data
Node? left
Node? right
F (data, Node? left = N, Node? right = N)
.data = data
.left = left
.right = right
F preorder(visitor) -> N
visitor(.data)
I .left != N
.left.preorder(visitor)
I .right != N
.right.preorder(visitor)
F in... |
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... | #AppleScript | AppleScript | on run
1 + 2
ap({square, squareRoot}, {result})
--> {9, 1.732050807569}
end run
-- square :: Num a => a -> a
on square(x)
x * x
end square
-- squareRoot :: Num a, Float b => a -> b
on squareRoot(x)
x ^ 0.5
end squareRoot
-- GENERIC FUNCTIONS --------------------------------------------... |
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 ... | #Clojure | Clojure |
(defn tape
"Creates a new tape with given blank character and tape contents"
([blank] (tape () blank () blank))
([right blank] (tape () (first right) (rest right) blank))
([left head right blank] [(reverse left) (or head blank) (into () right) blank]))
; Tape operations
(defn- left [[[l & ls] _ rs b]... |
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... | #ALGOL-M | ALGOL-M |
BEGIN
% RETURN P MOD Q %
INTEGER FUNCTION MOD (P, Q);
INTEGER P, Q;
BEGIN
MOD := P - Q * (P / Q);
END;
% RETURN GREATEST COMMON DIVISOR OF X AND Y %
INTEGER FUNCTION GCD (X, Y);
INTEGER X, Y;
BEGIN
INTEGER R;
IF X < Y THEN
BEGIN
INTEGER TEMP;
TEMP := X;
X := Y;
Y := TEMP;
END;
WHILE (R := MOD(X,... |
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 ... | #D | D | import std.stdio, std.algorithm, std.range, permutations2;
int topswops(in int n) pure @safe {
static int flip(int[] xa) pure nothrow @safe @nogc {
if (!xa[0]) return 0;
xa[0 .. xa[0] + 1].reverse();
return 1 + flip(xa);
}
return n.iota.array.permutations.map!flip.reduce!max;
}
v... |
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... | #AutoHotkey | AutoHotkey | pi := 4 * atan(1)
radians := pi / 4
degrees := 45.0
result .= "`n" . sin(radians) . " " . sin(degrees * pi / 180)
result .= "`n" . cos(radians) . " " . cos(degrees * pi / 180)
result .= "`n" . tan(radians) . " " . tan(degrees * pi / 180)
temp := asin(sin(radians))
result .= "`n" . temp .... |
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... | #BASIC | BASIC |
10 REM Trabb Pardo-Knuth algorithm
20 REM Used "magic numbers" because of strict specification
30 REM of the algorithm.
40 DEF FNF(N) = SQR(ABS(N))+5*N*N*N
50 DIM S(10)
60 PRINT "Enter 11 numbers."
70 FOR I = 0 TO 10
80 PRINT I+1; "- Enter number";
90 INPUT S(I)
100 NEXT I
110 PRINT
120 REM Reverse
130 FOR I = 0 TO 1... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Print["Answer:\n", Column@Cases[#, {s_, 0} :> s], "\nNear misses:\n",
Column@Cases[#, {s_, 1} :> s]] &[{#,
Count[Boole /@ {Length@# == 12, Total@#[[7 ;;]] == 3,
Total@#[[2 ;; 12 ;; 2]] == 2, #[[5]] (#[[6]] + #[[7]] - 2) ==
0, Total@#[[2 ;; 4]] == 0,
Total@#[[1 ;; 11 ;; 2]] == 4, #[[... |
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... | #Kotlin | Kotlin | // Version 1.2.31
import java.util.Stack
class Variable(val name: Char, var value: Boolean = false)
lateinit var expr: String
var variables = mutableListOf<Variable>()
fun Char.isOperator() = this in "&|!^"
fun Char.isVariable() = this in variables.map { it.name }
fun evalExpression(): Boolean {
val sta... |
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, ... | #Lua | Lua | local function ulamspiral(n, f)
print("n = " .. n)
local function isprime(p)
if p < 2 then return false end
if p % 2 == 0 then return p==2 end
if p % 3 == 0 then return p==3 end
local limit = math.sqrt(p)
for f = 5, limit, 6 do
if p % f == 0 or p % (f+2) == 0 then return false end
end
... |
http://rosettacode.org/wiki/Truncatable_primes | Truncatable primes | A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.
Examples
The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.
The number 7393 is a right-truncatable prime as the numbers 7393, 7... | #Elena | Elena | import extensions;
const MAXN = 1000000;
extension mathOp
{
isPrime()
{
int n := cast int(self);
if (n < 2) { ^ false };
if (n < 4) { ^ true };
if (n.mod:2 == 0) { ^ false };
if (n < 9) { ^ true };
if (n.mod:3 == 0) { ^ false };
in... |
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... | #VBScript | VBScript |
Sub truncate(fpath,n)
'Check if file exist
Set objfso = CreateObject("Scripting.FileSystemObject")
If objfso.FileExists(fpath) = False Then
WScript.Echo fpath & " does not exist"
Exit Sub
End If
content = ""
'stream the input file
Set objinstream = CreateObject("Adodb.Stream")
With objinstream
.Type = 1... |
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... | #Wren | Wren | import "/ioutil" for FileUtil
var fileName = "temp.txt"
// create a file of length 26 bytes
FileUtil.write(fileName, "abcdefghijklmnopqrstuvwxyz")
System.print("Contents before truncation: %(FileUtil.read(fileName))")
// truncate file to 13 bytes
FileUtil.truncate(fileName, 13)
System.print("Contents after trunca... |
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
/ ... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program deftree64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM6... |
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... | #Axe | Axe | 3
Disp *3▶Dec,i |
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.