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/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would repr... | #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
func DotProd(A, B); \Return the dot product of two 3D vectors
int A, B; \A ù B
return A(0)*B(0) + A(1)*B(1) + A(2)*B(2);
proc CrossProd(A, B, C); \Calculate the cross product of two 3D vectors
int A, B, C; ... |
http://rosettacode.org/wiki/Twin_primes | Twin primes | Twin primes are pairs of natural numbers (P1 and P2) that satisfy the following:
P1 and P2 are primes
P1 + 2 = P2
Task
Write a program that displays the number of pairs of twin primes that can be found under a user-specified number
(P1 < user-specified number & P2 < user-specified numbe... | #REXX | REXX | /*REXX pgm counts the number of twin prime pairs under a specified number N (or a list).*/
parse arg $ . /*get optional number of primes to find*/
if $='' | $="," then $= 10 100 1000 10000 100000 1000000 10000000 /*No $? Use default.*/
w= length( commas( word($, words($) ) ) ) ... |
http://rosettacode.org/wiki/Unprimeable_numbers | Unprimeable numbers | Definitions
As used here, all unprimeable numbers (positive integers) are always expressed in base ten.
───── Definition from OEIS ─────:
Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed.
───── Definition from Wiktionary (reference... | #REXX | REXX | /*REXX program finds and displays unprimeable numbers (non─negative integers). */
parse arg n x hp . /*obtain optional arguments from the CL*/
if n=='' | n=="," then n= 35 /*Not specified? Then use the default.*/
if x=='' | x=="," then x= 600 ... |
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... | #ALGOL_68 | ALGOL 68 | #!/usr/local/bin/a68g --script #
PROC is prime = (INT n)BOOL:(
[]BOOL is short prime=(FALSE, TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE);
IF n<=UPB is short prime THEN is short prime[n] # EXIT # ELSE
IF ( NOT ODD n | TRUE | n MOD 3 = 0 ) THEN FALSE # EXIT # ELSE
INT h := ENTIER sqrt(n)+3;
... |
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... | #Quackery | Quackery | $ "bigrat.qky" loadfile
[ random 0 = ] is randN ( n --> n )
[ dup randN
over randN
2dup = iff
2drop again
drop nip ] is unbias ( n --> n )
[ dup echo say " biased --> "
0
1000000 times
[ over randN if 1+ ]
nip 1000000 6 p... |
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... | #R | R | randN = function(N) sample.int(N, 1) == 1
unbiased = function(f)
{while ((x <- f()) == f()) {}
x}
samples = 10000
print(t(round(d = 2, sapply(3:6, function(N) c(
N = N,
biased = mean(replicate(samples, randN(N))),
unbiased = mean(replicate(samples, unbiased(function() randN(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... | #Java | Java | import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class TruncFile {
public static void main(String[] args) throws IOException{
if(args.length < 2){
System.out.println("Usage: java TruncFile fileName newSize");
return;
}
//turn on "append" so it does... |
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... | #Julia | Julia | function truncate_file(fname, size):
open(fname, "r+") do f
truncate(f, size)
end
end |
http://rosettacode.org/wiki/Tree_datastructures | Tree datastructures | The following shows a tree of data with nesting denoted by visual levels of indentation:
RosettaCode
rocks
code
comparison
wiki
mocks
trolling
A common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of... | #Haskell | Haskell | {-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableSuperClasses #-}
{-# LANGUAGE TypeApplications #-}
import Data.List (span)
-- A nested tree structure.
-- Using `Maybe` allows encoding several zero-level items
-- or irregular lists (see test example)
... |
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... | #C.2B.2B | C++ | #include <any>
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
// Make a tree that is a vector of either values or other trees
vector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1)
{
vector<any> tree;
while (first < last && depth <= *first)
... |
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... | #C.2B.2B | C++ | #include <iostream>
#include <vector>
#include <string>
#include <cmath>
using namespace std;
// convert int (0 or 1) to string (F or T)
inline
string str(int n)
{
return n ? "T": "F";
}
int main(void)
{
int solution_list_number = 1;
vector<string> st;
st = {
" 1. This is a numbered list ... |
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... | #Clojure | Clojure | (use '[clojure.math.combinatorics]
(defn xor? [& args]
(odd? (count (filter identity args))))
(defn twelve-statements []
(for [[a b c d e f g h i j k l] (selections [true false] 12)
:when (true? a)
:when (if (= 3 (count (filter true? [g h i j k l]))) (true? b) (false? b))
:when (if (= 2 (count (filt... |
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... | #C.23 | C# | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class TruthTable
{
enum TokenType { Unknown, WhiteSpace, Constant, Operand, Operator, LeftParenthesis, RightParenthesis }
readonly char trueConstant, falseConstant;
readonly IDictionary... |
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, ... | #Factor | Factor | USING: arrays grouping kernel math math.combinatorics
math.matrices math.primes math.ranges math.statistics
prettyprint sequences sequences.repeating ;
IN: rosetta-code.ulam-spiral
: counts ( n -- seq ) 1 [a,b] 2 repeat rest ;
: vals ( n -- seq )
[ -1 swap neg 2dup [ neg ] bi@ 4array ] [ 2 * 1 - cycle ] bi ;
... |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would repr... | #zkl | zkl | fcn dotp(a,b){ a.zipWith('*,b).sum() } //1 slow but concise
fcn crossp([(a1,a2,a3)],[(b1,b2,b3)]) //2
{ return(a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1) } |
http://rosettacode.org/wiki/Twin_primes | Twin primes | Twin primes are pairs of natural numbers (P1 and P2) that satisfy the following:
P1 and P2 are primes
P1 + 2 = P2
Task
Write a program that displays the number of pairs of twin primes that can be found under a user-specified number
(P1 < user-specified number & P2 < user-specified numbe... | #Ring | Ring |
load "stdlib.ring"
limit = list(7)
for n = 1 to 7
limit[n] = pow(10,n)
next
TwinPrimes = []
for n = 1 to limit[7]-2
bool1 = isprime(n)
bool2 = isprime(n+2)
bool = bool1 and bool2
if bool =1
add(TwinPrimes,[n,n+2])
ok
next
numTwin = list(7)
len = len(TwinPrimes)
for n = 1 to l... |
http://rosettacode.org/wiki/Twin_primes | Twin primes | Twin primes are pairs of natural numbers (P1 and P2) that satisfy the following:
P1 and P2 are primes
P1 + 2 = P2
Task
Write a program that displays the number of pairs of twin primes that can be found under a user-specified number
(P1 < user-specified number & P2 < user-specified numbe... | #Ruby | Ruby | require 'prime'
(1..8).each do |n|
count = Prime.each(10**n).each_cons(2).count{|p1, p2| p2-p1 == 2}
puts "Twin primes below 10**#{n}: #{count}"
end
|
http://rosettacode.org/wiki/Unprimeable_numbers | Unprimeable numbers | Definitions
As used here, all unprimeable numbers (positive integers) are always expressed in base ten.
───── Definition from OEIS ─────:
Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed.
───── Definition from Wiktionary (reference... | #Rust | Rust | // main.rs
mod bit_array;
mod prime_sieve;
use prime_sieve::PrimeSieve;
// return number of decimal digits
fn count_digits(mut n: u32) -> u32 {
let mut digits = 0;
while n > 0 {
n /= 10;
digits += 1;
}
digits
}
// return the number with one digit replaced
fn change_digit(mut n: u32... |
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... | #Arturo | Arturo | leftTruncatable?: function [n][
every? map 0..(size s)-1 'z -> to :integer slice s z (size s)-1
=> prime?
]
rightTruncatable?: function [n][
every? map 0..(size s)-1 'z -> to :integer slice s 0 z
=> prime?
]
upperLimit: 999999
loop range uppe... |
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... | #Racket | Racket |
#lang racket
;; Using boolean #t/#f instead of 1/0
(define ((randN n)) (zero? (random n)))
(define ((unbiased biased))
(let loop () (let ([r (biased)]) (if (eq? r (biased)) (loop) r))))
;; Counts
(define N 1000000)
(for ([n (in-range 3 7)])
(define (try% R) (round (/ (for/sum ([i N]) (if (R) 1 0)) N 1/100)))
... |
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... | #Raku | Raku | sub randN ( $n where 3..6 ) {
return ( $n.rand / ($n - 1) ).Int;
}
sub unbiased ( $n where 3..6 ) {
my $n1;
repeat { $n1 = randN($n) } until $n1 != randN($n);
return $n1;
}
my $iterations = 1000;
for 3 .. 6 -> $n {
my ( @raw, @fixed );
for ^$iterations {
@raw[ randN($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... | #Kotlin | Kotlin | // version 1.1.2
import java.io.FileOutputStream
import java.nio.channels.FileChannel
fun truncateFile(fileName: String, newSize: Long) {
var fc: FileChannel? = null
try {
fc = FileOutputStream(fileName, true).channel
if (newSize >= fc.size())
println("Requested file size isn't ... |
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... | #Lasso | Lasso | define file_truncate(path::string, size::integer) => {
local(file = file(#path))
fail_if(not(#file -> exists), -1, 'There is no file at the given path')
fail_if(#file -> size < #size, -1, 'No point in truncating a file to a larger size than it already is')
#file -> setSize(#size)
}
local(filepath = '//Libra... |
http://rosettacode.org/wiki/Tree_datastructures | Tree datastructures | The following shows a tree of data with nesting denoted by visual levels of indentation:
RosettaCode
rocks
code
comparison
wiki
mocks
trolling
A common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of... | #Julia | Julia | const nesttext = """
RosettaCode
rocks
code
comparison
wiki
mocks
trolling
"""
function nesttoindent(txt)
ret = ""
windent = gcd(length.([x.match for x in eachmatch(r"\s+", txt)]) .- 1)
for lin in split(txt, "\n")
ret *= isempty(lin) ? "\n" : isspace(lin[1])... |
http://rosettacode.org/wiki/Tree_datastructures | Tree datastructures | The following shows a tree of data with nesting denoted by visual levels of indentation:
RosettaCode
rocks
code
comparison
wiki
mocks
trolling
A common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of... | #Nim | Nim | import strformat, strutils
####################################################################################################
# Nested representation of trees.
# The tree is simply the first node.
type
NNode*[T] = ref object
value*: T
children*: seq[NNode[T]]
proc newNNode*[T](value: T; children... |
http://rosettacode.org/wiki/Tree_datastructures | Tree datastructures | The following shows a tree of data with nesting denoted by visual levels of indentation:
RosettaCode
rocks
code
comparison
wiki
mocks
trolling
A common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
use JSON;
use Data::Printer;
my $trees = <<~END;
RosettaCode
encourages
code
diversity
comparison
discourages
golfing
trolling
emphasising execution speed
code-golf.io
encourages
golfing
... |
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... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import "fmt"
type any = interface{}
func toTree(list []int) any {
s := []any{[]any{}}
for _, n := range list {
for n != len(s) {
if n > len(s) {
inner := []any{}
s[len(s)-1] = append(s[len(s)-1].([]any), inner)
s = append(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... | #Common_Lisp | Common Lisp |
(defparameter *state* (make-list 12))
(defparameter *statements* '(t ; 1
(= (count-true '(7 8 9 10 11 12)) 3) ; 2
(= (count-true '(2 4 6 8 10 12)) 2) ; 3
... |
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... | #Clojure | Clojure | (ns clojure-sandbox.truthtables
(:require [clojure.string :as s]
[clojure.pprint :as pprint]))
;; Definitions of the logical operators
(defn !op [expr]
(not expr))
(defn |op [e1 e2]
(not (and (not e1)
(not e2))))
(defn &op [e1 e2]
(and e1 e2))
(defn ->op [e1 e2]
(if e1
e2
... |
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, ... | #Forth | Forth |
43 constant border \ grid size is border x border
border border * constant size
variable crawler \ position of the crawler
: set.crawler border ... |
http://rosettacode.org/wiki/Twin_primes | Twin primes | Twin primes are pairs of natural numbers (P1 and P2) that satisfy the following:
P1 and P2 are primes
P1 + 2 = P2
Task
Write a program that displays the number of pairs of twin primes that can be found under a user-specified number
(P1 < user-specified number & P2 < user-specified numbe... | #Rust | Rust | // [dependencies]
// primal = "0.3"
// num-format = "0.4"
use num_format::{Locale, ToFormattedString};
fn twin_prime_count_for_powers_of_ten(max_power: u32) {
let mut count = 0;
let mut previous = 0;
let mut power = 1;
let mut limit = 10;
for prime in primal::Primes::all() {
if prime > l... |
http://rosettacode.org/wiki/Twin_primes | Twin primes | Twin primes are pairs of natural numbers (P1 and P2) that satisfy the following:
P1 and P2 are primes
P1 + 2 = P2
Task
Write a program that displays the number of pairs of twin primes that can be found under a user-specified number
(P1 < user-specified number & P2 < user-specified numbe... | #Sidef | Sidef | func twin_primes_count(upto) {
var count = 0
var p1 = 2
each_prime(3, upto, {|p2|
if (p2 - p1 == 2) {
++count
}
p1 = p2
})
return count
}
for n in (1..9) {
var count = twin_primes_count(10**n)
say "There are #{count} twin primes <= 10^#{n}"
} |
http://rosettacode.org/wiki/Unprimeable_numbers | Unprimeable numbers | Definitions
As used here, all unprimeable numbers (positive integers) are always expressed in base ten.
───── Definition from OEIS ─────:
Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed.
───── Definition from Wiktionary (reference... | #Sidef | Sidef | func is_unprimeable(n) {
var t = 10*floor(n/10)
for k in (t+1 .. t+9 `by` 2) {
return false if k.is_prime
}
if (n.is_div(2) || n.is_div(5)) {
return true if !is_prime(n%10)
return true if (n % 10**n.ilog(10) > 9)
}
for k in (1 .. n.ilog(10)) {
var u = 10**k
... |
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... | #AutoHotkey | AutoHotkey | SetBatchLines, -1
MsgBox, % "Largest left-truncatable and right-truncatable primes less than one million:`n"
. "Left:`t" LTP(10 ** 6) "`nRight:`t" RTP(10 ** 6)
LTP(n) {
while n {
n--
if (!Instr(n, "0") && IsPrime(n)) {
Loop, % StrLen(n)
if (!IsPrime(SubStr(n, A_Index)))
continue, 2
break
}
}
... |
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... | #REXX | REXX | /*REXX program generates unbiased random numbers and displays the results to terminal.*/
parse arg # R seed . /*obtain optional arguments from the CL*/
if #=='' | #=="," then #=1000 /*#: the number of SAMPLES to be used.*/
if R=='' | R=="," then R=6 ... |
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... | #Liberty_BASIC | Liberty BASIC |
dim info$( 50, 50) ' NB pre-dimension before calling file-exists
' needed for file-exists function
open "test.dat" for output as #1 'create file
for i = 1 to 10000
#1 chr$( int( 256 *rnd( 1)));
next
close #1
call truncateFile, "test.dat", 5000
wait
sub trunca... |
http://rosettacode.org/wiki/Tree_datastructures | Tree datastructures | The following shows a tree of data with nesting denoted by visual levels of indentation:
RosettaCode
rocks
code
comparison
wiki
mocks
trolling
A common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of... | #Phix | Phix | function text_to_indent(string plain_text)
sequence lines = split(plain_text,"\n",no_empty:=true),
parents = {}
for i=1 to length(lines) do
string line = trim_tail(lines[i]),
text = trim_head(line)
integer indent = length(line)-length(text)
-- remove any compl... |
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... | #Go | Go | package main
import "fmt"
type any = interface{}
func toTree(list []int) any {
s := []any{[]any{}}
for _, n := range list {
for n != len(s) {
if n > len(s) {
inner := []any{}
s[len(s)-1] = append(s[len(s)-1].([]any), inner)
s = append(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... | #D | D | import std.stdio, std.algorithm, std.range, std.functional;
immutable texts = [
"this is a numbered list of twelve statements",
"exactly 3 of the last 6 statements are true",
"exactly 2 of the even-numbered statements are true",
"if statement 5 is true, then statements 6 and 7 are both true",
"the... |
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... | #Cowgol | Cowgol | # Truth table generator in Cowgol
# -
# This program will generate a truth table for the Boolean expression
# given on the command line.
#
# The expression is in infix notation, and operator precedence is impemented,
# i.e., the following expression:
# A & B | C & D => E
# is parsed as:
# ((A & B) | (C & D... |
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, ... | #Fortran | Fortran | program ulam
implicit none
integer, parameter :: nsize = 49
integer :: i, j, n, x, y
integer :: a(nsize*nsize) = (/ (i, i = 1, nsize*nsize) /)
character(1) :: spiral(nsize, nsize) = " "
character(2) :: sstr
character(10) :: fmt
n = 1
x = nsize / 2 + 1
y = x
if(isprime(a(n))) spiral(x, y) = ... |
http://rosettacode.org/wiki/Twin_primes | Twin primes | Twin primes are pairs of natural numbers (P1 and P2) that satisfy the following:
P1 and P2 are primes
P1 + 2 = P2
Task
Write a program that displays the number of pairs of twin primes that can be found under a user-specified number
(P1 < user-specified number & P2 < user-specified numbe... | #Visual_Basic | Visual Basic | Function IsPrime(x As Long) As Boolean
Dim i As Long
If x Mod 2 = 0 Then
Exit Function
Else
For i = 3 To Int(Sqr(x)) Step 2
If x Mod i = 0 Then Exit Function
Next i
End If
IsPrime = True
End Function
Function TwinPrimePairs(max As Long) As Long
Dim p1 As Boo... |
http://rosettacode.org/wiki/Twin_primes | Twin primes | Twin primes are pairs of natural numbers (P1 and P2) that satisfy the following:
P1 and P2 are primes
P1 + 2 = P2
Task
Write a program that displays the number of pairs of twin primes that can be found under a user-specified number
(P1 < user-specified number & P2 < user-specified numbe... | #Wren | Wren | import "/math" for Int
import "/fmt" for Fmt
var c = Int.primeSieve(1e8-1, false)
var limit = 10
var start = 3
var twins = 0
for (i in 1..8) {
var j = start
while (j < limit) {
if (!c[j] && !c[j-2]) twins = twins + 1
j = j + 2
}
Fmt.print("Under $,11d there are $,7d pairs of twin prime... |
http://rosettacode.org/wiki/Unprimeable_numbers | Unprimeable numbers | Definitions
As used here, all unprimeable numbers (positive integers) are always expressed in base ten.
───── Definition from OEIS ─────:
Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed.
───── Definition from Wiktionary (reference... | #Swift | Swift | import Foundation
class BitArray {
var array: [UInt32]
init(size: Int) {
array = Array(repeating: 0, count: (size + 31)/32)
}
func get(index: Int) -> Bool {
let bit = UInt32(1) << (index & 31)
return (array[index >> 5] & bit) != 0
}
func set(index: Int, value: Boo... |
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... | #AWK | AWK |
# syntax: GAWK -f TRUNCATABLE_PRIMES.AWK
BEGIN {
limit = 1000000
for (i=1; i<=limit; i++) {
if (is_prime(i)) {
prime_count++
arr[i] = ""
if (truncate_left(i) == 1) {
max_left = max(max_left,i)
}
if (truncate_right(i) == 1) {
max_right = max(max... |
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... | #Ring | Ring |
for n = 3 to 6
biased = 0
unb = 0
for i = 1 to 10000
biased += randN(n)
unb += unbiased(n)
next
see "N = " + n + " : biased = " + biased/100 + "%, unbiased = " + unb/100 + "%" + nl
next
func unbiased nr
while 1
a = randN(nr)
if a != randN(nr) return ... |
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... | #Ruby | Ruby | def rand_n(bias)
rand(bias) == 0 ? 1 : 0
end
def unbiased(bias)
a, b = rand_n(bias), rand_n(bias) until a != b #loop until a and b are 0,1 or 1,0
a
end
runs = 1_000_000
keys = %i(bias biased unbiased) #use [:bias,:biased,:unbiased] in Ruby < 2.0
puts keys.join("\t")
(3..6).each do |bias|
counter = Hash.ne... |
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... | #Lingo | Lingo | ----------------------------------------
-- Truncates file
-- @param {string} filename
-- @param {integer} length
-- @return {bool} success
----------------------------------------
on truncate (filename, length)
fp = xtra("fileIO").new()
fp.openFile(filename, 0)
if fp.status() then return false
if fp.getLength(... |
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... | #Lua | Lua | function truncate (filename, length)
local inFile = io.open(filename, 'r')
if not inFile then
error("Specified filename does not exist")
end
local wholeFile = inFile:read("*all")
inFile:close()
if length >= wholeFile:len() then
error("Provided length is not less than current file... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Truncate[file_, n_] := Module[{filename = file, nbbytes = n, temp},
temp = $TemporaryPrefix <> filename;
BinaryWrite[temp, BinaryReadList[filename, "Byte", nbbytes]];
Close[temp]; DeleteFile[filename]; RenameFile[temp, filename];
] |
http://rosettacode.org/wiki/Tree_datastructures | Tree datastructures | The following shows a tree of data with nesting denoted by visual levels of indentation:
RosettaCode
rocks
code
comparison
wiki
mocks
trolling
A common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of... | #Python | Python | from pprint import pprint as pp
def to_indent(node, depth=0, flat=None):
if flat is None:
flat = []
if node:
flat.append((depth, node[0]))
for child in node[1]:
to_indent(child, depth + 1, flat)
return flat
def to_nest(lst, depth=0, level=None):
if level is None:
... |
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... | #Guile | Guile | ;; helper function that finds the rest that are less than or equal
(define (rest-less-eq x ls)
(cond
((null? ls) #f)
((<= (car ls) x) ls)
(else (rest-less-eq x (cdr ls)))))
;; nest the input as a tree
(define (make-tree input depth)
(cond
((null? input) '())
((eq? input #f ) '())
((= ... |
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... | #Eiffel | Eiffel |
class
APPLICATION
create
make
feature
make
-- Possible solutions.
do
create s.make_filled (False, 1, 12)
s [1] := True
recurseAll (2)
io.put_string (counter.out + " solution found. ")
end
feature {NONE}
s: ARRAY [BOOLEAN]
check2: BOOLEAN
-- Is statement 2 fulfilled?
local
c... |
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... | #D | D | import std.stdio, std.string, std.array, std.algorithm, std.typecons;
struct Var {
const char name;
bool val;
}
const string expr;
Var[] vars;
bool pop(ref bool[] arr) pure nothrow {
const last = arr.back;
arr.popBack;
return last;
}
enum isOperator = (in char c) pure => "&|!^".canFind(c);
e... |
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, ... | #FreeBASIC | FreeBASIC |
#define SIZE 639
screenres SIZE, SIZE, 4
function is_prime( n as ulongint ) as boolean
if n < 2 then return false
if n = 2 then return true
if n mod 2 = 0 then return false
for i as uinteger = 3 to int(sqr(n))+1 step 2
if n mod i = 0 then return false
next i
return true
end functio... |
http://rosettacode.org/wiki/Twin_primes | Twin primes | Twin primes are pairs of natural numbers (P1 and P2) that satisfy the following:
P1 and P2 are primes
P1 + 2 = P2
Task
Write a program that displays the number of pairs of twin primes that can be found under a user-specified number
(P1 < user-specified number & P2 < user-specified numbe... | #XPL0 | XPL0 | func IsPrime(N); \Return 'true' if N is prime
int N, I;
[if N <= 2 then return N = 2;
if (N&1) = 0 then \even >2\ return false;
for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
func Twins(Limit);
int Limit, C, N;
[C:= 0; N:= 3;
repeat if IsPrime(N) then
... |
http://rosettacode.org/wiki/Twin_primes | Twin primes | Twin primes are pairs of natural numbers (P1 and P2) that satisfy the following:
P1 and P2 are primes
P1 + 2 = P2
Task
Write a program that displays the number of pairs of twin primes that can be found under a user-specified number
(P1 < user-specified number & P2 < user-specified numbe... | #Yabasic | Yabasic |
sub isPrime(v)
if v < 2 then return False : fi
if mod(v, 2) = 0 then return v = 2 : fi
if mod(v, 3) = 0 then return v = 3 : fi
d = 5
while d * d <= v
if mod(v, d) = 0 then return False else d = d + 2 : fi
wend
return True
end sub
sub paresDePrimos(limite)
p1 = 0 : p2 = 1 : p3... |
http://rosettacode.org/wiki/Unprimeable_numbers | Unprimeable numbers | Definitions
As used here, all unprimeable numbers (positive integers) are always expressed in base ten.
───── Definition from OEIS ─────:
Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed.
───── Definition from Wiktionary (reference... | #Wren | Wren | import "/fmt" for Fmt
import "/math" for Int
System.print("The first 35 unprimeable numbers are:")
var count = 0 // counts all unprimeable numbers
var firstNum = List.filled(10, 0) // stores the first unprimeable number ending with each digit
var i = 100
var countFirst = 0
while (countFirst < 10) ... |
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... | #Bracmat | Bracmat | ( 1000001:?i
& whl
' ( !i+-2:>0:?i
& !i:?L
& whl'(!L^1/2:#?^1/2&@(!L:% ?L))
& !L:~
)
& out$("left:" !i)
& 1000001:?i
& whl
' ( !i+-2:>0:?i
& !i:?R
& whl'(!R^1/2:#?^1/2&@(!R:?R %@))
& !R:~
)
& out$("right:" !i)
) |
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... | #Rust | Rust | #![feature(inclusive_range_syntax)]
extern crate rand;
use rand::Rng;
fn rand_n<R: Rng>(rng: &mut R, n: u32) -> usize {
rng.gen_weighted_bool(n) as usize // maps `false` to 0 and `true` to 1
}
fn unbiased<R: Rng>(rng: &mut R, n: u32) -> usize {
let mut bit = rand_n(rng, n);
while bit == rand_n(rng, ... |
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... | #Scala | Scala | def biased( n:Int ) = scala.util.Random.nextFloat < 1.0 / n
def unbiased( n:Int ) = { def loop : Boolean = { val a = biased(n); if( a != biased(n) ) a else loop }; loop }
for( i <- (3 until 7) ) println {
val m = 50000
var c1,c2 = 0
(0 until m) foreach { j => if( biased(i) ) c1 += 1; if( unbiased(i) ) c2... |
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... | #MATLAB_.2F_Octave | MATLAB / Octave | function truncate_a_file(fn,count);
fid=fopen(fn,'r');
s = fread(fid,count,'uint8');
fclose(fid);
fid=fopen(fn,'w');
s = fwrite(fid,s,'uint8');
fclose(fid); |
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... | #Nim | Nim | import posix
discard truncate("filename", 1024) |
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... | #OCaml | OCaml | val truncate : string -> int -> unit
(** Truncates the named file to the given size. *) |
http://rosettacode.org/wiki/Tree_datastructures | Tree datastructures | The following shows a tree of data with nesting denoted by visual levels of indentation:
RosettaCode
rocks
code
comparison
wiki
mocks
trolling
A common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of... | #Raku | Raku | #`(
Sort of vague as to what we are trying to accomplish here. If we are just
trying to transform from one format to another, probably easiest to just
perform string manipulations.
)
my $level = ' ';
my $trees = q:to/END/;
RosettaCode
encourages
code
diversity
comparison
... |
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 ... | #11l | 11l | F run_utm(halt, state, Char blank; rules_in, [Char] &tape = [Char](); =pos = 0)
V st = state
I tape.empty
tape.append(blank)
I pos < 0
pos += tape.len
V rules = Dict(rules_in, r -> ((r[0], Char(r[1])), (Char(r[2]), r[3], r[4])))
L
print(st.ljust(4), end' ‘ ’)
L(v) tape
... |
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... | #Haskell | Haskell | {-# LANGUAGE TupleSections #-}
import Data.Bifunctor (bimap)
import Data.Tree (Forest, Tree (..), drawTree, foldTree)
------------- TREE FROM NEST LEVELS (AND BACK) -----------
treeFromSparseLevels :: [Int] -> Tree (Maybe Int)
treeFromSparseLevels =
Node Nothing
. forestFromNestLevels
. rooted
. nor... |
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... | #Elena | Elena | import system'routines;
import extensions;
import extensions'text;
extension op
{
printSolution(bits)
= self.zipBy(bits,
(s,b => s.iif("T","F") + (s.xor:b).iif("* "," "))).summarize(new StringWriter());
toBit()
= self.iif(1,0);
}
puzzle = new Func1[]
{
(bits => bits.Length... |
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... | #ERRE | ERRE |
PROGRAM TWELVE_STMS
!$DYNAMIC
DIM PASS%[0],T%[0]
FUNCTION EOR(X,Y)
EOR=(X AND NOT(Y)) OR (NOT(X) AND Y)
END FUNCTION
BEGIN
NSTATEMENTS%=12
!$DIM PASS%[NSTATEMENTS%],T%[NSTATEMENTS%]
FOR TRY%=0 TO 2^NSTATEMENTS%-1 DO
! Postulate answer:
FOR STMT%=1 TO 12 DO
T%[... |
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... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | print-line lst end:
for v in reversed copy lst:
print\( v chr 9 )
print end
(print-truth-table) t n func:
if n:
(print-truth-table) push-through copy t 0 -- n @func
(print-truth-table) push-through copy t 1 -- n @func
else:
print-line t func for in copy t
print-truth-... |
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, ... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"math"
"fmt"
)
type Direction byte
const (
RIGHT Direction = iota
UP
LEFT
DOWN
)
func generate(n,i int, c byte) {
s := make([][]string, n)
for i := 0; i < n; i++ { s[i] = make([]string, n) }
dir := RIGHT
y := n / 2
var x int
if (n % 2 == 0) { x = y - 1 } else { x = y } // shift... |
http://rosettacode.org/wiki/Unprimeable_numbers | Unprimeable numbers | Definitions
As used here, all unprimeable numbers (positive integers) are always expressed in base ten.
───── Definition from OEIS ─────:
Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed.
───── Definition from Wiktionary (reference... | #XPL0 | XPL0 | func IsPrime(N); \Return 'true' if N is prime
int N, I;
[if N <= 2 then return N = 2;
if (N&1) = 0 then \even >2\ return false;
for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
func Unprimeable(N); \Return 'true' if N is unprimeable
int N, I, J, Len, D, S... |
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 | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_PRIME 1000000
char *primes;
int n_primes;
/* Sieve. If we were to handle 10^9 range, use bit field. Regardless,
* if a large amount of prime numbers need to be tested, sieve is fast.
*/
void init_primes()
{
int j;
primes = malloc(sizeof(ch... |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const func integer: randN (in integer: n) is
return ord(rand(1, n) = 1);
const func integer: unbiased (in integer: n) is func
result
var integer: unbiased is 0;
begin
repeat
unbiased := randN(n);
until unbiased <> randN(n);
end func;
const... |
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... | #Sidef | Sidef | func randN (n) {
n.rand / (n-1) -> int
}
func unbiased(n) {
var n1 = nil
do { n1 = randN(n) } while (n1 == randN(n))
return n1
}
var iterations = 1000
for n in (3..6) {
var raw = []
var fixed = []
iterations.times {
raw[ randN(n) ] := 0 ++
fixed[ unbiased(n) ] := 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... | #PARI.2FGP | PARI/GP | install("truncate", "isL", "trunc")
trunc("/tmp/test.file", 20) |
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... | #Pascal | Pascal |
Program FileTruncate;
uses
SysUtils;
var
myfile: file of byte;
filename: string;
position: integer;
begin
write('File for truncation: ');
readln(filename);
if not FileExists(filename) then
begin
writeln('Error: File does not exist.');
exit;
end;
write('Truncate position: ');
re... |
http://rosettacode.org/wiki/Tree_datastructures | Tree datastructures | The following shows a tree of data with nesting denoted by visual levels of indentation:
RosettaCode
rocks
code
comparison
wiki
mocks
trolling
A common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of... | #Wren | Wren | import "/dynamic" for Struct
import "/fmt" for Fmt
var NNode = Struct.create("NNode", ["name", "children"])
var INode = Struct.create("INode", ["level", "name"])
var sw = ""
var printNest // recursive
printNest = Fn.new { |n, level|
if (level == 0) sw = sw + "\n==Nest form==\n\n"
sw = sw + Fmt.swrite("$0s... |
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 ... | #Ada | Ada | private with Ada.Containers.Doubly_Linked_Lists;
generic
type State is (<>); -- State'First is starting state
type Symbol is (<>); -- Symbol'First is blank
package Turing is
Start: constant State := State'First;
Halt: constant State := State'Last;
subtype Action_State is State range Start .. Stat... |
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... | #11l | 11l | V rad = math:pi / 4
V deg = 45.0
print(‘Sine: ’sin(rad)‘ ’sin(radians(deg)))
print(‘Cosine: ’cos(rad)‘ ’cos(radians(deg)))
print(‘Tangent: ’tan(rad)‘ ’tan(radians(deg)))
V arcsine = asin(sin(rad))
print(‘Arcsine: ’arcsine‘ ’degrees(arcsine))
V arccosine = acos(cos(rad))
print(‘Arccosine: ’arccosine‘ ’degrees(arccosine)... |
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... | #11l | 11l | F f(x)
R sqrt(abs(x)) + 5 * x ^ 3
V s = Array(1..11)
s.reverse()
L(x) s
V result = f(x)
I result > 400
print(‘#.: #.’.format(x, ‘TOO LARGE!’))
E
print(‘#.: #.’.format(x, result))
print() |
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... | #J | J | [[[3]], 1, [[3]], 1
1 1
[[[3]], 1, [[3]], 1]
|syntax error |
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... | #Julia | Julia | function makenested(list)
nesting = 0
str = isempty(list) ? "[]" : ""
for n in list
if n > nesting
str *= "["^(n - nesting)
nesting = n
elseif n < nesting
str *= "]"^(nesting - n) * ", "
nesting = n
end
str *= "$n, "
end
... |
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... | #Nim | Nim | import sequtils, strutils
type
Kind = enum kValue, kList
Node = ref object
case kind: Kind
of kValue: value: int
of kList: list: seq[Node]
proc newTree(s: varargs[int]): Node =
## Build a tree from a list of level values.
var level = 1
result = Node(kind: kList)
var stack = @[result]
for... |
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... | #Forth | Forth | : lastbit ( n1 -- n2)
dup if 1 swap begin dup 1 <> while swap 1+ swap 1 rshift repeat drop then
;
: bit 1 swap lshift and 0<> ; ( n1 n2 -- f)
: bitcount 0 swap begin dup while dup 1- and swap 1+ swap repeat drop ;
12 constant #stat \ number of statements
... |
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... | #Factor | Factor | USING: arrays combinators eval formatting io kernel listener
math.combinatorics prettyprint qw sequences splitting
vocabs.parser ;
IN: rosetta-code.truth-table
: prompt ( -- str )
"Please enter a boolean expression using 1-long" print
"variable names and postfix notation. Available" print
"operators are a... |
http://rosettacode.org/wiki/Ulam_spiral_(for_primes) | Ulam spiral (for primes) | An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1), constructed on a square grid, starting at the "center".
An Ulam spiral is also known as a prime spiral.
The first grid (green) is shown with sequential integers, ... | #Go | Go | package main
import (
"math"
"fmt"
)
type Direction byte
const (
RIGHT Direction = iota
UP
LEFT
DOWN
)
func generate(n,i int, c byte) {
s := make([][]string, n)
for i := 0; i < n; i++ { s[i] = make([]string, n) }
dir := RIGHT
y := n / 2
var x int
if (n % 2 == 0) { x = y - 1 } else { x = y } // shift... |
http://rosettacode.org/wiki/Unprimeable_numbers | Unprimeable numbers | Definitions
As used here, all unprimeable numbers (positive integers) are always expressed in base ten.
───── Definition from OEIS ─────:
Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed.
───── Definition from Wiktionary (reference... | #zkl | zkl | var [const] BI=Import("zklBigNum"); // libGMP
fcn isUnprimeable(n){ //--> n (!0) or Void, a filter
bn,t := BI(0),n/10*10;
foreach k in ([t+1..t+9,2]){ if(bn.set(k).probablyPrime()) return(Void.Skip) }
if(n==n/2*2 or n==n/5*5){
if(not bn.set(n%10).probablyPrime()) return(n);
if( (n % (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... | #C.23 | C# | using System; // 4790@3.6
using System.Collections.Generic;
class truncatable_primes
{
static void Main()
{
uint m = 1000000;
Console.Write("L " + L(m) + " R " + R(m) + " ");
var sw = System.Diagnostics.Stopwatch.StartNew();
for (int i = 1000; i > 0; i--) { L(m); R(m); }
... |
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... | #Tcl | Tcl | # 1,0 random generator factory with 1 appearing 1/N'th of the time
proc randN n {expr {rand()*$n < 1}}
# uses a biased generator of 1 or 0, to create an unbiased one
proc unbiased {biased} {
while 1 {
if {[set a [eval $biased]] != [eval $biased]} {return $a}
}
}
for {set n 3} {$n <= 6} {incr n} {
set b... |
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... | #Perl | Perl | # Open a file for writing, and truncate it to 1234 bytes.
open FOO, ">>file" or die;
truncate(FOO, 1234);
close FOO;
# Truncate a file to 567 bytes.
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... | #Phix | Phix | without js -- (file i/o)
?get_file_size("test.txt")
?set_file_size("test.txt",100)
?get_file_size("test.txt")
?set_file_size("test.txt",1024)
?get_file_size("test.txt")
|
http://rosettacode.org/wiki/Tree_datastructures | Tree datastructures | The following shows a tree of data with nesting denoted by visual levels of indentation:
RosettaCode
rocks
code
comparison
wiki
mocks
trolling
A common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of... | #zkl | zkl | fcn nestToIndent(nestTree){
fcn(out,node,level){
out.append(List(level,node[0])); // (n,name) or ("..",name)
if(node.len()>1){ // (name children), (name, (tree))
level+=1;
foreach child in (node[1,*]){
if(String.isType(child)) out.append(List(level,child));
else self.fcn(out,child,level)
... |
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 ... | #Amazing_Hopper | Amazing Hopper |
#include <hopper.h>
#proto UniversalTuringMachine(_X_)
main:
.ctrlc
stbegin=0,stEnd=0,state=0,ptr=0
tape=0,states=0,rules=0,long=0,tapeSize=0
file="turing/prg03.tm"
// load program, rules & states:
jsub(load Archive)
// RUN Universal Turing Machine program:
i=1
__TURING_RUN__:
_Univ... |
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... | #ACL2 | ACL2 | (defun fac (n)
(if (zp n)
1
(* n (fac (1- n)))))
(defconst *pi-approx*
(/ 3141592653589793238462643383279
(expt 10 30)))
(include-book "arithmetic-3/floor-mod/floor-mod" :dir :system)
(defun dgt-to-str (d)
(case d
(1 "1") (2 "2") (3 "3") (4 "4") (5 "5")
(6 "6") (7 "7... |
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... | #Ada | Ada | with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions;
procedure Trabb_Pardo_Knuth is
type Real is digits 6 range -400.0 .. 400.0;
package TIO renames Ada.Text_IO;
package FIO is new TIO.Float_IO(Real);
package Math is new Ada.Numerics.Generic_Elementary_Functions(Real);
function F(X: Real... |
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... | #OxygenBasic | OxygenBasic |
uses console
declare DemoTree(string src)
DemoTree "[]"
DemoTree "[1, 2, 4]"
DemoTree "[3, 1, 3, 1]"
DemoTree "[1, 2, 3, 1]"
DemoTree "[3, 2, 1, 3]"
DemoTree "[3, 3, 3, 1, 1, 3, 3, 3]"
pause
end
/*
RESULTS:
========
[]
[]
[1, 2, 4]
[ 1,[ 2,[[ 4]]]]
[3, 1, 3, 1]
[[[ 3]], 1,[[ 3]], 1]
[1, 2, 3, 1]
[ 1,[ 2,[ 3... |
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... | #Perl | Perl | #!/usr/bin/perl
use strict;
use warnings;
use Data::Dump qw(dd pp);
my @tests =
(
[]
,[1, 2, 4]
,[3, 1, 3, 1]
,[1, 2, 3, 1]
,[3, 2, 1, 3]
,[3, 3, 3, 1, 1, 3, 3, 3]
);
for my $before ( @tests )
{
dd { before => $before };
local $_ = (pp $before) =~ s/\d+/ '['x($&-1) . $& . ']'x($&-1) /ger;
... |
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... | #FreeBASIC | FreeBASIC | Dim As Integer nEnunciados = 12, intento, enun, errado
Dim As Integer Afirm(nEnunciados), T(nEnunciados)
For intento = 0 To 2^nEnunciados-1
REM Postular respuesta:
For enun = 1 To 12
T(enun) = (intento And 2^(enun-1)) <> 0
Next enum
REM Prueba de consistencia:
Afirm(1) = T(1) = (nEnunci... |
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... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | 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)
... |
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.