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/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for ...
#Seed7
Seed7
# International class; name and street class 国際( なまえ, Straße ) {   # Say who am I! method 言え { say "I am #{self.なまえ} from #{self.Straße}"; } }   # all the people of the world! var 民族 = [ 国際( "高田 Friederich", "台湾" ), 国際( "Smith Σωκράτης", "Cantù" ), 国際( "S...
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for ...
#Sidef
Sidef
# International class; name and street class 国際( なまえ, Straße ) {   # Say who am I! method 言え { say "I am #{self.なまえ} from #{self.Straße}"; } }   # all the people of the world! var 民族 = [ 国際( "高田 Friederich", "台湾" ), 国際( "Smith Σωκράτης", "Cantù" ), 国際( "S...
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...
#J
J
tp=: 3 : '+/ (*. _2&(|.!.0)) 1 p: i. y'   NB. 3 : '' explicitly define a "monad" (a one-argument function) NB. i. y list integers up to the provided argument NB. 1 p: create list of 0s, 1s where those ints are prime NB. _2&(|.!.0) "shift" that list to the right by two, filling left side with 0 NB. (*. ...
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...
#jq
jq
def odd_gt2_is_prime: . as $n | if ($n % 3 == 0) then $n == 3 elif ($n % 5 == 0) then $n == 5 elif ($n % 7 == 0) then $n == 7 elif ($n % 11 == 0) then $n == 11 elif ($n % 13 == 0) then $n == 13 elif ($n % 17 == 0) then $n == 17 elif ($n % 19 == 0) then $n == 19 else {i:23} ...
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...
#Julia
Julia
using Formatting, Primes   function counttwinprimepairsbetween(n1, n2) npairs, t = 0, nextprime(n1) while t < n2 p = nextprime(t + 1) if p - t == 2 npairs += 1 end t = p end return npairs end   for t2 in (10).^collect(2:8) paircount = counttwinprimepairsbe...
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...
#Perl
Perl
use strict; use warnings; use feature 'say'; use ntheory 'is_prime'; use enum qw(False True);   sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }   sub is_unprimeable { my($n) = @_; return False if is_prime($n); my $chrs = length $n; for my $place (0..$chrs-1) { my $pow = 10*...
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identif...
#zkl
zkl
delta:="\U0394;"; // UTF-8 delta klass:= // embryo(names, numFcns, numClasses, numParents, ...) self.embryo(L("","",delta),0,0,0).cook(); klass.setVar(0,Ref(1)); // indirect set since delta not valid var name klass.vars.println();   dv:=klass.setVar(0); // which actually gets the var, go figure dv.inc(); ...
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...
#Nim
Nim
import random, sequtils, strformat   type randProc = proc: range[0..1]   randomize()   proc randN(n: Positive): randProc = result = proc: range[0..1] = ord(rand(n) == 0)   proc unbiased(biased: randProc): range[0..1] = result = biased() var that = biased() while result == that: result = biased() that = ...
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...
#OCaml
OCaml
let randN n = if Random.int n = 0 then 1 else 0   let rec unbiased n = let a = randN n in if a <> randN n then a else unbiased n   let () = Random.self_init(); let n = 50_000 in for b = 3 to 6 do let cb = ref 0 in let cu = ref 0 in for i = 1 to n do cb := !cb + (randN b); cu := !cu +...
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...
#Clojure
Clojure
(defn truncate [file size] (with-open [chan (.getChannel (java.io.FileOutputStream. file true))] (.truncate chan size)))   (truncate "truncate_test.txt" 2)
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...
#D
D
import std.file, std.exception;   void truncateFile(in string name, in size_t newSize) { if (!exists(name) || !isFile(name)) throw new Exception("File not found.");   auto size = getSize(name); if (size <= newSize) throw new Exception( "New size must be smaller than original size...
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...
#11l
11l
[([Int] -> Bool)] predicates predicates [+]= st -> st.len == 12 predicates [+]= st -> sum(st[(len)-6 ..]) == 3 predicates [+]= st -> sum(st[(1..).step(2)]) == 2 predicates [+]= st -> I st[4] {(st[5] [&] st[6])} E 1 predicates [+]= st -> sum(st[1.<4]) == 0 predicates [+]= st -> sum(st[(0..).step(2)]) == 4 predicates [+]...
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...
#8080_Assembly
8080 Assembly
;;; CP/M truth table generator ;;; Supported operators: ;;; ~ (not), & (and), | (or), ^ (xor) and => (implies) ;;; Variables are A-Z, constants are 0 and 1. putch: equ 2 puts: equ 9 TVAR: equ 32 TCONST: equ 64 TOP: equ 96 TPAR: equ 128 TMASK: equ 31 TTYPE: equ 224 org 100h lxi h,80h ; Have we got a command line ...
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,   ...
#Common_Lisp
Common Lisp
  (defun ulam-spiral (n) (loop for a in (spiral n n (* n n)) do (format t "~{~d~}~%" a)))   (defun spiral (n m b &aux (row (loop for a below n collect (if (primep (- b a)) '* '#\space)))) (if (= m 1) (list row) (cons row (mapcar #'r...
http://rosettacode.org/wiki/Two_bullet_roulette
Two bullet roulette
The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street: A revolver handgun has a revolving cylinder with six chambers for bullets. It is loaded with the following procedure: 1. Check the first chamber to the right of the trigger for a bullet. If a bullet is seen, the cyli...
#Wren
Wren
import "random" for Random import "/fmt" for Fmt   var Rand = Random.new()   class Revolver { construct new() { _cylinder = List.filled(6, false) }   rshift() { var t = _cylinder[-1] for (i in 4..0) _cylinder[i+1] = _cylinder[i] _cylinder[0] = t }   unload() { ...
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Ruby
Ruby
  Dir.foreach("./"){|n| puts n}  
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Run_BASIC
Run BASIC
files #f, DefaultDir$ + "\*.*" ' RunBasic Default directory.. Can be any directroy print "rowcount: ";#f ROWCOUNT() ' how many rows in directory #f DATEFORMAT("mm/dd/yy") 'set format of file date or not #f TIMEFORMAT("hh:mm:ss") 'set format of file time or not count = #f rowcount() for i = 1 to count ' loop ...
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Rust
Rust
use std::{env, fmt, fs, process}; use std::io::{self, Write}; use std::path::Path;   fn main() { let cur = env::current_dir().unwrap_or_else(|e| exit_err(e, 1)); let arg = env::args().nth(1); print_files(arg.as_ref().map_or(cur.as_path(), |p| Path::new(p))) .unwrap_or_else(|e| exit_err(e, 2)); }   #...
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...
#Visual_Basic_.NET
Visual Basic .NET
Public Class Vector3D Private _x, _y, _z As Double   Public Sub New(ByVal X As Double, ByVal Y As Double, ByVal Z As Double) _x = X _y = Y _z = Z End Sub   Public Property X() As Double Get Return _x End Get Set(ByVal value As Double) ...
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Wren
Wren
var f = Fn.new { System.print("'f' called.") // note no return value }   var res = f.call() System.print("The value returned by 'f' is %(res).")   var m = {} // empty map System.print("m[1] is %(m[1]).")   var u // declared but not assigned a value System.print("u is %(u).")   var v = null // explicitly assigned n...
http://rosettacode.org/wiki/Undefined_values
Undefined values
#zkl
zkl
println(Void); 1+Void if(Void){} else { 23 }
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for ...
#Stata
Stata
@{TITLE /[あ-ん一-耙]+/} (@ROMAJI/@ENGLISH) @(freeform) @(coll)@{STANZA /[^\n\x3000 ]+/}@(end)@/.*/  
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for ...
#Tcl
Tcl
@{TITLE /[あ-ん一-耙]+/} (@ROMAJI/@ENGLISH) @(freeform) @(coll)@{STANZA /[^\n\x3000 ]+/}@(end)@/.*/  
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for ...
#TXR
TXR
@{TITLE /[あ-ん一-耙]+/} (@ROMAJI/@ENGLISH) @(freeform) @(coll)@{STANZA /[^\n\x3000 ]+/}@(end)@/.*/  
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...
#Kotlin
Kotlin
import java.math.BigInteger import java.util.*   fun main() { val input = Scanner(System.`in`) println("Search Size: ") val max = input.nextBigInteger() var counter = 0 var x = BigInteger("3") while (x <= max) { val sqrtNum = x.sqrt().add(BigInteger.ONE) if (x.add(BigInteger.TWO)...
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...
#Phix
Phix
with javascript_semantics printf(1,"The first 35 unprimeable numbers are:\n") integer count := 0, -- counts all unprimeable numbers countFirst = 0, i = 100 sequence firstNum = repeat(0,10) -- stores the first unprimeable number ending with each digit atom t0 = time(), t1=t0+1 while countFirst<1...
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...
#PARI.2FGP
PARI/GP
randN(N)=!random(N); unbiased(N)={ my(a,b); while(1, a=randN(N); b=randN(N); if(a!=b, return(a)) ) }; for(n=3,6,print(n"\t"sum(k=1,1e5,unbiased(n))"\t"sum(k=1,1e5,randN(n))))
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...
#Perl
Perl
sub randn { my $n = shift; return int(rand($n) / ($n - 1)); }   for my $n (3 .. 6) { print "Bias $n: "; my (@raw, @fixed); for (1 .. 10000) { my $x = randn($n); $raw[$x]++; $fixed[$x]++ if randn($n) != $x } print ...
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...
#Delphi
Delphi
procedure TruncateFile(FileName : string; NewSize : integer); var aFile: file of byte; begin Assign(aFile, FileName); Reset(aFile); try Seek(afile, NewSize); Truncate(aFile); finally Close(afile); 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...
#Elena
Elena
import system'io; import extensions;   extension fileOp : File { set Length(int len) { auto stream := FileStream.openForEdit(self);   stream.Length := len;   stream.close() } }   public program() { if (program_arguments.Length != 3) { console.printLine:"Please provide the...
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...
#Ada
Ada
with Ada.Text_IO, Logic;   procedure Twelve_Statements is   package L is new Logic(Number_Of_Statements => 12); use L;   -- formally define the 12 statements as expression function predicates function P01(T: Table) return Boolean is (T'Length = 12); -- list of 12 statements function P02(T: Tab...
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...
#ALGOL_68
ALGOL 68
# prints the truth table of a boolean expression composed of the 26 lowercase variables a..z, # # the boolean operators AND, OR, XOR and NOT and the literal values TRUE and FALSE # # The evaluation is done with the Algol 68G evaluate function which is an extension # PROC print truth table = ( STRIN...
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,   ...
#Crystal
Crystal
enum Direction RIGHT UP LEFT DOWN end   def generate(n : Int32, i : Int32, c : Int32 | String) s = Array.new(n) { Array.new(n) { "" } }   dir = Direction::RIGHT y = n // 2 x = n % 2 == 0 ? y - 1 : y   j = 1 while j <= n * n - 1 + i s[y][x] = is_prime(j) ? j.to_s : c.to_s   # printf "j: %s, x...
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#S-lang
S-lang
variable d = listdir(getcwd()), p; foreach p (array_sort(d)) () = printf("%s\n", d[p] );
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Scala
Scala
scala> new java.io.File("/").listFiles.sorted.foreach(println) /bin /boot /core /dev /etc /home /lib /lib64 /local /lost+found /media /mnt /opt /proc /root /run /sbin /selinux /srv /sys /tmp /user /usr /var
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "osfiles.s7i";   const proc: main is func local var string: name is ""; begin for name range readDir(".") do writeln(name); end for; end func;
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...
#Vlang
Vlang
struct Vector { x f64 y f64 z f64 }   const ( a = Vector{3, 4, 5} b = Vector{4, 3, 5} c = Vector{-5, -12, -13} )   fn dot(a Vector, b Vector) f64 { return a.x*b.x + a.y*b.y + a.z*b.z }   fn cross(a Vector, b Vector) Vector { return Vector{a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a...
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for ...
#UNIX_Shell
UNIX Shell
stdout.printf ("UTF-8 encoded string. Let's go to a café!");
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for ...
#Vala
Vala
stdout.printf ("UTF-8 encoded string. Let's go to a café!");
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for ...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Sub Main() Console.OutputEncoding = Text.Encoding.Unicode   ' normal identifiers allowed Dim a = 0 ' unicode characters allowed Dim δ = 1   ' ascii strings Console.WriteLine("some text") ' unicode strings strings Console.WriteL...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[TwinPrimeCount] TwinPrimeCount[mx_] := Module[{pmax, min, max, total}, pmax = PrimePi[mx]; total = 0; Do[ min = 10^6 i; min = Max[min, 1]; max = 10^6 (i + 1); max = Min[max, pmax]; total += Count[Differences[Prime[Range[min, max]]], 2] , {i, 0, Ceiling[pmax/10^6]} ]; total ] Do...
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...
#Nim
Nim
import math, strformat, strutils   const N = 1_000_000_000   proc sieve(n: Positive): seq[bool] = ## Build and fill a sieve of Erathosthenes. result.setLen(n + 1) # Default to false which means prime. result[0] = true result[1] = true for n in countup(3, sqrt(N.toFloat).int, 2): if not result[n]: f...
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...
#Perl
Perl
use strict; use warnings;   use Primesieve;   sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }   printf "Twin prime pairs less than %14s: %s\n", comma(10**$_), comma count_twins(1, 10**$_) for 1..10;
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...
#Pike
Pike
  bool is_unprimeable(int i) { string s = i->digits(); for(int offset; offset < sizeof(s); offset++) { foreach("0123456789"/1, string repl) { array chars = s/1; chars[offset] = repl; int testme = (int)(chars*""); if( testme->probably_prime_p() ) return false; } } return true; }  ...
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...
#Phix
Phix
with javascript_semantics function randN(integer N) return rand(N) = 1 end function function unbiased(integer N) while true do integer a = randN(N) if a!=randN(N) then return a end if end while end function constant n = 100000 for b=3 to 6 do integer cb = 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...
#Erlang
Erlang
  -module( truncate ).   -export( [file/2] ).   file( Name, Size ) -> {file_exists, true} = {file_exists, filelib:is_file( Name )}, {ok, IO} = file:open( Name, [read, write] ), {ok, Max} = file:position( IO, eof ), {correct_size, true} = {correct_size, (Size < Max)}, {ok, Size} = file:position( IO, {bof, Size} ), ...
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...
#F.23
F#
open System open System.IO   let truncateFile path length = if not (File.Exists(path)) then failwith ("File not found: " + path) use fileStream = new FileStream(path, FileMode.Open, FileAccess.Write) if (fileStream.Length < length) then failwith "The specified length is greater than the current file 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...
#ALGOL_W
ALGOL W
begin  % we have 12 statements to determine the truth/falsehood of (see task)  %   logical array stmt, expected( 1 :: 12 );    % logical (boolean) to integer utility procedure  % integer procedure toInteger ( logical value v ) ; if v then 1 else 0;    % procedure to determine whet...
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...
#APL
APL
truth←{ op←⍉↑'~∧∨≠→('(4 3 2 2 1 0) order←⍬⍬{ out stk←⍺ 0=≢⍵:out,⌽stk c rst←(⊃⍵) (1↓⍵) c∊⎕A:((out,c)stk)∇rst c∊'01':((out,⍎c)stk)∇rst (c≠'(')∧(≢op)≥n←op[;1]⍳c:rst∇⍨out{ cnd←⌽∧\⌽(⍵≠'(')∧op[op[;1]⍳⍵;2]≥op[n;2] (⍺,⌽cnd/⍵)(((~cnd)/⍵),c) ...
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,   ...
#D
D
import std.stdio, std.math, std.algorithm, std.array, std.range;   int cell(in int n, int x, int y, in int start=1) pure nothrow @safe @nogc { x = x - (n - 1) / 2; y = y - n / 2; immutable l = 2 * max(x.abs, y.abs); immutable d = (y > x) ? (l * 3 + x + y) : (l - x - y); return (l - 1) ^^ 2 + d + sta...
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Sidef
Sidef
var content = []; Dir.cwd.open.each { |file| file ~~ < . .. > && next; content.append(file); }   content.sort.each { |file| say file; }
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Smalltalk
Smalltalk
Stdout printCR: ( PipeStream outputFromCommand:'ls' )
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...
#Wortel
Wortel
@let { dot &[a b] @sum @mapm ^* [a b] cross &[a b] [[ -*a.1 b.2 *a.2 b.1 -*a.2 b.0 *a.0 b.2 -*a.0 b.1 *a.1 b.0 ]] scalarTripleProduct &[a b c] !!dot a !!cross b c vectorTripleProduct &[a b c] !!cross a !!cross b c   a [3 4 5] b [4 3 5] c [5N 12N 13N]   [[  !!dot a b  !!cross a b ...
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for ...
#WDTE
WDTE
let プリント t => io.writeln io.stdout t;   プリント 'これは実験です。';
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for ...
#Wren
Wren
var w = "voilà" for (c in w) { System.write("%(c) ") // prints the 5 Unicode 'characters'. } System.print("\nThe length of %(w) is %(w.count)")     System.print("\nIts code-points are:") for (cp in w.codePoints) { System.write("%(cp) ") // prints the code-points as numbers }   System.print("\n\nIts bytes are: ...
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...
#Phix
Phix
with javascript_semantics atom t0 = time() function twin_primes(integer maxp, bool both=true) integer n = 0, -- result pn = 2, -- next prime index p, -- a prime, <= maxp prev_p = 2 while true do p = get_prime(pn) if both and p>=maxp then exit end if ...
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...
#Python
Python
from itertools import count, islice   def primes(_cache=[2, 3]): yield from _cache for n in count(_cache[-1]+2, 2): if isprime(n): _cache.append(n) yield n   def isprime(n, _seen={0: False, 1: False}): def _isprime(n): for p in primes(): if p*p > n: ...
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...
#PicoLisp
PicoLisp
(de randN (N) (if (= 1 (rand 1 N)) 1 0) )   (de unbiased (N) (use (A B) (while (= (setq A (randN N)) (setq B (randN N)) ) ) A ) )
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...
#PL.2FI
PL/I
  test: procedure options (main); /* 20 Nov. 2012 */   randN: procedure(N) returns (bit (1)); declare N fixed (1); declare random builtin; declare r fixed (2) external initial (-1); if r >= 0 then do; r = r-1; return ('0'b); end; r = random()*2*N; return ('1'b); end randN;   random: procedure returns ...
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...
#Fortran
Fortran
SUBROUTINE CROAK(GASP) !Something bad has happened. CHARACTER*(*) GASP !As noted. WRITE (6,*) "Oh dear. ",GASP !So, gasp away. STOP "++ungood." !Farewell, cruel world. END !No return from this.   SUBROUTINE FILEHACK(FNAME,NB) CHARACTER*(*) FNAME !Name for the file. ...
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...
#11l
11l
T NNode String value [NNode] children   F (value) .value = value   F add(node) .children.append(node)   F.const to_str(depth) -> String V result = (‘ ’ * depth)‘’(.value)"\n" L(child) .children result ‘’= child.to_str(depth + 1) R result   F String() R .to...
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...
#AutoHotkey
AutoHotkey
; Note: the original puzzle provides 12 statements and starts with ; "Given the following twelve statements...", so the first statement ; should ignore the F1 flag and always be true (see "( N == 1 )").   S := 12 ; number of statements Output := "" Loop, % 2**S { ;;If !Mod(A_Index,100) ;; optional 'if' to show the loo...
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...
#BASIC
BASIC
10 DEFINT A-Z: DATA "~",4,"&",3,"|",2,"^",2,"=>",1 20 DIM V(26),E(255),S(255),C(5),C$(5) 30 FOR I=1 TO 5: READ C$(I),C(I): NEXT 40 PRINT "Boolean expression evaluator" 50 PRINT "----------------------------" 60 PRINT "Operators are: ~ (not), & (and), | (or), ^ (xor), => (implies)." 70 PRINT "Variables are A-Z. Constant...
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,   ...
#EchoLisp
EchoLisp
  (lib 'plot)   (define *red* (rgb 1 0 0)) (define (ulam n nmax) (if ( prime? n) *red* (gray (// n nmax)))) (plot-spiral ulam 1000) ;; range [0...1000]  
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Standard_ML
Standard ML
OS.Process.system "ls -a"
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Stata
Stata
. dir *.dta 6.3k 6/12/17 14:26 auto.dta 2.3k 8/10/17 7:34 titanium.dta 6.0k 8/12/17 9:28 trend.dta
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Tcl
Tcl
puts [join [lsort [glob -nocomplain *]] "\n"]
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...
#Wren
Wren
class Vector3D { construct new(x, y, z) { if (x.type != Num || y.type != Num || z.type != Num) Fiber.abort("Arguments must be numbers.") _x = x _y = y _z = z }   x { _x } y { _y } z { _z }   dot(v) { if (v.type != Vector3D) Fiber.abort("Argument must be ...
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...
#PureBasic
PureBasic
  Procedure isPrime(v.i) If v <= 1  : ProcedureReturn #False ElseIf v < 4  : ProcedureReturn #True ElseIf v % 2 = 0 : ProcedureReturn #False ElseIf v < 9  : ProcedureReturn #True ElseIf v % 3 = 0 : ProcedureReturn #False Else Protected r = Round(Sqr(v), #PB_Round_Down) Protected f = 5 ...
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...
#Python
Python
primes = [2, 3, 5, 7, 11, 13, 17, 19]     def count_twin_primes(limit: int) -> int: global primes if limit > primes[-1]: ram_limit = primes[-1] + 90000000 - len(primes) reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) - 1   while reasonable_limit < limit: ram_limit =...
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...
#Racket
Racket
#lang racket   (require math/number-theory)   (define cached-prime? (let ((hsh# (make-hash))) (λ (p) (hash-ref! hsh# p (λ () (prime? p))))))   (define (zero-digit n d) (define p (expt 10 d)) (+ (remainder n p) (* 10 p (quotient n (* p 10)))))   (define (primeable? n) (or (cached-prime? n) (for*/first ((d ...
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...
#11l
11l
V MAX_PRIME = 1000000 V primes = [1B] * MAX_PRIME primes[0] = primes[1] = 0B   V i = 2 L i * i < MAX_PRIME L(j) (i * i .< MAX_PRIME).step(i) primes[j] = 0B i++ L i < MAX_PRIME & !primes[i] i++   F left_trunc(=n) V tens = 1 L tens < n tens *= 10   L n != 0 I !:primes[n] ...
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...
#PowerShell
PowerShell
  function randN ( [int]$N ) { [int]( ( Get-Random -Maximum $N ) -eq 0 ) }   function unbiased ( [int]$N ) { do { $X = randN $N $Y = randN $N } While ( $X -eq $Y )   return $X }  
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...
#PureBasic
PureBasic
Procedure biased(n) If Random(n) <> 1 ProcedureReturn 0 EndIf ProcedureReturn 1 EndProcedure   Procedure unbiased(n) Protected a, b Repeat a = biased(n) b = biased(n) Until a <> b ProcedureReturn a EndProcedure   #count = 100000   Define n, m, output.s For n = 3 To 6 Dim b_count(1) Dim u_...
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...
#FreeBASIC
FreeBASIC
Sub truncateFile (archivo As String, longitud As Long) If Len(Dir(archivo)) Then Dim f As Long, c As String f = Freefile Open archivo For Binary As #f If longitud > Lof(f) Then Close #f Error 62 'Input past end of file Else c = Space(longit...
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...
#Go
Go
import ( "fmt" "os" )   if err := os.Truncate("filename", newSize); err != nil { fmt.Println(err) }
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...
#C.2B.2B
C++
#include <iomanip> #include <iostream> #include <list> #include <string> #include <vector> #include <utility> #include <vector>   class nest_tree;   bool operator==(const nest_tree&, const nest_tree&);   class nest_tree { public: explicit nest_tree(const std::string& name) : name_(name) {} nest_tree& add_child(...
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...
#BBC_BASIC
BBC BASIC
nStatements% = 12 DIM Pass%(nStatements%), T%(nStatements%)   FOR try% = 0 TO 2^nStatements%-1   REM Postulate answer: FOR stmt% = 1 TO 12 T%(stmt%) = (try% AND 2^(stmt%-1)) <> 0 NEXT   REM Test consistency: Pass%(1) = T%(1) = (nStatements% = 12) ...
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...
#Bracmat
Bracmat
( ( number = n done ntest oldFT .  !arg:(?done.(=?ntest).?oldFT) & 0:?n & (  !done  :  ? ( !ntest . !oldFT&1+!n:?n&~ )  ? | !n ) ) & ( STATEMENTS = ( (1."This is a numbered list o...
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
C
#include <stdio.h> #include <string.h> #include <stdlib.h>   #define TRUE 1 #define FALSE 0 #define STACK_SIZE 80 #define BUFFER_SIZE 100   typedef int bool;   typedef struct { char name; bool val; } var;   typedef struct { int top; bool els[STACK_SIZE]; } stack_of_bool;   char expr[BUFFER_SIZE]; int ex...
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,   ...
#Elixir
Elixir
defmodule Ulam do defp cell(n, x, y, start) do y = y - div(n, 2) x = x - div(n - 1, 2) l = 2 * max(abs(x), abs(y)) d = if y >= x, do: l*3 + x + y, else: l - x - y (l - 1)*(l - 1) + d + start - 1 end   def show_spiral(n, symbol\\nil, start\\1) do IO.puts "\nN : #{n}" if symbol==nil, do:...
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Ursa
Ursa
decl file f decl string<> fnames set fnames (sort (f.listdir "."))   for (decl int i) (< i (size fnames)) (inc i) out fnames<i> endl console end for
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Vlang
Vlang
import os   fn main() { contents := os.ls('.')? println(contents) }
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Wren
Wren
import "io" for Directory   var path = "./" // or whatever   // Note that output is automatically sorted using this method. Directory.list(path).each { |f| System.print(f) }
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...
#XBS
XBS
#> Vector3 Class <# class Vector3 { construct=func(self,x,y,z){ self:x=x; self:y=y; self:z=z; }; ToString=func(self){ send self.x+", "+self.y+", "+self.z; }; Magnitude=func(self){ send math.sqrt((self.x^2)+(self.y^2)+(self.z^2)); }; Normalize=func(self){ set Mag = self::Magnitude(); send new Vector...
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...
#Quackery
Quackery
[ dup dip [ eratosthenes 0 1 primes share ] bit 1 - & 1 >> [ dup while dup 5 & 5 = if [ rot 1+ unrot ] 2 >> dip [ 2 + ] again ] 2drop ] is twinprimes ( n --> [ )   5 times [ say "Number of twin primes below " 10 i^ 1+ ** dup echo ...
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...
#Raku
Raku
use Lingua::EN::Numbers;   use Math::Primesieve;   my $p = Math::Primesieve.new;   printf "Twin prime pairs less than %14s: %s\n", comma(10**$_), comma $p.count(10**$_, :twins) for 1 .. 10;
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...
#Raku
Raku
use ntheory:from<Perl5> <is_prime>; use Lingua::EN::Numbers;   sub is-unprimeable (\n) { return False if n.&is_prime; my \chrs = n.chars; for ^chrs -> \place { my \pow = 10**(chrs - place - 1); my \this = n.substr(place, 1) × pow; ^10 .map: -> \dgt { next if this =...
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...
#Ada
Ada
  with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Ordered_Sets;   procedure Truncatable_Primes is package Natural_Set is new Ada.Containers.Ordered_Sets (Natural); use Natural_Set;   Primes : Set;   function Is_Prime (N : Natural) return Boolean is Position : Cursor := First (Primes); begin...
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...
#Python
Python
from __future__ import print_function import random   def randN(N): " 1,0 random generator factory with 1 appearing 1/N'th of the time" return lambda: random.randrange(N) == 0   def unbiased(biased): 'uses a biased() generator of 1 or 0, to create an unbiased one' this, that = biased(), biased() whi...
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...
#Haskell
Haskell
setFileSize :: FilePath -> FileOffset -> IO () -- Truncates the file down to the specified length. -- If the file was larger than the given length -- before this operation was performed the extra is lost. -- Note: calls truncate.  
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...
#Icon_and_Unicon
Icon and Unicon
truncate(f := open(filename, "bu"), newsizeinbytes) & 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...
#J
J
require 'files' NB. needed for versions prior to J7 ftruncate=: ] fwrite~ ] fread@; 0 , [
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...
#Go
Go
package main   import ( "fmt" "io" "os" "strings" )   type nNode struct { name string children []nNode }   type iNode struct { level int name string }   func printNest(n nNode, level int, w io.Writer) { if level == 0 { fmt.Fprintln(w, "\n==Nest form==\n") } fmt.F...
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...
#AppleScript
AppleScript
on treeFromNestingLevels(input) set maxLevel to 0 repeat with thisLevel in input if (thisLevel > maxLevel) then set maxLevel to thisLevel end repeat if (maxLevel < 2) then return input   set emptyList to {} repeat with testLevel from maxLevel to 2 by -1 set output to {} 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...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   public static class TwelveStatements { public static void Main() { Func<Statements, bool>[] checks = { st => st[1], st => st[2] == (7.To(12).Count(i => st[i]) == 3), st => st[3] == (2.To(12, by: 2).Count...
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.2B.2B
C++
#include <iostream> #include <stack> #include <string> #include <sstream> #include <vector>   struct var { char name; bool value; }; std::vector<var> vars;   template<typename T> T pop(std::stack<T> &s) { auto v = s.top(); s.pop(); return v; }   bool is_operator(char c) { return c == '&' || c ==...
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,   ...
#ERRE
ERRE
PROGRAM SPIRAL   !$INTEGER   CONST RIGHT=1,UP=2,LEFT=3,DOWN=4   !$DYNAMIC DIM SPIRAL$[0,0]   PROCEDURE PRT_ULAM(N) FOR ROW=0 TO N DO FOR COL=0 TO N DO PRINT(SPIRAL$[ROW,COL];) END FOR PRINT END FOR PRINT GET(K$) FOR ROW=0 TO N DO FOR COL=0 TO N DO IF VAL(SPIRAL$[ROW,COL])<>0 TH...
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#XPL0
XPL0
string 0; char S; [S:= "ls"; asm { ldr r0, S bl system } ]
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#zkl
zkl
File.glob("*").sort()