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 number).
Extension
Find all twin prime pairs under 100000, 10000000 and 1000000000.
What is the time complexity of the program? Are there ways to reduce computation time?
Examples
> Search Size: 100
> 8 twin prime pairs.
> Search Size: 1000
> 35 twin prime pairs.
Also see
The OEIS entry: A001097: Twin primes.
The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.
The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.
The OEIS entry: A007508: Number of twin prime pairs below 10^n.
| #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 mod d = 0) then
Exit(false);
inc(d, 2);
if (a mod d = 0) then
Exit(false);
inc(d, 4);
end;
Result := True;
end;
function Sieve(limit: UInt64): TArray<Boolean>;
var
p, p2, i: UInt64;
begin
inc(limit);
SetLength(Result, limit);
FillChar(Result[2], sizeof(Boolean) * limit - 2, 0); // all false except 1,2
FillChar(Result[0], sizeof(Boolean) * 2, 1); // 1,2 are true
p := 3;
while true do
begin
p2 := p * p;
if p2 >= limit then
break;
i := p2;
while i < limit do
begin
Result[i] := true;
inc(i, 2 * p);
end;
while true do
begin
inc(p, 2);
if not Result[p] then
Break;
end;
end;
end;
function Commatize(const n: UInt64): string;
var
str: string;
digits: Integer;
i: Integer;
begin
Result := '';
str := n.ToString;
digits := str.Length;
for i := 1 to digits do
begin
if ((i > 1) and (((i - 1) mod 3) = (digits mod 3))) then
Result := Result + ',';
Result := Result + str[i];
end;
end;
var
limit, start, twins: UInt64;
c: TArray<Boolean>;
i, j: UInt64;
begin
c := Sieve(Trunc(1e9 - 1));
limit := 10;
start := 3;
twins := 0;
for i := 1 to 9 do
begin
j := start;
while j < limit do
begin
if (not c[j]) and (not c[j - 2]) then
inc(twins);
inc(j, 2);
end;
Writeln(Format('Under %14s there are %10s pairs of twin primes.', [commatize
(limit), commatize(twins)]));
start := limit + 1;
limit := 10 * limit;
end;
readln;
end.
|
http://rosettacode.org/wiki/Unprimeable_numbers | Unprimeable numbers | Definitions
As used here, all unprimeable numbers (positive integers) are always expressed in base ten.
───── Definition from OEIS ─────:
Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed.
───── Definition from Wiktionary (referenced from Adam Spencer's book) ─────:
(arithmetic) that cannot be turned into a prime number by changing just one of its digits to any other
digit. (sic)
Unprimeable numbers are also spelled: unprimable.
All one─ and two─digit numbers can be turned into primes by changing a single decimal digit.
Examples
190 isn't unprimeable, because by changing the zero digit into a three yields 193, which is a prime.
The number 200 is unprimeable, since none of the numbers 201, 202, 203, ··· 209 are
prime, and all the other numbers obtained by changing a single digit to
produce 100, 300, 400, ··· 900, or 210, 220, 230, ··· 290 which are all even.
It is valid to change 189 into 089 by changing the 1 (one) into
a 0 (zero), which then the leading zero can be removed, and then treated as if
the "new" number is 89.
Task
show the first 35 unprimeable numbers (horizontally, on one line, preferably with a title)
show the 600th unprimeable number
(optional) show the lowest unprimeable number ending in a specific decimal digit (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
(optional) use commas in the numbers where appropriate
Show all output here, on this page.
Also see
the OEIS entry: A118118 (unprimeable)
with some useful counts to compare unprimeable number
the Wiktionary entry (reference from below): (arithmetic definition) unprimeable
from the Adam Spencer book (page 200): Adam Spencer's World of Numbers (Xoum Publishing)
| #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 = genLowest()
println("Least unprimeable number that ends in:")
for (i in 0..9) {
println(" $i is ${lowest[i]}")
}
}
private fun genLowest(): IntArray {
val lowest = IntArray(10)
var count = 0
var test = 1
while (count < 10) {
test++
if (unPrimable(test) && lowest[test % 10] == 0) {
lowest[test % 10] = test
count++
}
}
return lowest
}
private fun nthUnprimeableNumber(maxCount: Int): Int {
var test = 1
var count = 0
var result = 0
while (count < maxCount) {
test++
if (unPrimable(test)) {
count++
result = test
}
}
return result
}
private fun displayUnprimeableNumbers(maxCount: Int) {
var test = 1
var count = 0
while (count < maxCount) {
test++
if (unPrimable(test)) {
count++
print("$test ")
}
}
println()
}
private fun unPrimable(test: Int): Boolean {
if (primes[test]) {
return false
}
val s = test.toString() + ""
for (i in s.indices) {
for (j in 0..9) {
if (primes[replace(s, i, j).toInt()]) {
return false
}
}
}
return true
}
private fun replace(str: String, position: Int, value: Int): String {
val sChar = str.toCharArray()
sChar[position] = value.toChar()
return str.substring(0, position) + value + str.substring(position + 1)
}
private fun sieve() {
// primes
for (i in 2 until MAX) {
primes[i] = true
}
for (i in 2 until MAX) {
if (primes[i]) {
var j = 2 * i
while (j < MAX) {
primes[j] = false
j += i
}
}
}
} |
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 identifiers
| #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 identifiers
| #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 identifiers
| #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 identifiers
| #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 unity*/
say 'Δ=' Δ /*stick a fork in it, we're all done. */ |
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/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
For N over its range, generate and show counts of the outputs of randN and unbiased(randN).
The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.
This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
| #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/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
For N over its range, generate and show counts of the outputs of randN and unbiased(randN).
The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.
This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
| #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
}
showResults(n, "randN", results_randN)
showResults(n, "unbiased", results_unbiased)
}
end
procedure showResults(n, s, t)
write(n," ",left(s,9),":",t[0],"/",t[1]," = ",t[0]/real(t[1]))
end
procedure unbiased(n)
repeat {
n1 := randN(n)
n2 := randN(n)
if n1 ~= n2 then suspend n1
}
end
procedure randN(n)
repeat suspend if 1 = ?n then 1 else 0
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 size and renaming it, after first deleting the original file, if no other method is available. The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged.
If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition.
On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file.
This task permits the use of such facilities. However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
| #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
WHILE i<=text(0)
DO
IF text(i)=c THEN
RETURN (i)
FI
i==+1
OD
RETURN (0)
PROC MakeRenameCommand(CHAR ARRAY left,right,result)
BYTE i,len,pos
SCopy(result,left)
len=left(0)+1
result(len)=32
pos=Find(right,':)
FOR i=pos+1 TO right(0)
DO
len==+1
result(len)=right(i)
OD
result(0)=len
RETURN
PROC DeleteFile(CHAR ARRAY fname)
BYTE dev=[1]
Close(dev)
Xio(dev,0,33,0,0,fname)
RETURN
PROC TruncateFile(CHAR ARRAY fname CARD maxlen)
DEFINE BUF_LEN="100"
CHAR ARRAY tmp="D:TEMP.TMP",cmd(255)
BYTE in=[1], out=[2]
BYTE ARRAY buff(BUF_LEN)
CARD len,size
Close(in)
Close(out)
Open(in,fname,4)
Open(out,tmp,8)
DO
IF maxlen>BUF_LEN THEN
size=BUF_LEN
ELSE
size=maxlen
FI
len=Bget(in,buff,size)
maxlen==-len
IF len>0 THEN
Bput(out,buff,len)
FI
UNTIL len#BUF_LEN
OD
Close(in)
Close(out)
MakeRenameCommand(tmp,fname,cmd)
DeleteFile(fname)
Rename(cmd)
RETURN
PROC Main()
CHAR ARRAY filter="D:*.*", fname="D:INPUT.TXT"
CARD len=[400]
Put(125) PutE() ;clear screen
PrintF("Dir ""%S""%E",filter)
Dir(filter)
PrintF("Truncate ""%S"" to %U bytes.%E%E",fname,len)
TruncateFile(fname,len)
PrintF("Dir ""%S""%E",filter)
Dir(filter)
RETURN |
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 size and renaming it, after first deleting the original file, if no other method is available. The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged.
If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition.
On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file.
This task permits the use of such facilities. However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
| #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.Command_Line.Argument_Count;
begin
-- give help output if neccessary
if Args < 2 or else Args > 3 then
raise Program_Error
with "usage: truncate_file <filename> <length> [<temp_file>]";
end if;
-- now do the real work
declare
File_Name: String := Arg(1);
Temp_Name: String := (if Args = 2 then Arg(1) & ".tmp" else Arg(3));
-- an Ada 2012 conditional expression
File, Temp: Byte_IO.File_Type;
Count: Natural := Natural'Value(Arg(2));
Value: Byte;
begin
-- open files
Byte_IO.Open (File => File, Mode => Byte_IO.In_File, Name => File_Name);
Byte_IO.Create(File => Temp, Mode => Byte_IO.Out_File, Name => Temp_Name);
-- copy the required bytes (but at most as much as File has) from File to Temp
while (not Byte_IO.End_Of_File(File)) and Count > 0 loop
Byte_IO.Read (File, Value);
Byte_IO.Write(Temp, Value);
Count := Count - 1;
end loop;
-- close files
Byte_IO.Close(Temp);
Byte_IO.Close(File);
if Count = 0 then -- File was at least Count bytes long
-- remove File and rename Temp to File
Ada.Directories.Delete_File(Name => File_Name);
Ada.Directories.Rename(Old_Name => Temp_Name, New_Name => File_Name);
else -- File was too short
-- remove Temp and leave File as it is, output error
Ada.Directories.Delete_File(Name => Temp_Name);
raise Program_Error
with "Size of """ & File_Name & """ less than " & Arg(2);
end if;
end;
end Truncate_File; |
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, starting at 1.
In an Ulam spiral of primes, only the primes are shown (usually indicated by some glyph such as a dot or asterisk), and all non-primes as shown as a blank (or some other whitespace).
Of course, the grid and border are not to be displayed (but they are displayed here when using these Wiki HTML tables).
Normally, the spiral starts in the "center", and the 2nd number is to the viewer's right and the number spiral starts from there in a counter-clockwise direction.
There are other geometric shapes that are used as well, including clock-wise spirals.
Also, some spirals (for the 2nd number) is viewed upwards from the 1st number instead of to the right, but that is just a matter of orientation.
Sometimes, the starting number can be specified to show more visual striking patterns (of prime densities).
[A larger than necessary grid (numbers wise) is shown here to illustrate the pattern of numbers on the diagonals (which may be used by the method to orientate the direction of spiral-construction algorithm within the example computer programs)].
Then, in the next phase in the transformation of the Ulam prime spiral, the non-primes are translated to blanks.
In the orange grid below, the primes are left intact, and all non-primes are changed to blanks.
Then, in the final transformation of the Ulam spiral (the yellow grid), translate the primes to a glyph such as a • or some other suitable glyph.
65
64
63
62
61
60
59
58
57
66
37
36
35
34
33
32
31
56
67
38
17
16
15
14
13
30
55
68
39
18
5
4
3
12
29
54
69
40
19
6
1
2
11
28
53
70
41
20
7
8
9
10
27
52
71
42
21
22
23
24
25
26
51
72
43
44
45
46
47
48
49
50
73
74
75
76
77
78
79
80
81
61
59
37
31
67
17
13
5
3
29
19
2
11
53
41
7
71
23
43
47
73
79
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
The Ulam spiral becomes more visually obvious as the grid increases in size.
Task
For any sized N × N grid, construct and show an Ulam spiral (counter-clockwise) of primes starting at some specified initial number (the default would be 1), with some suitably dotty (glyph) representation to indicate primes, and the absence of dots to indicate non-primes.
You should demonstrate the generator by showing at Ulam prime spiral large enough to (almost) fill your terminal screen.
Related tasks
Spiral matrix
Zig-zag matrix
Identity matrix
Sequence of primes by Trial Division
See also
Wikipedia entry: Ulam spiral
MathWorld™ entry: Prime Spiral
| #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, 0B] * (top I/ 2)
L(x) 3 .< 1 + Int(sqrt(top))
I !is_prime[x]
L.continue
L(i) (x * x .< top).step(x * 2)
is_prime[i] = 0B
(Int -> String) f = _ -> @symbol
I space == ‘’
space = ‘ ’ * symbol.len
I symbol.empty
V max_str = String(n * n + start - 1).len
I space == ‘’
space = (‘.’ * max_str)‘ ’
f = x -> String(x).rjust(@max_str)‘ ’
V cell_str = x -> I @is_prime[x] {@f(x)} E @space
L(y) 0 .< n
print((0 .< n).map(x -> cell(@n, x, @y, @start)).map(v -> @cell_str(v)).join(‘’))
print()
show_spiral(10, symbol' ‘# ’, space' ‘ ’)
show_spiral(9, symbol' ‘’, space' ‘ - ’) |
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 cylinder is rotated one chamber clockwise and the next chamber
checked until an empty chamber is found.
2. A cartridge containing a bullet is placed in the empty chamber.
3. The cylinder is then rotated one chamber clockwise.
To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take
a random position from 1 to 6 chamber rotations clockwise from its starting position.
When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just
counterclockwise from the loading position.
The gun is unloaded by removing all cartridges from the cylinder.
According to the legend, a suicidal Russian imperial military officer plays a game of Russian
roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice.
If the gun fires with a trigger pull, this is considered a successful suicide.
The cylinder is always spun before the first shot, but it may or may not be spun after putting
in the first bullet and may or may not be spun after taking the first shot.
Which of the following situations produces the highest probability of suicide?
A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot.
B. Spinning the cylinder after loading the first bullet only.
C. Spinning the cylinder after firing the first shot only.
D. Not spinning the cylinder either after loading the first bullet or after the first shot.
E. The probability is the same for all cases.
Task
Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios.
Show the results as a percentage of deaths for each type of scenario.
The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question.
Reference
Youtube video on the Russian 1895 Nagant revolver [[1]]
| #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[state, 1], shot}
]
ClearAll[LSLSFSF]
LSLSFSF[] := Module[{state, shot},
state = Unload[];
state = Load[state];
state = Spin[state];
state = Load[state];
state = Spin[state];
{state, shot} = Fire[state];
If[shot,
Return[True]
];
state = Spin[state];
{state, shot} = Fire[state];
If[shot,
Return[True]
];
Return[False]
]
ClearAll[LSLSFF]
LSLSFF[] := Module[{state, shot},
state = Unload[];
state = Load[state];
state = Spin[state];
state = Load[state];
state = Spin[state];
{state, shot} = Fire[state];
If[shot,
Return[True]
];
{state, shot} = Fire[state];
If[shot,
Return[True]
];
Return[False]
]
ClearAll[LLSFSF]
LLSFSF[] := Module[{state, shot},
state = Unload[];
state = Load[state];
state = Load[state];
state = Spin[state];
{state, shot} = Fire[state];
If[shot,
Return[True]
];
state = Spin[state];
{state, shot} = Fire[state];
If[shot,
Return[True]
];
Return[False]
]
ClearAll[LLSFF]
LLSFF[] := Module[{state, shot},
state = Unload[];
state = Load[state];
state = Load[state];
state = Spin[state];
{state, shot} = Fire[state];
If[shot,
Return[True]
];
{state, shot} = Fire[state];
If[shot,
Return[True]
];
Return[False]
]
n = 10^5;
Count[Table[LSLSFSF[], n], True]/N[n]
Count[Table[LSLSFF[], n], True]/N[n]
Count[Table[LLSFSF[], n], True]/N[n]
Count[Table[LLSFF[], n], True]/N[n] |
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 cylinder is rotated one chamber clockwise and the next chamber
checked until an empty chamber is found.
2. A cartridge containing a bullet is placed in the empty chamber.
3. The cylinder is then rotated one chamber clockwise.
To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take
a random position from 1 to 6 chamber rotations clockwise from its starting position.
When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just
counterclockwise from the loading position.
The gun is unloaded by removing all cartridges from the cylinder.
According to the legend, a suicidal Russian imperial military officer plays a game of Russian
roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice.
If the gun fires with a trigger pull, this is considered a successful suicide.
The cylinder is always spun before the first shot, but it may or may not be spun after putting
in the first bullet and may or may not be spun after taking the first shot.
Which of the following situations produces the highest probability of suicide?
A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot.
B. Spinning the cylinder after loading the first bullet only.
C. Spinning the cylinder after firing the first shot only.
D. Not spinning the cylinder either after loading the first bullet or after the first shot.
E. The probability is the same for all cases.
Task
Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios.
Show the results as a percentage of deaths for each type of scenario.
The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question.
Reference
Youtube video on the Russian 1895 Nagant revolver [[1]]
| #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 Revolver) =
while revolver[1]:
revolver.spin(1)
revolver[1] = true
revolver.spin(1)
func fire(revolver: var Revolver): bool =
result = revolver[0]
revolver.spin(1)
proc test(scenario: string) =
let actions = scenario.mapIt(Actions.getOrDefault(it, Error))
var deaths = 0
var count = 100_000
for _ in 1..count:
var revolver: Revolver
for action in actions:
case action
of Load:
revolver.load()
of Spin:
revolver.spin(rand(1..6))
of Fire:
if revolver.fire():
inc deaths
break
of Error:
raise newException(ValueError, "encountered an unknown action.")
echo &"""{100 * deaths / count:5.2f}% deaths for scenario {actions.join(", ")}."""
randomize()
for scenario in ["LSLSFSF", "LSLSFF", "LLSFSF", "LLSFF"]:
test(scenario) |
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 cylinder is rotated one chamber clockwise and the next chamber
checked until an empty chamber is found.
2. A cartridge containing a bullet is placed in the empty chamber.
3. The cylinder is then rotated one chamber clockwise.
To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take
a random position from 1 to 6 chamber rotations clockwise from its starting position.
When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just
counterclockwise from the loading position.
The gun is unloaded by removing all cartridges from the cylinder.
According to the legend, a suicidal Russian imperial military officer plays a game of Russian
roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice.
If the gun fires with a trigger pull, this is considered a successful suicide.
The cylinder is always spun before the first shot, but it may or may not be spun after putting
in the first bullet and may or may not be spun after taking the first shot.
Which of the following situations produces the highest probability of suicide?
A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot.
B. Spinning the cylinder after loading the first bullet only.
C. Spinning the cylinder after firing the first shot only.
D. Not spinning the cylinder either after loading the first bullet or after the first shot.
E. The probability is the same for all cases.
Task
Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios.
Show the results as a percentage of deaths for each type of scenario.
The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question.
Reference
Youtube video on the Russian 1895 Nagant revolver [[1]]
| #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;
load, spin, load, spin;
return 1 if fire;
spin;
fire
}
sub LSLSFF {
@cyl = (0) x $shots;
load, spin, load, spin;
fire or fire
}
sub LLSFSF {
@cyl = (0) x $shots;
load, load, spin;
return 1 if fire;
spin;
fire
}
sub LLSFF {
@cyl = (0) x $shots;
load, load, spin;
fire or fire
}
my $trials = 10000;
for my $ref (<LSLSFSF LSLSFF LLSFSF LLSFF>) {
no strict 'refs';
my $total = 0;
$total += &$ref for 1..$trials;
printf "%7s %.2f%%\n", $ref, $total / $trials * 100;
} |
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:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #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:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #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 represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
The dot product (a scalar quantity)
A • B = a1b1 + a2b2 + a3b3
The cross product (a vector quantity)
A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
The scalar triple product (a scalar quantity)
A • (B x C)
The vector triple product (a vector quantity)
A x (B x C)
Task
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
Create a named function/subroutine/method to compute the dot product of two vectors.
Create a function to compute the cross product of two vectors.
Optionally create a function to compute the scalar triple product of three vectors.
Optionally create a function to compute the vector triple product of three vectors.
Compute and display: a • b
Compute and display: a x b
Compute and display: a • (b x c), the scalar triple product.
Compute and display: a x (b x c), the vector triple product.
References
A starting page on Wolfram MathWorld is Vector Multiplication .
Wikipedia dot product.
Wikipedia cross product.
Wikipedia triple product.
Related tasks
Dot product
Quaternion type
| #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) {
return(sprod(u, vprod(v, w)))
}
real colvector vtriple(real colvector u, real colvector v, real colvector w) {
return(vprod(u, vprod(v, w)))
}
a = 3\4\5
b = 4\3\5
c = -5\-12\-13
sprod(a, b)
49
vprod(a, b)
1
+------+
1 | 5 |
2 | 5 |
3 | -7 |
+------+
striple(a, b, c)
6
vtriple(a, b, c)
1
+--------+
1 | -267 |
2 | 204 |
3 | -3 |
+--------+
end |
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.'
else say y "isn't defined."
/*check if the fire god is defined. */
y= 'xiuhtecuhtli' /*assign a value to the Aztec file god.*/
if symbol(y)=="VAR" then say y ' is defined.'
else say y "isn't defined."
drop tlaloc /*un─define the TLALOC REXX variable.*/
/*check if the rain god is defined. */
y= 'tlaloc'
if symbol(y)=="VAR" then say y ' is defined.'
else say y "isn't defined."
/*stick a fork in it, we're all done. */ |
|
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 Unicode?
Task
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
How easy is it to present Unicode strings in source code?
Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
How well can the language communicate with the rest of the world?
Is it good at input/output with Unicode?
Is it convenient to manipulate Unicode strings in the language?
How broad/deep does the language support Unicode?
What encodings (e.g. UTF-8, UTF-16, etc) can be used?
Does it support normalization?
Note
This task is a bit unusual in that it encourages general discussion rather than clever coding.
See also
Unicode variable names
Terminal control/Display an extended character
| #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 Unicode?
Task
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
How easy is it to present Unicode strings in source code?
Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
How well can the language communicate with the rest of the world?
Is it good at input/output with Unicode?
Is it convenient to manipulate Unicode strings in the language?
How broad/deep does the language support Unicode?
What encodings (e.g. UTF-8, UTF-16, etc) can be used?
Does it support normalization?
Note
This task is a bit unusual in that it encourages general discussion rather than clever coding.
See also
Unicode variable names
Terminal control/Display an extended character
| #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 number).
Extension
Find all twin prime pairs under 100000, 10000000 and 1000000000.
What is the time complexity of the program? Are there ways to reduce computation time?
Examples
> Search Size: 100
> 8 twin prime pairs.
> Search Size: 1000
> 35 twin prime pairs.
Also see
The OEIS entry: A001097: Twin primes.
The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.
The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.
The OEIS entry: A007508: Number of twin prime pairs below 10^n.
| #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 10000000: %d" (primes64()|>Seq.takeWhile(fun n->n<=10000000L)|>Seq.pairwise|>Seq.filter(fun(n,g)->g=n+2L)|>Seq.length)
printfn "twin primes below 100000000: %d" (primes64()|>Seq.takeWhile(fun n->n<=100000000L)|>Seq.pairwise|>Seq.filter(fun(n,g)->g=n+2L)|>Seq.length)
printfn "twin primes below 1000000000: %d" (primes64()|>Seq.takeWhile(fun n->n<=1000000000L)|>Seq.pairwise|>Seq.filter(fun(n,g)->g=n+2L)|>Seq.length)
printfn "twin primes below 10000000000: %d" (primes64()|>Seq.takeWhile(fun n->n<=10000000000L)|>Seq.pairwise|>Seq.filter(fun(n,g)->g=n+2L)|>Seq.length)
printfn "twin primes below 100000000000: %d" (primes64()|>Seq.takeWhile(fun n->n<=100000000000L)|>Seq.pairwise|>Seq.filter(fun(n,g)->g=n+2L)|>Seq.length)
|
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 (referenced from Adam Spencer's book) ─────:
(arithmetic) that cannot be turned into a prime number by changing just one of its digits to any other
digit. (sic)
Unprimeable numbers are also spelled: unprimable.
All one─ and two─digit numbers can be turned into primes by changing a single decimal digit.
Examples
190 isn't unprimeable, because by changing the zero digit into a three yields 193, which is a prime.
The number 200 is unprimeable, since none of the numbers 201, 202, 203, ··· 209 are
prime, and all the other numbers obtained by changing a single digit to
produce 100, 300, 400, ··· 900, or 210, 220, 230, ··· 290 which are all even.
It is valid to change 189 into 089 by changing the 1 (one) into
a 0 (zero), which then the leading zero can be removed, and then treated as if
the "new" number is 89.
Task
show the first 35 unprimeable numbers (horizontally, on one line, preferably with a title)
show the 600th unprimeable number
(optional) show the lowest unprimeable number ending in a specific decimal digit (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
(optional) use commas in the numbers where appropriate
Show all output here, on this page.
Also see
the OEIS entry: A118118 (unprimeable)
with some useful counts to compare unprimeable number
the Wiktionary entry (reference from below): (arithmetic definition) unprimeable
from the Adam Spencer book (page 200): Adam Spencer's World of Numbers (Xoum Publishing)
| #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 = {}, 10000000
for i = 2,S do sieve[i]=true end
for i = 2,S do if sieve[i] then for j=i*i,S,i do sieve[j]=nil end end end
-- UNPRIMABLE:
local unprimables, lowests = T{}, T{}
local floor, log10 = math.floor, math.log10
local function unprimable(n)
if sieve[n] then return false end
local nd = floor(log10(n))+1
for i = 1, nd do
local pow10 = 10^(nd-i)
for j = 0, 9 do
local p = (floor(n/10/pow10) * 10 + j) * pow10 + (n % pow10)
if sieve[p] then return false end
end
end
return true
end
local n, done = 1, 0
while done < 10 do
if unprimable(n) then
unprimables:insert(n)
if not lowests[n%10] then
lowests[n%10] = n
done = done + 1
end
end
n = n + 1
end
-- OUTPUT:
local function commafy(i) return tostring(i):reverse():gsub("(%d%d%d)","%1,"):reverse():gsub("^,","") end
print("The first 35 unprimable numbers are:")
print(unprimables:firstn(35):concat(" "))
print()
print("The 600th unprimable number is: " .. commafy(unprimables[600]))
print()
print("The lowest unprimable number that ends in..")
for i = 0, 9 do
print(" " .. i .. " is: " .. commafy(lowests[i]))
end |
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 identifiers
| #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 identifiers
| #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 identifiers
| #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 identifiers
| #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/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
For N over its range, generate and show counts of the outputs of randN and unbiased(randN).
The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.
This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
| #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/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
For N over its range, generate and show counts of the outputs of randN and unbiased(randN).
The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.
This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
| #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 main(String[] args) {
final int M = 50000;
for (int n = 3; n < 7; n++) {
int c1 = 0, c2 = 0;
for (int i = 0; i < M; i++) {
c1 += biased(n) ? 1 : 0;
c2 += unbiased(n) ? 1 : 0;
}
System.out.format("%d: %2.2f%% %2.2f%%\n",
n, 100.0*c1/M, 100.0*c2/M);
}
}
} |
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 size and renaming it, after first deleting the original file, if no other method is available. The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged.
If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition.
On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file.
This task permits the use of such facilities. However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
| #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 := length_bytes
f.close()
} |
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 size and renaming it, after first deleting the original file, if no other method is available. The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged.
If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition.
On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file.
This task permits the use of such facilities. However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
| #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_file(filename,size, cmd,fnr,msg,old_BINMODE,old_RS,rec) {
cmd = sprintf("ls --full-time -o %s",filename)
if (size < 0) {
return("size cannot be negative")
}
old_BINMODE = BINMODE
old_RS = RS
BINMODE = 3
RS = "[^\x00-\xFF]"
while (getline rec <filename > 0) {
fnr++
}
close(filename)
if (fnr == 0) {
msg = "file not found"
}
if (fnr > 1) {
msg = "choose a different RecordSeparator"
}
if (msg == "") { # no errors
system(cmd) # optional: show filesize before truncation
if (length(rec) > size) {
rec = substr(rec,1,size)
}
printf("%s",rec) >filename
close(filename)
system(cmd) # optional: show filesize after truncation
}
BINMODE = old_BINMODE
RS = old_RS
return(msg)
}
|
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, starting at 1.
In an Ulam spiral of primes, only the primes are shown (usually indicated by some glyph such as a dot or asterisk), and all non-primes as shown as a blank (or some other whitespace).
Of course, the grid and border are not to be displayed (but they are displayed here when using these Wiki HTML tables).
Normally, the spiral starts in the "center", and the 2nd number is to the viewer's right and the number spiral starts from there in a counter-clockwise direction.
There are other geometric shapes that are used as well, including clock-wise spirals.
Also, some spirals (for the 2nd number) is viewed upwards from the 1st number instead of to the right, but that is just a matter of orientation.
Sometimes, the starting number can be specified to show more visual striking patterns (of prime densities).
[A larger than necessary grid (numbers wise) is shown here to illustrate the pattern of numbers on the diagonals (which may be used by the method to orientate the direction of spiral-construction algorithm within the example computer programs)].
Then, in the next phase in the transformation of the Ulam prime spiral, the non-primes are translated to blanks.
In the orange grid below, the primes are left intact, and all non-primes are changed to blanks.
Then, in the final transformation of the Ulam spiral (the yellow grid), translate the primes to a glyph such as a • or some other suitable glyph.
65
64
63
62
61
60
59
58
57
66
37
36
35
34
33
32
31
56
67
38
17
16
15
14
13
30
55
68
39
18
5
4
3
12
29
54
69
40
19
6
1
2
11
28
53
70
41
20
7
8
9
10
27
52
71
42
21
22
23
24
25
26
51
72
43
44
45
46
47
48
49
50
73
74
75
76
77
78
79
80
81
61
59
37
31
67
17
13
5
3
29
19
2
11
53
41
7
71
23
43
47
73
79
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
The Ulam spiral becomes more visually obvious as the grid increases in size.
Task
For any sized N × N grid, construct and show an Ulam spiral (counter-clockwise) of primes starting at some specified initial number (the default would be 1), with some suitably dotty (glyph) representation to indicate primes, and the absence of dots to indicate non-primes.
You should demonstrate the generator by showing at Ulam prime spiral large enough to (almost) fill your terminal screen.
Related tasks
Spiral matrix
Zig-zag matrix
Identity matrix
Sequence of primes by Trial Division
See also
Wikipedia entry: Ulam spiral
MathWorld™ entry: Prime Spiral
| #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,8(R13) linkage in previous SA
LR R13,R15 establish addressability
LA R5,1 n=1
LH R8,NSIZE x=nsize
SRA R8,1
LA R8,1(R8) x=nsize/2+1
LR R9,R8 y=x
LR R1,R5 n
BAL R14,ISPRIME
C R0,=F'1' if isprime(n)
BNE NPRMJ0
BAL R14,SPIRALO spiral(x,y)=o
NPRMJ0 LA R5,1(R5) n=n+1
LA R6,1 i=1
LOOPI1 LH R2,NSIZE do i=1 to nsize-1 by 2
BCTR R2,0
CR R6,R2 if i>nsize-1
BH ELOOPI1
LR R7,R6 j=i; do j=1 to i
LOOPJ1 LA R8,1(R8) x=x+1
LR R1,R5 n
BAL R14,ISPRIME
C R0,=F'1' if isprime(n)
BNE NPRMJ1
BAL R14,SPIRALO spiral(x,y)=o
NPRMJ1 LA R5,1(R5) n=n+1
BCT R7,LOOPJ1 next j
ELOOPJ1 LR R7,R6 j=i; do j=1 to i
LOOPJ2 BCTR R9,0 y=y-1
LR R1,R5 n
BAL R14,ISPRIME
C R0,=F'1' if isprime(n)
BNE NPRMJ2
BAL R14,SPIRALO spiral(x,y)=o
NPRMJ2 LA R5,1(R5) n=n+1
BCT R7,LOOPJ2 next j
ELOOPJ2 LR R7,R6 j=i
LA R7,1(R7) j=i+1; do j=1 to i+1
LOOPJ3 BCTR R8,0 x=x-1
LR R1,R5 n
BAL R14,ISPRIME
C R0,=F'1' if isprime(n)
BNE NPRMJ3
BAL R14,SPIRALO spiral(x,y)=o
NPRMJ3 LA R5,1(R5) n=n+1
BCT R7,LOOPJ3 next j
ELOOPJ3 LR R7,R6 j=i
LA R7,1(R7) j=i+1; do j=1 to i+1
LOOPJ4 LA R9,1(R9) y=y+1
LR R1,R5 n
BAL R14,ISPRIME
C R0,=F'1' if isprime(n)
BNE NPRMJ4
BAL R14,SPIRALO spiral(x,y)=o
NPRMJ4 LA R5,1(R5) n=n+1
BCT R7,LOOPJ4 next j
ELOOPJ4 LA R6,2(R6) i=i+2
B LOOPI1
ELOOPI1 LH R7,NSIZE j=nsize
BCTR R7,0 j=nsize-1; do j=1 to nsize-1
LOOPJ5 LA R8,1(R8) x=x+1
LR R1,R5 n
BAL R14,ISPRIME
C R0,=F'1' if isprime(n)
BNE NPRMJ5
BAL R14,SPIRALO spiral(x,y)=o
NPRMJ5 LA R5,1(R5) n=n+1
BCT R7,LOOPJ5 next j
ELOOPJ5 LA R6,1 i=1
LOOPI2 CH R6,NSIZE do i=1 to nsize
BH ELOOPI2
LA R10,PG reset buffer
LA R7,1 j=1
LOOPJ6 CH R7,NSIZE do j=1 to nsize
BH ELOOPJ6
LR R1,R7 j
BCTR R1,0 (j-1)
MH R1,NSIZE (j-1)*nsize
AR R1,R6 r1=(j-1)*nsize+i
LA R14,SPIRAL-1(R1) @spiral(j,i)
MVC 0(1,R10),0(R14) output spiral(j,i)
LA R10,1(R10) pgi=pgi+1
LA R7,1(R7) j=j+1
B LOOPJ6
ELOOPJ6 XPRNT PG,80 print
LA R6,1(R6) i=i+1
B LOOPI2
ELOOPI2 L R13,4(0,R13) reset previous SA
LM R14,R12,12(R13) restore previous env
XR R15,R15 set return code
BR R14 call back
ISPRIME CNOP 0,4 ---------- isprime function
C R1,=F'2' if nn=2
BNE NOT2
LA R0,1 rr=1
B ELOOPII
NOT2 C R1,=F'2' if nn<2
BL RRZERO
LR R2,R1 nn
LA R4,2 2
SRDA R2,32 shift
DR R2,R4 nn/2
C R2,=F'0' if nn//2=0
BNE TAGII
RRZERO SR R0,R0 rr=0
B ELOOPII
TAGII LA R0,1 rr=1
LA R4,3 ii=3
LOOPII LR R3,R4 ii
MR R2,R4 ii*ii
CR R3,R1 if ii*ii<=nn
BH ELOOPII
LR R3,R1 nn
LA R2,0 clear
DR R2,R4 nn/ii
LTR R2,R2 if nn//ii=0
BNZ NEXTII
SR R0,R0 rr=0
B ELOOPII
NEXTII LA R4,2(R4) ii=ii+2
B LOOPII
ELOOPII BR R14 ---------- end isprime return rr
SPIRALO CNOP 0,4 ---------- spiralo subroutine
LR R1,R8 x
BCTR R1,0 x-1
MH R1,NSIZE (x-1)*nsize
AR R1,R9 r1=(x-1)*nsize+y
LA R10,SPIRAL-1(R1) r10=@spiral(x,y)
MVC 0(1,R10),O spiral(x,y)=o
BR R14 ---------- end spiralo
NS EQU 79 4n+1
NSIZE DC AL2(NS) =H'ns'
O DC CL1'*' if prime
PG DC CL80' ' buffer
LTORG
SPIRAL DC (NS*NS)CL1' '
YREGS
END ULAM |
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 cylinder is rotated one chamber clockwise and the next chamber
checked until an empty chamber is found.
2. A cartridge containing a bullet is placed in the empty chamber.
3. The cylinder is then rotated one chamber clockwise.
To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take
a random position from 1 to 6 chamber rotations clockwise from its starting position.
When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just
counterclockwise from the loading position.
The gun is unloaded by removing all cartridges from the cylinder.
According to the legend, a suicidal Russian imperial military officer plays a game of Russian
roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice.
If the gun fires with a trigger pull, this is considered a successful suicide.
The cylinder is always spun before the first shot, but it may or may not be spun after putting
in the first bullet and may or may not be spun after taking the first shot.
Which of the following situations produces the highest probability of suicide?
A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot.
B. Spinning the cylinder after loading the first bullet only.
C. Spinning the cylinder after firing the first shot only.
D. Not spinning the cylinder either after loading the first bullet or after the first shot.
E. The probability is the same for all cases.
Task
Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios.
Show the results as a percentage of deaths for each type of scenario.
The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question.
Reference
Youtube video on the Russian 1895 Nagant revolver [[1]]
| #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
revolver[1] = true
revolver = spin(revolver,1)
return revolver
end function
function fire(sequence revolver, bool dead)
if revolver[1] then dead = true end if
revolver = spin(revolver,1)
return {revolver,dead}
end function
procedure test(sequence me)
{string method, atom expected} = me
integer deaths = 0,
limit = 100_000
for n=1 to limit do
sequence revolver = repeat(false,6)
bool dead = false
for i=1 to length(method) do
integer ch = method[i]
switch ch
case 'L': revolver = load(revolver)
case 'S': revolver = spin(revolver,rand(6))
case 'F': {revolver,dead} = fire(revolver,dead)
end switch
end for
deaths += dead
end for
printf(1,"%s: %5.2f (expected %.2f%%)\n",{method,100*deaths/limit,expected*100})
end procedure
printf(1,"Load/Spin/Fire method percentage fatalities:\n")
papply({{"LSLSFSF",5/9},{"LSLSFF",7/12},{"LLSFSF",5/9},{"LLSFF",1/2}},test)
|
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:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #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:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #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:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #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 represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
The dot product (a scalar quantity)
A • B = a1b1 + a2b2 + a3b3
The cross product (a vector quantity)
A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
The scalar triple product (a scalar quantity)
A • (B x C)
The vector triple product (a vector quantity)
A x (B x C)
Task
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
Create a named function/subroutine/method to compute the dot product of two vectors.
Create a function to compute the cross product of two vectors.
Optionally create a function to compute the scalar triple product of three vectors.
Optionally create a function to compute the vector triple product of three vectors.
Compute and display: a • b
Compute and display: a x b
Compute and display: a • (b x c), the scalar triple product.
Compute and display: a x (b x c), the vector triple product.
References
A starting page on Wolfram MathWorld is Vector Multiplication .
Wikipedia dot product.
Wikipedia cross product.
Wikipedia triple product.
Related tasks
Dot product
Quaternion type
| #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 • (lhs: Vector, rhs: Vector) -> Double {
return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z
}
public static func × (lhs: Vector, rhs: Vector) -> Vector {
return Vector(
x: lhs.y * rhs.z - lhs.z * rhs.y,
y: lhs.z * rhs.x - lhs.x * rhs.z,
z: lhs.x * rhs.y - lhs.y * rhs.x
)
}
}
let a = Vector(x: 3, y: 4, z: 5)
let b = Vector(x: 4, y: 3, z: 5)
let c = Vector(x: -5, y: -12, z: -13)
print("a: \(a)")
print("b: \(b)")
print("c: \(c)")
print()
print("a • b = \(a • b)")
print("a × b = \(a × b)")
print("a • (b × c) = \(a • (b × c))")
print("a × (b × c) = \(a × (b × c))") |
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 variable in Ruby
# Because most of the output is conditional, this serves as
# a clear indicator that the program has run to completion.
puts "Done" |
|
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 Unicode?
Task
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
How easy is it to present Unicode strings in source code?
Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
How well can the language communicate with the rest of the world?
Is it good at input/output with Unicode?
Is it convenient to manipulate Unicode strings in the language?
How broad/deep does the language support Unicode?
What encodings (e.g. UTF-8, UTF-16, etc) can be used?
Does it support normalization?
Note
This task is a bit unusual in that it encourages general discussion rather than clever coding.
See also
Unicode variable names
Terminal control/Display an extended character
| #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) ; -> 16
;; and in fact the standard language makes use of some of these
(λ(x) x) ; -> an identity function
|
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 Unicode?
Task
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
How easy is it to present Unicode strings in source code?
Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
How well can the language communicate with the rest of the world?
Is it good at input/output with Unicode?
Is it convenient to manipulate Unicode strings in the language?
How broad/deep does the language support Unicode?
What encodings (e.g. UTF-8, UTF-16, etc) can be used?
Does it support normalization?
Note
This task is a bit unusual in that it encourages general discussion rather than clever coding.
See also
Unicode variable names
Terminal control/Display an extended character
| #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 Unicode?
Task
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
How easy is it to present Unicode strings in source code?
Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
How well can the language communicate with the rest of the world?
Is it good at input/output with Unicode?
Is it convenient to manipulate Unicode strings in the language?
How broad/deep does the language support Unicode?
What encodings (e.g. UTF-8, UTF-16, etc) can be used?
Does it support normalization?
Note
This task is a bit unusual in that it encourages general discussion rather than clever coding.
See also
Unicode variable names
Terminal control/Display an extended character
| #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 = "नमस्ते दुनिया!"
ok
ring_see("Converted To (Hindi): " + cText + nl)
|
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 number).
Extension
Find all twin prime pairs under 100000, 10000000 and 1000000000.
What is the time complexity of the program? Are there ways to reduce computation time?
Examples
> Search Size: 100
> 8 twin prime pairs.
> Search Size: 1000
> 35 twin prime pairs.
Also see
The OEIS entry: A001097: Twin primes.
The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.
The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.
The OEIS entry: A007508: Number of twin prime pairs below 10^n.
| #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 prime pairs." print |
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 number).
Extension
Find all twin prime pairs under 100000, 10000000 and 1000000000.
What is the time complexity of the program? Are there ways to reduce computation time?
Examples
> Search Size: 100
> 8 twin prime pairs.
> Search Size: 1000
> 35 twin prime pairs.
Also see
The OEIS entry: A001097: Twin primes.
The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.
The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.
The OEIS entry: A007508: Number of twin prime pairs below 10^n.
| #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, p2 = 1, p3 = 1, count = 0
For i As Uinteger = 5 To limite
p3 = p2
p2 = p1
p1 = isPrime(i)
If (p3 And p1) Then count += 1
Next i
Return count
End Function
Dim As Uinteger n = 1
For i As Byte = 1 To 6
n *= 10
Print Using "pares de primos gemelos por debajo de < ####### : ####"; n; paresDePrimos(n)
Next i
Print !"\n--- terminado, pulsa RETURN---"
Sleep
|
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 (referenced from Adam Spencer's book) ─────:
(arithmetic) that cannot be turned into a prime number by changing just one of its digits to any other
digit. (sic)
Unprimeable numbers are also spelled: unprimable.
All one─ and two─digit numbers can be turned into primes by changing a single decimal digit.
Examples
190 isn't unprimeable, because by changing the zero digit into a three yields 193, which is a prime.
The number 200 is unprimeable, since none of the numbers 201, 202, 203, ··· 209 are
prime, and all the other numbers obtained by changing a single digit to
produce 100, 300, 400, ··· 900, or 210, 220, 230, ··· 290 which are all even.
It is valid to change 189 into 089 by changing the 1 (one) into
a 0 (zero), which then the leading zero can be removed, and then treated as if
the "new" number is 89.
Task
show the first 35 unprimeable numbers (horizontally, on one line, preferably with a title)
show the 600th unprimeable number
(optional) show the lowest unprimeable number ending in a specific decimal digit (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
(optional) use commas in the numbers where appropriate
Show all output here, on this page.
Also see
the OEIS entry: A118118 (unprimeable)
with some useful counts to compare unprimeable number
the Wiktionary entry (reference from below): (arithmetic definition) unprimeable
from the Adam Spencer book (page 200): Adam Spencer's World of Numbers (Xoum Publishing)
| #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 = {};
PrintTemporary[Dynamic[{Length[res], i}]];
i = 0;
While[Length[res] < 600,
If[Unprimeable[i],
AppendTo[res, i]
];
i++
];
PrintTemporary[Dynamic[{lastdig, i}]];
out = Table[
i = lastdig;
While[! Unprimeable[i],
i += 10
];
i
,
{lastdig, 0, 9}
];
res[[;; 35]]
res[[600]]
lastdigit = IntegerDigits /* Last;
Print["Least unprimeable number ending in ", lastdigit[#], ": ", #] & /@ SortBy[out, lastdigit]; |
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 identifiers
| #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 identifiers
| #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 identifiers
| #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 identifiers
| #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/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
For N over its range, generate and show counts of the outputs of randN and unbiased(randN).
The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.
This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
| #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
biased = randN(N)
v = collect(biased() for __ in 1:nrep)
v1, v0 = count(v .== 1), count(v .== 0)
@printf("%2i | %10s | %5i | %5i | %5.2f%%\n", N, "biased", v1, v0, 100 * v1 / nrep)
v = collect(unbiased(biased) for __ in 1:nrep)
v1, v0 = count(v .== 1), count(v .== 0)
@printf("%2i | %10s | %5i | %5i | %5.2f%%\n", N, "unbiased", v1, v0, 100 * v1 / nrep)
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/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
For N over its range, generate and show counts of the outputs of randN and unbiased(randN).
The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.
This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
| #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%%"
for (n in 3..6) {
var c1 = 0
var c2 = 0
for (i in 0 until m) {
if (biased(n)) c1++
if (unbiased(n)) c2++
}
println(f.format(n, 100.0 * c1 / m, 100.0 * c2 / m))
}
} |
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 size and renaming it, after first deleting the original file, if no other method is available. The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged.
If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition.
On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file.
This task permits the use of such facilities. However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
| #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)
GET #f, 1, c
CLOSE f
OPEN file FOR OUTPUT AS f
PRINT #f, c;
CLOSE f
END IF
ELSE
ERROR 53
END IF
END SUB |
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 size and renaming it, after first deleting the original file, if no other method is available. The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged.
If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition.
On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file.
This task permits the use of such facilities. However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
| #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, starting at 1.
In an Ulam spiral of primes, only the primes are shown (usually indicated by some glyph such as a dot or asterisk), and all non-primes as shown as a blank (or some other whitespace).
Of course, the grid and border are not to be displayed (but they are displayed here when using these Wiki HTML tables).
Normally, the spiral starts in the "center", and the 2nd number is to the viewer's right and the number spiral starts from there in a counter-clockwise direction.
There are other geometric shapes that are used as well, including clock-wise spirals.
Also, some spirals (for the 2nd number) is viewed upwards from the 1st number instead of to the right, but that is just a matter of orientation.
Sometimes, the starting number can be specified to show more visual striking patterns (of prime densities).
[A larger than necessary grid (numbers wise) is shown here to illustrate the pattern of numbers on the diagonals (which may be used by the method to orientate the direction of spiral-construction algorithm within the example computer programs)].
Then, in the next phase in the transformation of the Ulam prime spiral, the non-primes are translated to blanks.
In the orange grid below, the primes are left intact, and all non-primes are changed to blanks.
Then, in the final transformation of the Ulam spiral (the yellow grid), translate the primes to a glyph such as a • or some other suitable glyph.
65
64
63
62
61
60
59
58
57
66
37
36
35
34
33
32
31
56
67
38
17
16
15
14
13
30
55
68
39
18
5
4
3
12
29
54
69
40
19
6
1
2
11
28
53
70
41
20
7
8
9
10
27
52
71
42
21
22
23
24
25
26
51
72
43
44
45
46
47
48
49
50
73
74
75
76
77
78
79
80
81
61
59
37
31
67
17
13
5
3
29
19
2
11
53
41
7
71
23
43
47
73
79
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
The Ulam spiral becomes more visually obvious as the grid increases in size.
Task
For any sized N × N grid, construct and show an Ulam spiral (counter-clockwise) of primes starting at some specified initial number (the default would be 1), with some suitably dotty (glyph) representation to indicate primes, and the absence of dots to indicate non-primes.
You should demonstrate the generator by showing at Ulam prime spiral large enough to (almost) fill your terminal screen.
Related tasks
Spiral matrix
Zig-zag matrix
Identity matrix
Sequence of primes by Trial Division
See also
Wikipedia entry: Ulam spiral
MathWorld™ entry: Prime Spiral
| #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
with procedure Put_String(S: String);
-- outputs a string, no new line
with procedure New_Line;
-- the name says all
package Generic_Ulam is
procedure Print_Spiral;
-- calls Put_String(Represent(I)) N^2 times
-- and New_Line N times
end Generic_Ulam; |
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 cylinder is rotated one chamber clockwise and the next chamber
checked until an empty chamber is found.
2. A cartridge containing a bullet is placed in the empty chamber.
3. The cylinder is then rotated one chamber clockwise.
To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take
a random position from 1 to 6 chamber rotations clockwise from its starting position.
When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just
counterclockwise from the loading position.
The gun is unloaded by removing all cartridges from the cylinder.
According to the legend, a suicidal Russian imperial military officer plays a game of Russian
roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice.
If the gun fires with a trigger pull, this is considered a successful suicide.
The cylinder is always spun before the first shot, but it may or may not be spun after putting
in the first bullet and may or may not be spun after taking the first shot.
Which of the following situations produces the highest probability of suicide?
A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot.
B. Spinning the cylinder after loading the first bullet only.
C. Spinning the cylinder after firing the first shot only.
D. Not spinning the cylinder either after loading the first bullet or after the first shot.
E. The probability is the same for all cases.
Task
Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios.
Show the results as a percentage of deaths for each type of scenario.
The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question.
Reference
Youtube video on the Russian 1895 Nagant revolver [[1]]
| #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[:] = False
def load(self):
""" load a chamber (advance til empty if full already), then advance once """
while self.cylinder[1]:
self.cylinder[:] = np.roll(self.cylinder, 1)
self.cylinder[1] = True
def spin(self):
""" spin cylinder, randomizing position of chamber to be fired """
self.cylinder[:] = np.roll(self.cylinder, np.random.randint(1, high=7))
def fire(self):
""" pull trigger of revolver, return True if fired, False if did not fire """
shot = self.cylinder[0]
self.cylinder[:] = np.roll(self.cylinder, 1)
return shot
def LSLSFSF(self):
""" load, spin, load, spin, fire, spin, fire """
self.unload()
self.load()
self.spin()
self.load()
self.spin()
if self.fire():
return True
self.spin()
if self.fire():
return True
return False
def LSLSFF(self):
""" load, spin, load, spin, fire, fire """
self.unload()
self.load()
self.spin()
self.load()
self.spin()
if self.fire():
return True
if self.fire():
return True
return False
def LLSFSF(self):
""" load, load, spin, fire, spin, fire """
self.unload()
self.load()
self.load()
self.spin()
if self.fire():
return True
self.spin()
if self.fire():
return True
return False
def LLSFF(self):
""" load, load, spin, fire, fire """
self.unload()
self.load()
self.load()
self.spin()
if self.fire():
return True
if self.fire():
return True
return False
if __name__ == '__main__':
REV = Revolver()
TESTCOUNT = 100000
for (name, method) in [['load, spin, load, spin, fire, spin, fire', REV.LSLSFSF],
['load, spin, load, spin, fire, fire', REV.LSLSFF],
['load, load, spin, fire, spin, fire', REV.LLSFSF],
['load, load, spin, fire, fire', REV.LLSFF]]:
percentage = 100 * sum([method() for _ in range(TESTCOUNT)]) / TESTCOUNT
print("Method", name, "produces", percentage, "per cent deaths.")
|
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:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #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:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #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
EndIf
Input()
EndIf |
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 represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
The dot product (a scalar quantity)
A • B = a1b1 + a2b2 + a3b3
The cross product (a vector quantity)
A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
The scalar triple product (a scalar quantity)
A • (B x C)
The vector triple product (a vector quantity)
A x (B x C)
Task
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
Create a named function/subroutine/method to compute the dot product of two vectors.
Create a function to compute the cross product of two vectors.
Optionally create a function to compute the scalar triple product of three vectors.
Optionally create a function to compute the vector triple product of three vectors.
Compute and display: a • b
Compute and display: a x b
Compute and display: a • (b x c), the scalar triple product.
Compute and display: a x (b x c), the vector triple product.
References
A starting page on Wolfram MathWorld is Vector Multiplication .
Wikipedia dot product.
Wikipedia cross product.
Wikipedia triple product.
Related tasks
Dot product
Quaternion type
| #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 $B $C]
}
proc vectorTriple {A B C} {
cross $A [cross $B $C]
} |
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 Unicode?
Task
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
How easy is it to present Unicode strings in source code?
Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
How well can the language communicate with the rest of the world?
Is it good at input/output with Unicode?
Is it convenient to manipulate Unicode strings in the language?
How broad/deep does the language support Unicode?
What encodings (e.g. UTF-8, UTF-16, etc) can be used?
Does it support normalization?
Note
This task is a bit unusual in that it encourages general discussion rather than clever coding.
See also
Unicode variable names
Terminal control/Display an extended character
| #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 = "नमस्ते दुनिया!"
ok
ring_see("Converted To (Hindi): " + cText + nl)
|
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 Unicode?
Task
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
How easy is it to present Unicode strings in source code?
Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
How well can the language communicate with the rest of the world?
Is it good at input/output with Unicode?
Is it convenient to manipulate Unicode strings in the language?
How broad/deep does the language support Unicode?
What encodings (e.g. UTF-8, UTF-16, etc) can be used?
Does it support normalization?
Note
This task is a bit unusual in that it encourages general discussion rather than clever coding.
See also
Unicode variable names
Terminal control/Display an extended character
| #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 Unicode?
Task
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
How easy is it to present Unicode strings in source code?
Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
How well can the language communicate with the rest of the world?
Is it good at input/output with Unicode?
Is it convenient to manipulate Unicode strings in the language?
How broad/deep does the language support Unicode?
What encodings (e.g. UTF-8, UTF-16, etc) can be used?
Does it support normalization?
Note
This task is a bit unusual in that it encourages general discussion rather than clever coding.
See also
Unicode variable names
Terminal control/Display an extended character
| #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 _ => Some(c.toInt)
}
if (s.length > 1) charToInt0(s(0), s(1)) else Some(s.toInt)
}
def intToChars(n: Int) = java.lang.Character.toChars(n).mkString
println('\uD869'.isHighSurrogate + " " + '\uDEA5'.isLowSurrogate)
println(charToInt("\uD869\uDEA5"))
val b = "\uD869\uDEA5"
println(b)
val c = "\uD834\uDD1E"
println(c)
val a = "$abcde¢£¤¥©ÇßçIJijŁłʒλπ•₠₡₢₣₤₥₦₧₨₩₪₫€₭₮₯₰₱₲₳₴₵₵←→⇒∙⌘☺☻ア字文𪚥".
map(c => "%s\t\\u%04X".format(c, c.toInt)).foreach(println)
} |
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 number).
Extension
Find all twin prime pairs under 100000, 10000000 and 1000000000.
What is the time complexity of the program? Are there ways to reduce computation time?
Examples
> Search Size: 100
> 8 twin prime pairs.
> Search Size: 1000
> 35 twin prime pairs.
Also see
The OEIS entry: A001097: Twin primes.
The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.
The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.
The OEIS entry: A007508: Number of twin prime pairs below 10^n.
| #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 {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
c := sieve(1e10 - 1)
limit := 10
start := 3
twins := 0
for i := 1; i < 11; i++ {
for i := start; i < limit; i += 2 {
if !c[i] && !c[i-2] {
twins++
}
}
fmt.Printf("Under %14s there are %10s pairs of twin primes.\n", commatize(limit), commatize(twins))
start = limit + 1
limit *= 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 (referenced from Adam Spencer's book) ─────:
(arithmetic) that cannot be turned into a prime number by changing just one of its digits to any other
digit. (sic)
Unprimeable numbers are also spelled: unprimable.
All one─ and two─digit numbers can be turned into primes by changing a single decimal digit.
Examples
190 isn't unprimeable, because by changing the zero digit into a three yields 193, which is a prime.
The number 200 is unprimeable, since none of the numbers 201, 202, 203, ··· 209 are
prime, and all the other numbers obtained by changing a single digit to
produce 100, 300, 400, ··· 900, or 210, 220, 230, ··· 290 which are all even.
It is valid to change 189 into 089 by changing the 1 (one) into
a 0 (zero), which then the leading zero can be removed, and then treated as if
the "new" number is 89.
Task
show the first 35 unprimeable numbers (horizontally, on one line, preferably with a title)
show the 600th unprimeable number
(optional) show the lowest unprimeable number ending in a specific decimal digit (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
(optional) use commas in the numbers where appropriate
Show all output here, on this page.
Also see
the OEIS entry: A118118 (unprimeable)
with some useful counts to compare unprimeable number
the Wiktionary entry (reference from below): (arithmetic definition) unprimeable
from the Adam Spencer book (page 200): Adam Spencer's World of Numbers (Xoum Publishing)
| #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[n]
proc isUmprimeable(n: Positive): bool =
if n.isPrime: return false
var nd = $n
for i, prevDigit in nd:
for newDigit in '0'..'9':
if newDigit != prevDigit:
nd[i] = newDigit
if nd.parseInt.isPrime: return false
nd[i] = prevDigit # Restore initial digit.
result = true
echo "First 35 unprimeable numbers:"
var n = 100
var list: seq[int]
while list.len < 35:
if n.isUmprimeable:
list.add n
inc n
echo list.join(" "), '\n'
var count = 0
n = 199
while count != 600:
inc n
if n.isUmprimeable: inc count
echo "600th unprimeable number: ", ($n).insertSep(','), '\n'
for d in 0..9:
var n = 200 + d
while not n.isUmprimeable:
inc n, 10
echo "Lowest unprimeable number ending in ", d, " is ", ($n).insertSep(',') |
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 identifiers
| #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 identifiers
| #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 identifiers
| #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/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
For N over its range, generate and show counts of the outputs of randN and unbiased(randN).
The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.
This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
| #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 function demonstrate (samples)
for n = 3, 6 do
biased = randN(n)
unbias = unbiased(n)
local bcounts = {[0]=0,[1]=0}
local ucounts = {[0]=0,[1]=0}
for i=1, samples do
local bnum = biased()
local unum = unbias()
bcounts[bnum] = bcounts[bnum]+1
ucounts[unum] = ucounts[unum]+1
end
print(string.format("N = %d",n),
"# 0", "# 1",
"% 0", "% 1")
print("biased", bcounts[0], bcounts[1],
bcounts[0] / samples * 100,
bcounts[1] / samples * 100)
print("unbias", ucounts[0], ucounts[1],
ucounts[0] / samples * 100,
ucounts[1] / samples * 100)
end
end
demonstrate(100000)
|
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 size and renaming it, after first deleting the original file, if no other method is available. The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged.
If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition.
On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file.
This task permits the use of such facilities. However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
| #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)
& fil$(,DEC,1)
& whl'(!file:%?c ?file&fil$(,,1,!c))
& (fil$(,SET,-1)|)
& !length:<0
)
& put$("I have a secret to tell you. Listen:","test.txt",NEW)
& ( trunc$("test.txt",20)&out$(get$("test.txt",STR))
| out$"File too short"
)
); |
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 size and renaming it, after first deleting the original file, if no other method is available. The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged.
If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition.
On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file.
This task permits the use of such facilities. However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
| #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_IGNORE_INSERTS,
NULL, error, 0, (wchar_t *)&buf, 0, NULL);
if (buf) {
fwprintf(stderr, L"%ls: %ls", message, buf);
LocalFree(buf);
} else {
/* FormatMessageW failed. */
fwprintf(stderr, L"%ls: unknown error 0x%x\n",
message, error);
}
}
int
dotruncate(wchar_t *fn, LARGE_INTEGER fp)
{
HANDLE fh;
fh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (fh == INVALID_HANDLE_VALUE) {
oops(fn);
return 1;
}
if (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||
SetEndOfFile(fh) == 0) {
oops(fn);
CloseHandle(fh);
return 1;
}
CloseHandle(fh);
return 0;
}
/*
* Truncate or extend a file to the given length.
*/
int
main()
{
LARGE_INTEGER fp;
int argc;
wchar_t **argv, *fn, junk[2];
/* MinGW never provides wmain(argc, argv). */
argv = CommandLineToArgvW(GetCommandLineW(), &argc);
if (argv == NULL) {
oops(L"CommandLineToArgvW");
return 1;
}
if (argc != 3) {
fwprintf(stderr, L"usage: %ls filename length\n", argv[0]);
return 1;
}
fn = argv[1];
/* fp = argv[2] converted to a LARGE_INTEGER. */
if (swscanf(argv[2], L"%lld%1ls", &fp.QuadPart, &junk) != 1) {
fwprintf(stderr, L"%ls: not a number\n", argv[2]);
return 1;
}
return dotruncate(fn, fp);
} |
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, starting at 1.
In an Ulam spiral of primes, only the primes are shown (usually indicated by some glyph such as a dot or asterisk), and all non-primes as shown as a blank (or some other whitespace).
Of course, the grid and border are not to be displayed (but they are displayed here when using these Wiki HTML tables).
Normally, the spiral starts in the "center", and the 2nd number is to the viewer's right and the number spiral starts from there in a counter-clockwise direction.
There are other geometric shapes that are used as well, including clock-wise spirals.
Also, some spirals (for the 2nd number) is viewed upwards from the 1st number instead of to the right, but that is just a matter of orientation.
Sometimes, the starting number can be specified to show more visual striking patterns (of prime densities).
[A larger than necessary grid (numbers wise) is shown here to illustrate the pattern of numbers on the diagonals (which may be used by the method to orientate the direction of spiral-construction algorithm within the example computer programs)].
Then, in the next phase in the transformation of the Ulam prime spiral, the non-primes are translated to blanks.
In the orange grid below, the primes are left intact, and all non-primes are changed to blanks.
Then, in the final transformation of the Ulam spiral (the yellow grid), translate the primes to a glyph such as a • or some other suitable glyph.
65
64
63
62
61
60
59
58
57
66
37
36
35
34
33
32
31
56
67
38
17
16
15
14
13
30
55
68
39
18
5
4
3
12
29
54
69
40
19
6
1
2
11
28
53
70
41
20
7
8
9
10
27
52
71
42
21
22
23
24
25
26
51
72
43
44
45
46
47
48
49
50
73
74
75
76
77
78
79
80
81
61
59
37
31
67
17
13
5
3
29
19
2
11
53
41
7
71
23
43
47
73
79
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
The Ulam spiral becomes more visually obvious as the grid increases in size.
Task
For any sized N × N grid, construct and show an Ulam spiral (counter-clockwise) of primes starting at some specified initial number (the default would be 1), with some suitably dotty (glyph) representation to indicate primes, and the absence of dots to indicate non-primes.
You should demonstrate the generator by showing at Ulam prime spiral large enough to (almost) fill your terminal screen.
Related tasks
Spiral matrix
Zig-zag matrix
Identity matrix
Sequence of primes by Trial Division
See also
Wikipedia entry: Ulam spiral
MathWorld™ entry: Prime Spiral
| #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)
{
unsigned i, j;
bitsieve *b = calloc((v >> 6) + 1, sizeof(uint32_t));
for (i = 3; i <= sqrt(v); i += 2)
if (!(b[i >> 6] & (1 << (i >> 1 & 31))))
for (j = i*i; j < v; j += (i << 1))
b[j >> 6] |= (1 << (j >> 1 & 31));
return b;
}
#define max(x,y) ((x) > (y) ? (x) : (y))
/* This mapping taken from python solution */
int ulam_get_map(int x, int y, int n)
{
x -= (n - 1) / 2;
y -= n / 2;
int mx = abs(x), my = abs(y);
int l = 2 * max(mx, my);
int d = y >= x ? l * 3 + x + y : l - x - y;
return pow(l - 1, 2) + d;
}
/* Passing a value of 0 as glyph will print numbers */
void output_ulam_spiral(int n, const char glyph)
{
/* An even side length does not make sense, use greatest odd value < n */
n -= n % 2 == 0 ? 1 : 0;
const char *spaces = ".................";
int mwidth = log10(n * n) + 1;
bitsieve *b = sieve(n * n + 1);
int x, y;
for (x = 0; x < n; ++x) {
for (y = 0; y < n; ++y) {
int z = ulam_get_map(y, x, n);
if (glyph == 0) {
if (sieve_check(b, z))
printf("%*d ", mwidth, z);
else
printf("%.*s ", mwidth, spaces);
}
else {
printf("%c", sieve_check(b, z) ? glyph : spaces[0]);
}
}
printf("\n");
}
free(b);
}
int main(int argc, char *argv[])
{
const int n = argc < 2 ? 9 : atoi(argv[1]);
output_ulam_spiral(n, 0);
printf("\n");
output_ulam_spiral(n, '#');
printf("\n");
return 0;
}
|
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 cylinder is rotated one chamber clockwise and the next chamber
checked until an empty chamber is found.
2. A cartridge containing a bullet is placed in the empty chamber.
3. The cylinder is then rotated one chamber clockwise.
To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take
a random position from 1 to 6 chamber rotations clockwise from its starting position.
When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just
counterclockwise from the loading position.
The gun is unloaded by removing all cartridges from the cylinder.
According to the legend, a suicidal Russian imperial military officer plays a game of Russian
roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice.
If the gun fires with a trigger pull, this is considered a successful suicide.
The cylinder is always spun before the first shot, but it may or may not be spun after putting
in the first bullet and may or may not be spun after taking the first shot.
Which of the following situations produces the highest probability of suicide?
A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot.
B. Spinning the cylinder after loading the first bullet only.
C. Spinning the cylinder after firing the first shot only.
D. Not spinning the cylinder either after loading the first bullet or after the first shot.
E. The probability is the same for all cases.
Task
Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios.
Show the results as a percentage of deaths for each type of scenario.
The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question.
Reference
Youtube video on the Russian 1895 Nagant revolver [[1]]
| #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;
fire
}
sub LSLSFF {
@cyl = 0 xx $shots;
load, spin, load, spin;
fire() || fire
}
sub LLSFSF {
@cyl = 0 xx $shots;
load, load, spin;
return 1 if fire;
spin;
fire
}
sub LLSFF {
@cyl = 0 xx $shots;
load, load, spin;
fire() || fire
}
my %revolver;
my $trials = 100000;
for ^$trials {
%revolver<LSLSFSF> += LSLSFSF;
%revolver<LSLSFF> += LSLSFF;
%revolver<LLSFSF> += LLSFSF;
%revolver<LLSFF> += LLSFF;
}
say "{.fmt('%7s')}: %{(%revolver{$_} / $trials × 100).fmt('%.2f')}"
for <LSLSFSF LSLSFF LLSFSF LLSFF> |
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:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #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:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #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 represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
The dot product (a scalar quantity)
A • B = a1b1 + a2b2 + a3b3
The cross product (a vector quantity)
A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
The scalar triple product (a scalar quantity)
A • (B x C)
The vector triple product (a vector quantity)
A x (B x C)
Task
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
Create a named function/subroutine/method to compute the dot product of two vectors.
Create a function to compute the cross product of two vectors.
Optionally create a function to compute the scalar triple product of three vectors.
Optionally create a function to compute the vector triple product of three vectors.
Compute and display: a • b
Compute and display: a x b
Compute and display: a • (b x c), the scalar triple product.
Compute and display: a x (b x c), the vector triple product.
References
A starting page on Wolfram MathWorld is Vector Multiplication .
Wikipedia dot product.
Wikipedia cross product.
Wikipedia triple product.
Related tasks
Dot product
Quaternion type
| #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);", ";@(d+1);", ";@(d+2);")"
Print "a . (b x c) = "; FUNC(_FNscalarTriple(a, b, c))
Proc _VectorTriple (a, b, c, d)
Print "a x (b x c) = (";@(d+0);", ";@(d+1);", ";@(d+2);")"
End
_FNdot Param (2)
Return ((@(a@+0)*@(b@+0))+(@(a@+1)*@(b@+1))+(@(a@+2)*@(b@+2)))
_Vector Param (4) ' initialize a vector
@(a@ + 0) = b@
@(a@ + 1) = c@
@(a@ + 2) = d@
Return
_Cross Param (3)
@(c@+0) = @(a@ + 1) * @(b@ + 2) - @(a@ + 2) * @(b@ + 1)
@(c@+1) = @(a@ + 2) * @(b@ + 0) - @(a@ + 0) * @(b@ + 2)
@(c@+2) = @(a@ + 0) * @(b@ + 1) - @(a@ + 1) * @(b@ + 0)
Return
_FNscalarTriple Param (3)
Local (1) ' a "local" vector
d@ = d + 3 ' (best effort) ;-)
Proc _Cross(b@, c@, d@)
Return (FUNC(_FNdot(a@, d@)))
_VectorTriple Param(4)
Local (1) ' a "local" vector
e@ = d + 3 ' (best effort) ;-)
Proc _Cross (b@, c@, e@)
Proc _Cross (a@, e@, d@)
Return |
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 Unicode?
Task
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
How easy is it to present Unicode strings in source code?
Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
How well can the language communicate with the rest of the world?
Is it good at input/output with Unicode?
Is it convenient to manipulate Unicode strings in the language?
How broad/deep does the language support Unicode?
What encodings (e.g. UTF-8, UTF-16, etc) can be used?
Does it support normalization?
Note
This task is a bit unusual in that it encourages general discussion rather than clever coding.
See also
Unicode variable names
Terminal control/Display an extended character
| #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 + ◌̊ COMBINING RING ABOVE + ◌́ COMBINING ACUTE ACCENT
let nfkx = "\u{FF21}\u{030A}\u{0301}"//Fullwidth Latin Capital Letter A + ◌̊ COMBINING RING ABOVE + ◌́ COMBINING ACUTE ACCENT
print(nfc == nfd) //NFx: true
print(nfc == nfkx) //NFKx: false
|
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 Unicode?
Task
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
How easy is it to present Unicode strings in source code?
Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
How well can the language communicate with the rest of the world?
Is it good at input/output with Unicode?
Is it convenient to manipulate Unicode strings in the language?
How broad/deep does the language support Unicode?
What encodings (e.g. UTF-8, UTF-16, etc) can be used?
Does it support normalization?
Note
This task is a bit unusual in that it encourages general discussion rather than clever coding.
See also
Unicode variable names
Terminal control/Display an extended character
| #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ù" ),
国際( "Stanisław Lec", "południow" ),
];
民族.each { |garçon|
garçon.言え;
} |
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 number).
Extension
Find all twin prime pairs under 100000, 10000000 and 1000000000.
What is the time complexity of the program? Are there ways to reduce computation time?
Examples
> Search Size: 100
> 8 twin prime pairs.
> Search Size: 1000
> 35 twin prime pairs.
Also see
The OEIS entry: A001097: Twin primes.
The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.
The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.
The OEIS entry: A007508: Number of twin prime pairs below 10^n.
| #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 x = new BigInteger("3"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){
BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);
if(x.add(BigInteger.TWO).compareTo(max) <= 0) {
counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;
}
}
System.out.println(counter + " twin prime pairs.");
}
public static boolean findPrime(BigInteger x, BigInteger sqrtNum){
for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){
if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){
return false;
}
}
return true;
}
}
|
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 (referenced from Adam Spencer's book) ─────:
(arithmetic) that cannot be turned into a prime number by changing just one of its digits to any other
digit. (sic)
Unprimeable numbers are also spelled: unprimable.
All one─ and two─digit numbers can be turned into primes by changing a single decimal digit.
Examples
190 isn't unprimeable, because by changing the zero digit into a three yields 193, which is a prime.
The number 200 is unprimeable, since none of the numbers 201, 202, 203, ··· 209 are
prime, and all the other numbers obtained by changing a single digit to
produce 100, 300, 400, ··· 900, or 210, 220, 230, ··· 290 which are all even.
It is valid to change 189 into 089 by changing the 1 (one) into
a 0 (zero), which then the leading zero can be removed, and then treated as if
the "new" number is 89.
Task
show the first 35 unprimeable numbers (horizontally, on one line, preferably with a title)
show the 600th unprimeable number
(optional) show the lowest unprimeable number ending in a specific decimal digit (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
(optional) use commas in the numbers where appropriate
Show all output here, on this page.
Also see
the OEIS entry: A118118 (unprimeable)
with some useful counts to compare unprimeable number
the Wiktionary entry (reference from below): (arithmetic definition) unprimeable
from the Adam Spencer book (page 200): Adam Spencer's World of Numbers (Xoum Publishing)
| #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,
EndDgtFound : TNumVal;
TotalCnt,
EndDgtCnt :NativeUint;
procedure Init;
var
i,val : NativeUint;
Begin
val := 1;
For i := low(TNumVal) to High(TNumVal) do
Begin
EndDgtFound[i] :=0;
PotBase[i] := val;
val := val * Base;
end;
TotalCnt := 0;
EndDgtCnt := 0;
end;
Procedure ConvertNum(n: NativeUint;var NConv:TConvNum);
//extract digit position replace by "0" to get NumRest
// 173 -> 170 -> 103 -> 073
var
i, dgt,n_red,n_mod: NativeUint;
begin
i := 0;
n_red := n;
with NConv do
Begin
repeat
n_mod := n_red DIV Base;
dgt := n_red-Base*n_mod;
n_red := n_mod;
IF i = 0 then
LowDgt := dgt;
NumRest[i]:= n-dgt*PotBase[i];
inc(i);
until (i > High(TNumVal)) OR (n<PotBase[i]);
MaxIdx := i-1;
end;
end;
procedure CheckOutPut(n: NativeUint);
Begin
IF TotalCnt > 600 then
EXIT;
IF TotalCnt <= 35 then
write(n,' ');
IF TotalCnt = 600 then
Begin
writeln;
writeln;
writeln('the 600.th unprimable number: ',n);
end;
end;
function isPrime(n : NativeUint):boolean;inline;
var
p : NativeUint;
Begin
result := (N=2) OR (N=3);
IF result then
EXIT;
//now result = false
IF (n<2) OR (NOT(ODD(n))) or (n mod 3= 0) then
EXIT;
p := 5;
while p*p <= n do
Begin
if n mod p = 0 then
Exit;
inc(p,2);
if n mod p = 0 then
Exit;
inc(p,4);
end;
result := true;
end;
procedure InsertFound(LowDgt,n:NativeUInt);
Begin
inc(TotalCnt);
IF EndDgtFound[LowDgt] = 0 then
Begin
EndDgtFound[LowDgt] := n;
inc(EndDgtCnt);
end;
end;
function CheckUnprimable(n:NativeInt):boolean;
var
ConvNum : TConvNum;
val,dgt,i,dtfac: NativeUint;
Begin
ConvertNum(n,ConvNum);
result := false;
//lowest digit
with ConvNum do
Begin
val := NumRest[0];
For dgt := 0 to Base-1 do
IF isPrime(val+dgt) then
EXIT;
dgt := LowDgt;
result := true;
i := MaxIdx;
IF NumRest[i] >= Base then
Begin
//****Only for base=10 if even or divisible by 5***
IF Not(ODD(dgt)) OR (dgt=5) then
Begin
InsertFound(dgt,n);
EXIT;
end;
end;
result := false;
For i := MaxIdx downto 1 do
Begin
dtfac := PotBase[i];
val := NumRest[i];
For dgt := 0 to Base-1 do
Begin
IF isPrime(val) then
EXIT;
inc(val,dtfac);
end;
end;
InsertFound(LowDgt,n);
result := true;
end;
end;
function CheckUnprimableReduced(n:NativeInt):boolean;
//lowest digit already tested before
var
ConvNum : TConvNum;
val,dgt,i,dtfac: NativeUint;
Begin
ConvertNum(n,ConvNum);
result := true;
with ConvNum do
Begin
i := MaxIdx;
IF NumRest[i] >= Base then
Begin
dgt := LowDgt;
IF Not(ODD(dgt)) OR (dgt=5) then
Begin
InsertFound(dgt,n);
EXIT;
end;
end;
result := false;
For i := i downto 1 do
Begin
dtfac := PotBase[i];
val := NumRest[i];
For dgt := 0 to Base-1 do
Begin
IF isPrime(val) then
EXIT;
inc(val,dtfac);
end;
end;
InsertFound(LowDgt,n);
result := true;
end;
end;
var
n,i : NativeUint;
Begin
init;
n := Base;
repeat
If CheckUnprimable(n) then
Begin
CheckOutPut(n);
For i := 1 to Base-1 do
Begin
IF CheckUnprimableReduced(n+i) then
CheckOutPut(n+i);
end;
end;
inc(n,Base);
until EndDgtCnt = Base;
writeln;
For i := 0 to Base-1 do
Writeln ('lowest digit ',i:2,' found first ',EndDgtFound[i]:7);
writeln;
writeln('There are ',TotalCnt,' unprimable numbers upto ',n);
{$IFNDEF UNIX}readln;{$ENDIF}
end. |
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 identifiers
| #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 identifiers
| #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 identifiers
| #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 identifiers
| #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/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
For N over its range, generate and show counts of the outputs of randN and unbiased(randN).
The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.
This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
| #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/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
For N over its range, generate and show counts of the outputs of randN and unbiased(randN).
The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.
This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
| #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
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method unbiased(n = int) public static returns boolean
a = boolean
b = boolean
loop until a \= b
a = biased(n)
b = biased(n)
end
return a
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
parse arg Mx .
if Mx.length <= 0 then Mx = 50000
M = int Mx
loop n = int 3 to 6
c1 = int 0
c2 = int 0
loop for M
if biased(n) then c1 = c1 + 1
if unbiased(n) then c2 = c2 + 1
end
say Rexx(n).right(3)':' Rexx(100.0 * c1 / M).format(6, 2)'%' Rexx(100.0 * c2 / M).format(6, 2)'%'
end n
return
|
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 size and renaming it, after first deleting the original file, if no other method is available. The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged.
If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition.
On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file.
This task permits the use of such facilities. However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
| #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.Exists(path))
throw new ArgumentException("No file found at specified path.", "path");
using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Write))
{
if (fileStream.Length < length)
throw new ArgumentOutOfRangeException("length",
"The specified length is greater than that of the file.");
fileStream.SetLength(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 size and renaming it, after first deleting the original file, if no other method is available. The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged.
If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition.
On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file.
This task permits the use of such facilities. However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
| #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( &buffer, sizeof(buffer) );
appendFile.write(&buffer,1);
}
appendFile.close(); }
int main () {
truncateFile("test.txt", 5);
return 0;
}
|
http://rosettacode.org/wiki/Truth_table | Truth table | A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.
Task
Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function.
(One can assume that the user input is correct).
Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function.
Either reverse-polish or infix notation expressions are allowed.
Related tasks
Boolean values
Ternary logic
See also
Wolfram MathWorld entry on truth tables.
some "truth table" examples from Google.
| #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)
.name = name
[Var] vars
T ASTNode
Symbol& symbol
Int var_index
ASTNode? first_child
ASTNode? second_child
F eval()
S .symbol.id
‘(var)’
R :vars[.var_index].value
‘|’
R .first_child.eval() [|] .second_child.eval()
‘^’
R .first_child.eval() (+) .second_child.eval()
‘&’
R .first_child.eval() [&] .second_child.eval()
‘!’
R (-).first_child.eval() [&] 1
‘(’
R .first_child.eval()
E
assert(0B)
R 0
[String = Symbol] symbol_table
[String] tokens
V tokeni = -1
ASTNode token_node
F advance(sid = ‘’)
I sid != ‘’
assert(:token_node.symbol.id == sid)
:tokeni++
:token_node = ASTNode()
I :tokeni == :tokens.len
:token_node.symbol = :symbol_table[‘(end)’]
R
V token = :tokens[:tokeni]
I token[0].is_alpha()
:token_node.symbol = :symbol_table[‘(var)’]
L(v) :vars
I v.name == token
:token_node.var_index = L.index
L.break
L.was_no_break
:token_node.var_index = :vars.len
:vars.append(Var(token))
E
:token_node.symbol = :symbol_table[token]
F expression(rbp = 0)
ASTNode t = move(:token_node)
advance()
V left = t.symbol.nud(move(t))
L rbp < :token_node.symbol.lbp
t = move(:token_node)
advance()
left = t.symbol.led(t, move(left))
R left
F parse(expr_str) -> ASTNode
:tokens = re:‘\s*(\w+|.)’.find_strings(expr_str)
:tokeni = -1
:vars.clear()
advance()
R expression()
F symbol(id, bp = 0) -> &
I id !C :symbol_table
V s = Symbol()
s.id = id
s.lbp = bp
:symbol_table[id] = s
R :symbol_table[id]
F infix(id, bp)
F led(ASTNode self, ASTNode left)
self.first_child = left
self.second_child = expression(self.symbol.led_bp)
R self
symbol(id, bp).set_led_bp(bp, led)
F prefix(id, bp)
F nud(ASTNode self)
self.first_child = expression(self.symbol.nud_bp)
R self
symbol(id).set_nud_bp(bp, nud)
infix(‘|’, 1)
infix(‘^’, 2)
infix(‘&’, 3)
prefix(‘!’, 4)
F nud(ASTNode self)
R self
symbol(‘(var)’).nud = nud
symbol(‘(end)’)
F nud_parens(ASTNode self)
V expr = expression()
advance(‘)’)
R expr
symbol(‘(’).nud = nud_parens
symbol(‘)’)
L(expr_str) [‘!A | B’, ‘A ^ B’, ‘S | ( T ^ U )’, ‘A ^ (B ^ (C ^ D))’]
print(‘Boolean expression: ’expr_str)
print()
ASTNode p = parse(expr_str)
print(vars.map(v -> v.name).join(‘ ’)‘ : ’expr_str)
L(i) 0 .< (1 << vars.len)
L(v) vars
v.value = (i >> (vars.len - 1 - L.index)) [&] 1
print(v.value, end' ‘ ’)
print(‘: ’p.eval())
print() |
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, starting at 1.
In an Ulam spiral of primes, only the primes are shown (usually indicated by some glyph such as a dot or asterisk), and all non-primes as shown as a blank (or some other whitespace).
Of course, the grid and border are not to be displayed (but they are displayed here when using these Wiki HTML tables).
Normally, the spiral starts in the "center", and the 2nd number is to the viewer's right and the number spiral starts from there in a counter-clockwise direction.
There are other geometric shapes that are used as well, including clock-wise spirals.
Also, some spirals (for the 2nd number) is viewed upwards from the 1st number instead of to the right, but that is just a matter of orientation.
Sometimes, the starting number can be specified to show more visual striking patterns (of prime densities).
[A larger than necessary grid (numbers wise) is shown here to illustrate the pattern of numbers on the diagonals (which may be used by the method to orientate the direction of spiral-construction algorithm within the example computer programs)].
Then, in the next phase in the transformation of the Ulam prime spiral, the non-primes are translated to blanks.
In the orange grid below, the primes are left intact, and all non-primes are changed to blanks.
Then, in the final transformation of the Ulam spiral (the yellow grid), translate the primes to a glyph such as a • or some other suitable glyph.
65
64
63
62
61
60
59
58
57
66
37
36
35
34
33
32
31
56
67
38
17
16
15
14
13
30
55
68
39
18
5
4
3
12
29
54
69
40
19
6
1
2
11
28
53
70
41
20
7
8
9
10
27
52
71
42
21
22
23
24
25
26
51
72
43
44
45
46
47
48
49
50
73
74
75
76
77
78
79
80
81
61
59
37
31
67
17
13
5
3
29
19
2
11
53
41
7
71
23
43
47
73
79
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
The Ulam spiral becomes more visually obvious as the grid increases in size.
Task
For any sized N × N grid, construct and show an Ulam spiral (counter-clockwise) of primes starting at some specified initial number (the default would be 1), with some suitably dotty (glyph) representation to indicate primes, and the absence of dots to indicate non-primes.
You should demonstrate the generator by showing at Ulam prime spiral large enough to (almost) fill your terminal screen.
Related tasks
Spiral matrix
Zig-zag matrix
Identity matrix
Sequence of primes by Trial Division
See also
Wikipedia entry: Ulam spiral
MathWorld™ entry: Prime Spiral
| #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( static_cast<long double>( v ) ) ) + 1;
for( unsigned u = 0; u < v; u++ )
_lst.push_back( -1 );
arrange( startWith );
}
void display( char c ) {
if( !c ) displayNumbers();
else displaySymbol( c );
}
private:
bool isPrime( unsigned u ) {
if( u < 4 ) return u > 1;
if( !( u % 2 ) || !( u % 3 ) ) return false;
unsigned q = static_cast<unsigned>( sqrt( static_cast<long double>( u ) ) ),
c = 5;
while( c <= q ) {
if( !( u % c ) || !( u % ( c + 2 ) ) ) return false;
c += 6;
}
return true;
}
void arrange( unsigned s ) {
unsigned stp = 1, n = 1, posX = _mx >> 1,
posY = posX, stC = 0;
int dx = 1, dy = 0;
while( posX < _mx && posY < _mx ) {
_lst.at( posX + posY * _mx ) = isPrime( s ) ? s : 0;
s++;
if( dx ) {
posX += dx;
if( ++stC == stp ) {
dy = -dx;
dx = stC = 0;
}
} else {
posY += dy;
if( ++stC == stp ) {
dx = dy;
dy = stC = 0;
stp++;
}
}
}
}
void displayNumbers() {
unsigned ct = 0;
for( std::vector<unsigned>::iterator i = _lst.begin(); i != _lst.end(); i++ ) {
if( *i ) std::cout << std::setw( _wd ) << *i << " ";
else std::cout << std::string( _wd, '*' ) << " ";
if( ++ct >= _mx ) {
std::cout << "\n";
ct = 0;
}
}
std::cout << "\n\n";
}
void displaySymbol( char c ) {
unsigned ct = 0;
for( std::vector<unsigned>::iterator i = _lst.begin(); i != _lst.end(); i++ ) {
if( *i ) std::cout << c;
else std::cout << " ";
if( ++ct >= _mx ) {
std::cout << "\n";
ct = 0;
}
}
std::cout << "\n\n";
}
std::vector<unsigned> _lst;
unsigned _mx, _wd;
};
int main( int argc, char* argv[] )
{
ulamSpiral ulam;
ulam.create( 9 );
ulam.display( 0 );
ulam.create( 35 );
ulam.display( '#' );
return 0;
} |
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 cylinder is rotated one chamber clockwise and the next chamber
checked until an empty chamber is found.
2. A cartridge containing a bullet is placed in the empty chamber.
3. The cylinder is then rotated one chamber clockwise.
To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take
a random position from 1 to 6 chamber rotations clockwise from its starting position.
When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just
counterclockwise from the loading position.
The gun is unloaded by removing all cartridges from the cylinder.
According to the legend, a suicidal Russian imperial military officer plays a game of Russian
roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice.
If the gun fires with a trigger pull, this is considered a successful suicide.
The cylinder is always spun before the first shot, but it may or may not be spun after putting
in the first bullet and may or may not be spun after taking the first shot.
Which of the following situations produces the highest probability of suicide?
A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot.
B. Spinning the cylinder after loading the first bullet only.
C. Spinning the cylinder after firing the first shot only.
D. Not spinning the cylinder either after loading the first bullet or after the first shot.
E. The probability is the same for all cases.
Task
Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios.
Show the results as a percentage of deaths for each type of scenario.
The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question.
Reference
Youtube video on the Russian 1895 Nagant revolver [[1]]
| #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 /* " " " " " " */
if datatype(seed, 'W') then call random ,,seed /* " " " " " " */
cyls_ = cyls - 1; @0= copies(0, cyls) /*shortcut placeholder for cylinders-1 */
@abc= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' /*indices for the various options used.*/
scenarios= 'LSLSFsF LSLSFF LLSFSF LLSFF' /*the list of scenarios to be tested. */
#= words(scenarios) /*the number of actions in a scenario. */
/*The scenarios are case insensitive. */
do m=1 for #; q= word(scenarios, m) /*test each of the scenarios specified.*/
sum= 0 /*initialize the sum to zero. */
do tests; sum= sum + method() /*added the sums up for the percentages*/
end /*tests*/
pc= left( (sum * 100 / tests)"%", 7)
say act() ' (option' substr(@abc, m, 1)") produces " pc ' deaths.'
end /*m*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
fire: != left(@, 1); @= right(@, cyls_)left(@, 1); /* ◄──── next cyl.*/ return !
load: if left(@, 1) then @= right(@, cyls_)left(@, 1); @= 1||right(@, cyls_); return
spin: ?= random(1, cyls); if ?\==cyls then @= substr(@ || @, ? + 1, cyls); return
/*──────────────────────────────────────────────────────────────────────────────────────*/
method: @= @0; do a=1 for length(q); y= substr(q, a, 1)
if y=='L' then call load
else if y=='S' then call spin
else if y=='F' then if fire() then return 1
end /*a*/; return 0
/*──────────────────────────────────────────────────────────────────────────────────────*/
act: $=; do a=1 for length(q); y= substr(q, a, 1)
if y=='L' then $= $", load"
if y=='S' then $= $", spin"
if y=='F' then $= $", fire"
end /*a*/; return right( strip( strip($, , ",") ), 45) |
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:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #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-directory* "foo/bar")
(for ([f '("1" "2" "a" "b")])
(with-output-to-file (format "foo/bar/~a"f) #:exists 'replace newline)))
(make-directory-tree)
(define (ls/str dir)
(parameterize ([current-directory dir]) (with-output-to-string ls)))
(test (ls/str "foo") => "bar\n"
(ls/str "foo/bar") => "1\n2\na\nb\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:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #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:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #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 represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
The dot product (a scalar quantity)
A • B = a1b1 + a2b2 + a3b3
The cross product (a vector quantity)
A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
The scalar triple product (a scalar quantity)
A • (B x C)
The vector triple product (a vector quantity)
A x (B x C)
Task
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
Create a named function/subroutine/method to compute the dot product of two vectors.
Create a function to compute the cross product of two vectors.
Optionally create a function to compute the scalar triple product of three vectors.
Optionally create a function to compute the vector triple product of three vectors.
Compute and display: a • b
Compute and display: a x b
Compute and display: a • (b x c), the scalar triple product.
Compute and display: a x (b x c), the vector triple product.
References
A starting page on Wolfram MathWorld is Vector Multiplication .
Wikipedia dot product.
Wikipedia cross product.
Wikipedia triple product.
Related tasks
Dot product
Quaternion type
| #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 Function
Function scalar_triple_product(a As Variant, b As Variant, c As Variant) As Variant
scalar_triple_product = dot_product(a, cross_product(b, c))
End Function
Function vector_triple_product(a As Variant, b As Variant, c As Variant) As Variant
vector_triple_product = cross_product(a, cross_product(b, c))
End Function
Public Sub main()
a = [{3, 4, 5}]
b = [{4, 3, 5}]
c = [{-5, -12, -13}]
Debug.Print " a . b = "; dot_product(a, b)
Debug.Print " a x b = "; "("; Join(cross_product(a, b), ", "); ")"
Debug.Print "a . (b x c) = "; scalar_triple_product(a, b, c)
Debug.Print "a x (b x c) = "; "("; Join(vector_triple_product(a, b, c), ", "); ")"
End Sub |
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 check"}
# Remove its value
unset var
# Check to see whether it is defined
if {![info exists var]} {puts "var is undefind at third check"}
# Give it a value again
set var 12345
# Check to see whether it is defined
if {![info exists var]} {puts "var is undefind at fourth check"}
puts "Done" |
|
http://rosettacode.org/wiki/Undefined_values | Undefined values | #UNIX_Shell | UNIX Shell | VAR1="VAR1"
echo ${VAR1:-"Not set."}
echo ${VAR2:-"Not set."} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.