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/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...
#Delphi
Delphi
  program Primes;   {$APPTYPE CONSOLE}   {$R *.res}   uses System.SysUtils;   function IsPrime(a: UInt64): Boolean; var d: UInt64; begin if (a < 2) then exit(False);   if (a mod 2) = 0 then exit(a = 2);   if (a mod 3) = 0 then exit(a = 3);   d := 5;   while (d * d <= a) do begin if (a mo...
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...
#Kotlin
Kotlin
private const val MAX = 10000000 private val primes = BooleanArray(MAX)   fun main() { sieve() println("First 35 unprimeable numbers:") displayUnprimeableNumbers(35) val n = 600 println() println("The ${n}th unprimeable number = ${nthUnprimeableNumber(n)}") println() val lowest = genLowe...
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...
#Racket
Racket
  #lang racket   ;; Racket can use Unicode in identifier names (define √ sqrt) (√ 256) ; -> 16 ;; and in fact the standard language makes use of some of these (λ(x) x) ; -> an identity function   ;; The required binding: (define Δ 1) (set! Δ (add1 Δ)) (printf "Δ = ~s\n" Δ) ; prints "Δ = 2"    
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...
#Raku
Raku
my $Δ = 1; $Δ++; say $Δ;
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...
#Retro
Retro
'Δ var #1 !Δ @Δ n:put &Δ v:inc @Δ n:put
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...
#REXX
REXX
/*REXX program (using the R4 REXX interpreter) which uses a Greek delta char).*/ 'chcp' 1253 "> NUL" /*ensure we're using correct code page.*/ Δ=1 /*define delta (variable name Δ) to 1*/ Δ=Δ+1 /*bump the delta REXX variable by unit...
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...
#Haskell
Haskell
import Control.Monad.Random import Control.Monad import Text.Printf   randN :: MonadRandom m => Int -> m Int randN n = fromList [(0, fromIntegral n-1), (1, 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...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) iters := \A[1] | 10000 write("ratios of 0 to 1 from ",iters," trials:") every n := 3 to 6 do { results_randN := table(0) results_unbiased := table(0) every 1 to iters do { results_randN[randN(n)] +:= 1 results_unbiased[unbiased(n)] +:= 1 ...
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced...
#Action.21
Action!
INCLUDE "D2:IO.ACT" ;from the Action! Tool Kit   PROC Dir(CHAR ARRAY filter) BYTE dev=[1] CHAR ARRAY line(255)   Close(dev) Open(dev,filter,6) DO InputSD(dev,line) PrintE(line) IF line(0)=0 THEN EXIT FI OD Close(dev) RETURN   BYTE FUNC Find(CHAR ARRAY text CHAR c) BYTE i   i=1 ...
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced...
#Ada
Ada
with Ada.Command_Line, Ada.Sequential_IO, Ada.Directories;   procedure Truncate_File is   type Byte is mod 256; for Byte'Size use 8;   package Byte_IO is new Ada.Sequential_IO(Byte);   function Arg(N: Positive) return String renames Ada.Command_Line.Argument; function Args return Natural renames Ada.Comm...
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,   ...
#11l
11l
F cell(n, =x, =y, start = 1) V d = 0 y = y - n I/ 2 x = x - (n - 1) I/ 2 V l = 2 * max(abs(x), abs(y)) d = I y >= x {(l * 3 + x + y)} E (l - x - y) R (l - 1) ^ 2 + d + start - 1   F show_spiral(n, symbol = ‘# ’, start = 1, =space = ‘’) V top = start + n * n + 1 V is_prime = [0B, 0B, 1B] [+] [1B,...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[Unload, Load, Spin, Fire] Unload[] := ConstantArray[False, 6] Load[state_List] := Module[{s = state}, While[s[[2]], s = RotateRight[s, 1] ]; s[[2]] = True; s ] Spin[state_List] := RotateRight[state, RandomInteger[{1, 6}]] Fire[state_List] := Module[{shot}, shot = First[state]; {RotateRight[st...
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...
#Nim
Nim
import algorithm, random, sequtils, strformat, strutils, tables   type Revolver = array[6, bool] Action {.pure.} = enum Load, Spin, Fire, Error   const Actions = {'L': Load, 'S': Spin, 'F': Fire}.toTable   func spin(revolver: var Revolver; count: Positive) = revolver.rotateLeft(-count)   func load(revolver: var 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...
#Perl
Perl
use strict; use warnings; use feature 'say';   my @cyl; my $shots = 6;   sub load { push @cyl, shift @cyl while $cyl[1]; $cyl[1] = 1; push @cyl, shift @cyl }   sub spin { push @cyl, shift @cyl for 0 .. int rand @cyl } sub fire { push @cyl, shift @cyl; $cyl[0] }   sub LSLSFSF { @cyl = (0) x $shots; ...
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:...
#Phix
Phix
without js -- (file i/o) pp(dir("."),{pp_Nest,1,pp_IntCh,false})
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:...
#PHP
PHP
  <?php foreach(scandir('.') as $fileName){ echo $fileName."\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...
#Stata
Stata
mata real scalar sprod(real colvector u, real colvector v) { return(u[1]*v[1] + u[2]*v[2] + u[3]*v[3]) }   real colvector vprod(real colvector u, real colvector v) { return(u[2]*v[3]-u[3]*v[2]\u[3]*v[1]-u[1]*v[3]\u[1]*v[2]-u[2]*v[1]) }   real scalar striple(real colvector u, real colvector v, real colvector w) { ret...
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Raku
Raku
my $x; $x = 42; $x = Nil; say $x.WHAT; # prints Any()
http://rosettacode.org/wiki/Undefined_values
Undefined values
#REXX
REXX
/*REXX program test if a (REXX) variable is defined or not defined. */ tlaloc = "rain god of the Aztecs." /*assign a value to the Aztec rain god.*/ /*check if the rain god is defined. */ y= 'tlaloc' if symbol(y)=="VAR" then say y ' is defined.' ...
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 ...
#Pike
Pike
  #charset utf8 void main() { string nånsense = "\u03bb \0344 \n"; string hello = "你好"; string 水果 = "pineapple"; string 真相 = sprintf("%s, %s goes really well on pizza\n", hello, 水果); write( string_to_utf8(真相) ); write( string_to_utf8(nånsense) ); }  
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 ...
#Python
Python
#!/usr/bin/env python # -*- coding: latin-1 -*-   u = 'abcdé' print(ord(u[-1]))
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...
#F.23
F#
  printfn "twin primes below 100000: %d" (primes64()|>Seq.takeWhile(fun n->n<=100000L)|>Seq.pairwise|>Seq.filter(fun(n,g)->g=n+2L)|>Seq.length) printfn "twin primes below 1000000: %d" (primes64()|>Seq.takeWhile(fun n->n<=1000000L)|>Seq.pairwise|>Seq.filter(fun(n,g)->g=n+2L)|>Seq.length) printfn "twin primes below 10000...
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...
#Lua
Lua
-- FUNCS: local function T(t) return setmetatable(t, {__index=table}) end table.filter = function(t,f) local s=T{} for _,v in ipairs(t) do if f(v) then s[#s+1]=v end end return s end table.firstn = function(t,n) local s=T{} n=n>#t and #t or n for i = 1,n do s[i]=t[i] end return s end   -- SIEVE: local sieve, S = {}, 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...
#Ring
Ring
  # Project : Unicode variable names   Δ = "Ring Programming Language" see Δ + nl  
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...
#Ruby
Ruby
Δ = 1 Δ += 1 puts Δ # => 2
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...
#Rust
Rust
#![feature(non_ascii_idents)] #![allow(non_snake_case)]   fn main() { let mut Δ: i32 = 1; Δ += 1; println!("{}", Δ); }
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...
#S-lang
S-lang
define ∆increment(∆ref) { @∆ref++; } variable foo∆bar = 1; foo∆bar++; variable ∆bar = 1; ∆bar++; ∆increment(&∆bar); % foo∆bar should be 2 and ∆bar should be 3. print(foo∆bar); print(∆bar);  
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...
#J
J
randN=: 0 = ? unbiased=: i.@# { ::$: 2 | 0 3 -.~ _2 #.\ 4&* randN@# ]
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...
#Java
Java
public class Bias { public static boolean biased(int n) { return Math.random() < 1.0 / n; }   public static boolean unbiased(int n) { boolean a, b; do { a = biased(n); b = biased(n); } while (a == b); return a; }   public static void ma...
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...
#AutoHotkey
AutoHotkey
truncFile("S:\Portables\AutoHotkey\My Scripts\Other_Codes\motion2.ahk", 1200) return   truncFile(file, length_bytes){ if !FileExist(file) msgbox, File doesn't exists. FileGetSize, fsize, % file, B if (length_bytes>fsize) msgbox, New truncated size more than current file size f := FileOpen(file, "rw") f.length ...
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...
#AWK
AWK
  # syntax: GAWK -f TRUNCATE_A_FILE.AWK BEGIN { main("NOTHERE",100) main("FILENAME.TMP",-1) main("FILENAME.TMP",500) exit(0) } function main(filename,size, ret) { ret = truncate_file(filename,size) if (ret != "") { printf("error: FILENAME=%s, %s\n",filename,ret) } } function truncate_...
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,   ...
#360_Assembly
360 Assembly
* Ulam spiral 26/04/2016 ULAM CSECT USING ULAM,R13 set base register SAVEAREA B STM-SAVEAREA(R15) skip savearea DC 17F'0' savearea STM STM R14,R12,12(R13) prolog ST R13,4(R15) save previous SA ST R15...
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...
#Phix
Phix
with javascript_semantics function spin(sequence revolver, integer count) while count do revolver = revolver[$]&revolver[1..$-1] count -= 1 end while return revolver end function function load(sequence revolver) while revolver[1] do revolver = spin(revolver,1) end while ...
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:...
#Picat
Picat
import os, util. main => println(ls()), println(ls("foo/bar")).   ls() = ls("."). ls(Path) = [F : F in listdir(Path), F != ".",F != ".."].sort.join('\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:...
#PicoLisp
PicoLisp
(for F (sort (dir)) (prinl F) )
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:...
#Pike
Pike
foreach(sort(get_dir()), string file) write(file +"\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...
#Swift
Swift
import Foundation   infix operator • : MultiplicationPrecedence infix operator × : MultiplicationPrecedence   public struct Vector { public var x = 0.0 public var y = 0.0 public var z = 0.0   public init(x: Double, y: Double, z: Double) { (self.x, self.y, self.z) = (x, y, z) }   public static func • (lh...
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Ring
Ring
  # Project : Undefined values   test() func test x=10 y=20 see islocal("x") + nl + islocal("y") + nl + islocal("z") + nl  
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Ruby
Ruby
# Check to see whether it is defined puts "var is undefined at first check" unless defined? var   # Give it a value var = "Chocolate"   # Check to see whether it is defined after we gave it the # value "Chocolate" puts "var is undefined at second check" unless defined? var   # I don't know any way of undefining a varia...
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Rust
Rust
use std::ptr;   let p: *const i32 = ptr::null(); assert!(p.is_null());
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 ...
#Racket
Racket
  #lang racket   ;; Unicode in strings, using ascii "\u03bb" ; -> "λ" ;; and since Racket source code is read in UTF-8, Unicode can be used ;; directly "λ" ; -> same   ;; The same holds for character constants #\u3bb ; -> #\λ #\λ  ; -> same   ;; And of course Unicode can be used in identifiers, (define √ sqrt) (√ 256...
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 ...
#Raku
Raku
sub prefix:<∛> (\𝐕) { 𝐕 ** (1/3) } say ∛27; # prints 3
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 ...
#REXX
REXX
  see "Hello, World!"   func ringvm_see cText ring_see("I can play with the string before displaying it" + nl) ring_see("I can convert it :D" + nl) ring_see("Original Text: " + cText + nl) if cText = "Hello, World!" # Convert it from English to Hindi cText = "नमस्ते दुनिया!" ...
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...
#Factor
Factor
USING: io kernel math math.parser math.primes.erato math.ranges sequences tools.memory.private ;   : twin-pair-count ( n -- count ) [ 5 swap 2 <range> ] [ sieve ] bi [ over 2 - over [ marked-prime? ] 2bi@ and ] curry count ;   "Search size: " write flush readln string>number twin-pair-count commas write " twin ...
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...
#FreeBASIC
FreeBASIC
  Function isPrime(Byval ValorEval As Integer) As Boolean If ValorEval <=1 Then Return False For i As Integer = 2 To Int(Sqr(ValorEval)) If ValorEval Mod i = 0 Then Return False Next i Return True End Function   Function paresDePrimos(limite As Uinteger) As Uinteger Dim As Uinteger p1 = 0, p...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[Unprimeable] Unprimeable[in_Integer] := Module[{id, new, pos}, id = IntegerDigits[in]; pos = Catenate@Table[ Table[ new = id; new[[d]] = n; new , {n, 0, 9} ] , {d, Length[id]} ]; pos //= Map[FromDigits]; NoneTrue[pos, PrimeQ] ] res = {}; PrintTe...
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...
#Scala
Scala
var Δ = 1 val π = 3.141592 val 你好 = "hello" Δ += 1 println(Δ)
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...
#SenseTalk
SenseTalk
put 1 into Δ add 1 to Δ put Δ
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...
#Sidef
Sidef
var Δ = 1; Δ += 1; say Δ;
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...
#Stata
Stata
sca Δ=10 sca Δ=Δ+1 di Δ   local Δ=20 local ++Δ di `Δ'   mata Δ=30 Δ++ Δ end
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...
#Julia
Julia
using Printf   randN(N) = () -> rand(1:N) == 1 ? 1 : 0 function unbiased(biased::Function) this, that = biased(), biased() while this == that this, that = biased(), biased() end return this end   @printf "%2s | %10s | %5s | %5s | %8s" "N" "bias./unb." "1s" "0s" "pct ratio" const nrep = 10000 for N in 3:6 ...
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...
#Kotlin
Kotlin
// version 1.1.2   fun biased(n: Int) = Math.random() < 1.0 / n   fun unbiased(n: Int): Boolean { var a: Boolean var b: Boolean do { a = biased(n) b = biased(n) } while (a == b) return a }   fun main(args: Array<String>) { val m = 50_000 val f = "%d: %2.2f%%  %2.2f%%" ...
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced...
#BASIC
BASIC
SUB truncateFile (file AS STRING, length AS LONG) IF LEN(DIR$(file)) THEN DIM f AS LONG, c AS STRING f = FREEFILE OPEN file FOR BINARY AS f IF length > LOF(f) THEN CLOSE f ERROR 62 'Input past end of file ELSE c = SPACE$(length) ...
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...
#BBC_BASIC
BBC BASIC
DEF PROCtruncate(file$, size%) LOCAL file% file% = OPENUP(file$) IF file%=0 ERROR 100, "Could not open file" EXT#file% = size% CLOSE #file% ENDPROC
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,   ...
#Ada
Ada
generic Size: Positive; -- determines the size of the square with function Represent(N: Natural) return String; -- this turns a number into a string to be printed -- the length of the output should not change -- e.g., Represent(N) may return " #" if N is a prime -- and " " else ...
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...
#Python
Python
""" Russian roulette problem """ import numpy as np   class Revolver: """ simulates 6-shot revolving cylinger pistol """   def __init__(self): """ start unloaded """ self.cylinder = np.array([False] * 6)   def unload(self): """ empty all chambers of cylinder """ self.cylinder...
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:...
#PowerShell
PowerShell
# Prints Name, Length, Mode, and LastWriteTime Get-ChildItem | Sort-Object Name | Write-Output   # Prints only the name of each file in the directory Get-ChildItem | Sort-Object Name | ForEach-Object Name | Write-Output
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:...
#PureBasic
PureBasic
NewList lslist.s()   If OpenConsole("ls-sim") If ExamineDirectory(0,GetCurrentDirectory(),"*.*") While NextDirectoryEntry(0) AddElement(lslist()) : lslist()=DirectoryEntryName(0) Wend FinishDirectory(0) SortList(lslist(),#PB_Sort_Ascending) ForEach lslist() PrintN(lslist()) Next ...
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...
#Tcl
Tcl
proc dot {A B} { lassign $A a1 a2 a3 lassign $B b1 b2 b3 expr {$a1*$b1 + $a2*$b2 + $a3*$b3} } proc cross {A B} { lassign $A a1 a2 a3 lassign $B b1 b2 b3 list [expr {$a2*$b3 - $a3*$b2}] \ [expr {$a3*$b1 - $a1*$b3}] \ [expr {$a1*$b2 - $a2*$b1}] } proc scalarTriple {A B C} { dot $A [cross $...
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Scala
Scala
var x; # declared, but not defined x == nil && say "nil value"; defined(x) || say "undefined";   # Give "x" some value x = 42;   defined(x) && say "defined";   # Change "x" back to `nil` x = nil;   defined(x) || say "undefined";
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Seed7
Seed7
var x; # declared, but not defined x == nil && say "nil value"; defined(x) || say "undefined";   # Give "x" some value x = 42;   defined(x) && say "defined";   # Change "x" back to `nil` x = nil;   defined(x) || say "undefined";
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 ...
#Ring
Ring
  see "Hello, World!"   func ringvm_see cText ring_see("I can play with the string before displaying it" + nl) ring_see("I can convert it :D" + nl) ring_see("Original Text: " + cText + nl) if cText = "Hello, World!" # Convert it from English to Hindi cText = "नमस्ते दुनिया!" ...
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 ...
#Ruby
Ruby
str = "你好" str.include?("好") # => true
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 ...
#Scala
Scala
object UTF8 extends App {   def charToInt(s: String) = { def charToInt0(c: Char, next: Char): Option[Int] = (c, next) match { case _ if (c.isHighSurrogate && next.isLowSurrogate) => Some(java.lang.Character.toCodePoint(c, next)) case _ if (c.isLowSurrogate) => None case _ ...
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...
#Go
Go
package main   import "fmt"   func sieve(limit uint64) []bool { limit++ // True denotes composite, false denotes prime. c := make([]bool, limit) // all false by default c[0] = true c[1] = true // no need to bother with even numbers over 2 for this task p := uint64(3) // Start from 3. for...
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...
#Nim
Nim
import strutils   const N = 10_000_000   # Erastosthenes sieve. var composite: array[0..N, bool] # Defualt is false i.e. composite. composite[0] = true composite[1] = true for n in 2..N: if not composite[n]: for k in countup(n * n, N, n): composite[k] = true   template isPrime(n: int): bool = not composite...
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...
#Swift
Swift
var Δ = 1 let π = 3.141592 let 你好 = "hello" Δ++ println(Δ)
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...
#Tcl
Tcl
set Δx 1 incr Δx puts [set Δx] puts ${Δx}
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...
#UNIX_Shell
UNIX Shell
  Δ=1 Δ=`expr $Δ + 1` echo $Δ  
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...
#Lua
Lua
  local function randN(n) return function() if math.random() < 1/n then return 1 else return 0 end end end   local function unbiased(n) local biased = randN (n) return function() local a, b = biased(), biased() while a==b do a, b = biased(), biased() end return a end end   local func...
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...
#Bracmat
Bracmat
( ( trunc = name length elif file c .  !arg:(?name,?length) & fil$(!name,rb) & fil$(,DEC,1) & :?elif & whl ' ( !length+-1:?length:~<0 & fil$() !elif:?elif ) & (fil$(,SET,-1)|) & whl'(!elif:%?c ?elif&!c !file:?file) & fil$(!name,wb) &...
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...
#C
C
#include <windows.h> #include <stdio.h> #include <wchar.h>   /* Print "message: last Win32 error" to stderr. */ void oops(const wchar_t *message) { wchar_t *buf; DWORD error;   buf = NULL; error = GetLastError(); FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNOR...
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,   ...
#C
C
  #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <math.h>   typedef uint32_t bitsieve;   unsigned sieve_check(bitsieve *b, const unsigned v) { if ((v != 2 && !(v & 1)) || (v < 2)) return 0; else return !(b[v >> 6] & (1 << (v >> 1 & 31))); }   bitsieve* sieve(const unsigned v...
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...
#Raku
Raku
unit sub MAIN ($shots = 6);   my @cyl;   sub load () { @cyl.=rotate(-1) while @cyl[1]; @cyl[1] = 1; @cyl.=rotate(-1); }   sub spin () { @cyl.=rotate: (^@cyl).pick }   sub fire () { @cyl.=rotate; @cyl[0] }   sub LSLSFSF { @cyl = 0 xx $shots; load, spin, load, spin; return 1 if fire; spin; ...
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:...
#Python
Python
>>> import os >>> print('\n'.join(sorted(os.listdir('.')))) DLLs Doc LICENSE.txt Lib NEWS.txt README.txt Scripts Tools include libs python.exe pythonw.exe tcl >>>
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:...
#R
R
  cat(paste(list.files(), collapse = "\n"), "\n") cat(paste(list.files("bar"), collapse = "\n"), "\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...
#uBasic.2F4tH
uBasic/4tH
a = 0 ' use variables for vector addresses b = a + 3 c = b + 3 d = c + 3   Proc _Vector (a, 3, 4, 5) ' initialize the vectors Proc _Vector (b, 4, 3, 5) Proc _Vector (c, -5, -12, -13)   Print "a . b = "; FUNC(_FNdot(a, b)) Proc _Cross (a, b, d) Print "a x b = (";@(d+0);", ";...
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Sidef
Sidef
var x; # declared, but not defined x == nil && say "nil value"; defined(x) || say "undefined";   # Give "x" some value x = 42;   defined(x) && say "defined";   # Change "x" back to `nil` x = nil;   defined(x) || say "undefined";
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Smalltalk
Smalltalk
Smalltalk includesKey: #FooBar myNamespace includesKey: #Baz
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 ...
#Swift
Swift
let flag = "🇵🇷" print(flag.characters.count) // Prints "1" print(flag.unicodeScalars.count) // Prints "2" print(flag.utf16.count) // Prints "4" print(flag.utf8.count) // Prints "8"   let nfc = "\u{01FA}"//Ǻ LATIN CAPITAL LETTER A WITH RING ABOVE AND ACUTE let nfd = "\u{0041}\u{030A}\u{0301}"//Latin Capital Letter 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 ...
#Rust
Rust
# 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...
#Java
Java
  import java.math.BigInteger; import java.util.Scanner;   public class twinPrimes { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Search Size: "); BigInteger max = input.nextBigInteger(); int counter = 0; for(BigInteger ...
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...
#Pascal
Pascal
program unprimable; {$IFDEF FPC}{$Mode Delphi}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF}   const base = 10;   type TNumVal = array[0..base-1] of NativeUint; TConvNum = record NumRest : TNumVal; LowDgt, MaxIdx : NativeUint; end;   var //global PotBase, EndDgtFou...
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...
#Vala
Vala
Sub Main() Dim Δ As Integer Δ=1 Δ=Δ+1 Debug.Print Δ End Sub
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...
#VBA
VBA
Sub Main() Dim Δ As Integer Δ=1 Δ=Δ+1 Debug.Print Δ End Sub
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...
#Visual_Basic
Visual Basic
Sub Main() Dim Δ As Integer Δ=1 Δ=Δ+1 Debug.Print Δ End Sub
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...
#Wren
Wren
var a = 3 var b = 2 var delta = a - b // ok var Δ = delta // not ok
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
rand[bias_, n_] := 1 - Unitize@RandomInteger[bias - 1, n] unbiased[bias_, n_] := DeleteCases[rand[bias, {n, 2}], {a_, a_}][[All, 1]] count = 1000000; TableForm[ Table[{n, Total[rand[n, count]]/count // N, Total[#]/Length[#] &@unbiased[n, count] // N}, {n, 3, 6}], TableHeadings -> {None, {n, "biased", "unbiased"}...
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...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method biased(n = int) public static returns boolean return Math.random() < 1.0 / 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...
#C.23
C#
using System; using System.IO;   namespace TruncateFile { internal class Program { private static void Main(string[] args) { TruncateFile(args[0], long.Parse(args[1])); }   private static void TruncateFile(string path, long length) { if (!File.Exis...
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...
#C.2B.2B
C++
#include <string> #include <fstream>   using namespace std;   void truncateFile(string filename, int max_size) { std::ifstream input( filename, std::ios::binary ); char buffer; string outfile = filename + ".trunc"; ofstream appendFile(outfile, ios_base::out); for(int i=0; i<max_size; i++) { input.read( &b...
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...
#11l
11l
T Symbol String id Int lbp Int nud_bp Int led_bp (ASTNode -> ASTNode) nud ((ASTNode, ASTNode) -> ASTNode) led   F set_nud_bp(nud_bp, nud) .nud_bp = nud_bp .nud = nud   F set_led_bp(led_bp, led) .led_bp = led_bp .led = led   T Var String name Int value F (name) ...
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,   ...
#C.2B.2B
C++
#include <cmath> #include <iostream> #include <string> #include <iomanip> #include <vector>   class ulamSpiral { public: void create( unsigned n, unsigned startWith = 1 ) { _lst.clear(); if( !( n & 1 ) ) n++; _mx = n; unsigned v = n * n; _wd = static_cast<unsigned>( log10( st...
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...
#REXX
REXX
/*REXX pgm simulates scenarios for a two─bullet Russian roulette game with a 6 cyl. gun.*/ parse arg cyls tests seed . /*obtain optional arguments from the CL*/ if cyls=='' | cyls=="," then cyls= 6 /*Not specified? Then use the default.*/ if tests=='' | tests=="," then tests= 100000 ...
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:...
#Racket
Racket
#lang racket/base   ;; Racket's `directory-list' produces a sorted list of files (define (ls) (for-each displayln (directory-list)))   ;; Code to run when this file is running directly (module+ main (ls))   (module+ test (require tests/eli-tester racket/port racket/file) (define (make-directory-tree) (make-di...
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:...
#Raku
Raku
.say for sort ~«dir
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:...
#REXX
REXX
/*REXX program lists contents of current folder (ala mode UNIX's LS). */ 'DIR /b /oN' /*use Windows DIR: sorts & lists.*/ /*stick a fork in it, we're done.*/
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...
#VBA
VBA
Option Base 1 Function dot_product(a As Variant, b As Variant) As Variant dot_product = WorksheetFunction.SumProduct(a, b) End Function   Function cross_product(a As Variant, b As Variant) As Variant cross_product = Array(a(2) * b(3) - a(3) * b(2), a(3) * b(1) - a(1) * b(3), a(1) * b(2) - a(2) * b(1)) End Funct...
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Tcl
Tcl
# Variables are undefined by default and do not need explicit declaration   # Check to see whether it is defined if {![info exists var]} {puts "var is undefind at first check"}   # Give it a value set var "Screwy Squirrel"   # Check to see whether it is defined if {![info exists var]} {puts "var is undefind at second c...
http://rosettacode.org/wiki/Undefined_values
Undefined values
#UNIX_Shell
UNIX Shell
VAR1="VAR1" echo ${VAR1:-"Not set."} echo ${VAR2:-"Not set."}