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/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. Β These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Β Walk a directory/Non-recursively Β (read a single directory).
| #Nim | Nim | import os, re
Β
for file in walkDirRec "/":
if file.match re".*\.mp3":
echo file |
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ββ 9 ββ
8 ββ 8 ββ
7 ββ ββ 7 ββββββββββββ
6 ββ ββ ββ 6 ββββββββββββ
5 ββ ββ ββ ββββ 5 ββββββββββββββββ
4 ββ ββ ββββββββ 4 ββββββββββββββββ
3 ββββββ ββββββββ 3 ββββββββββββββββ
2 ββββββββββββββββ ββ 2 ββββββββββββββββββββ
1 ββββββββββββββββββββ 1 ββββββββββββββββββββ
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
Four Solutions to a Trivial Problem β a Google Tech Talk by Guy Steele
Water collected between towers on Stack Overflow, from which the example above is taken)
An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| #Perl | Perl | use Modern::Perl;
use List::Util qw{ min max sum };
Β
sub water_collected {
my @t = map { { TOWER => $_, LEFT => 0, RIGHT => 0, LEVEL => 0 } } @_;
Β
my ( $l, $r ) = ( 0, 0 );
$_->{LEFT} = ( $l = max( $l, $_->{TOWER} ) ) for @t;
$_->{RIGHT} = ( $r = max( $r, $_->{TOWER} ) ) for reverse @t;
$_->{LEVEL} = min( $_->{LEFT}, $_->{RIGHT} ) for @t;
Β
return sum map { $_->{LEVEL} > 0 ? $_->{LEVEL} - $_->{TOWER} : 0 } @t;
}
Β
say join ' ', map { water_collected( @{$_} ) } (
[ 1, 5, 3, 7, 2 ],
[ 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 ],
[ 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 ],
[ 5, 5, 5, 5 ],
[ 5, 6, 7, 8 ],
[ 8, 7, 7, 6 ],
[ 6, 7, 10, 7, 6 ],
); |
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
| #11l | 11l | F scalartriplep(a, b, c)
return dot(a, cross(b, c))
Β
F vectortriplep(a, b, c)
return cross(a, cross(b, c))
Β
V a = (3, 4, 5)
V b = (4, 3, 5)
V c = (-5, -12, -13)
Β
print(βa = #.; b = #.; c = #.β.format(a, b, c))
print(βa . b = #.β.format(dot(a, b)))
print(βa x b = #.β.format(cross(a,b)))
print(βa . (b x c) = #.β.format(scalartriplep(a, b, c)))
print(βa x (b x c) = #.β.format(vectortriplep(a, b, c))) |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #PicoLisp | PicoLisp | (de checkDistribution (Cnt Pm . Prg)
(let Res NIL
(do Cnt (accu 'Res (run Prg 1) 1))
(let
(N (/ Cnt (length Res))
Min (*/ N (- 1000 Pm) 1000)
Max (*/ N (+ 1000 Pm) 1000) )
(for R Res
(prinl (cdr R) " " (if (>= Max (cdr R) Min) "Good" "Bad")) ) ) ) ) |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #PureBasic | PureBasic | Prototype RandNum_prt()
Β
Procedure.s distcheck(*function.RandNum_prt, repetitions, delta.d)
Protected text.s, maxIndex = 0
Dim bucket(maxIndex) ;array will be resized as needed
Β
For i = 1 To repetitions ;populate buckets
v = *function()
If v > maxIndex
maxIndex = v
Redim bucket(maxIndex)
EndIf
bucket(v) + 1
Next
Β
Β
lbnd = Round((repetitions / maxIndex) * (100 - delta) / 100, #PB_Round_Up)
ubnd = Round((repetitions / maxIndex) * (100 + delta) / 100, #PB_Round_Down)
text = "Distribution check:" + #crlf$ + #crlf$
text + "Total elements = " + Str(repetitions) + #crlf$ + #crlf$
text + "Margin = " + StrF(delta, 2) + "% --> Lbound = " + Str(lbnd) + ", Ubound = " + Str(ubnd) + #crlf$
Β
For i = 1 To maxIndex
If bucket(i) < lbnd Or bucket(i) > ubnd
text + #crlf$ + "Bucket " + Str(i) + " contains " + Str(bucket(i)) + " elements. Skewed."
EndIf
Next
ProcedureReturn text
EndProcedure
Β
MessageRequester("Results", distcheck(@dice7(), 1000000, 0.20)) |
http://rosettacode.org/wiki/Variable-length_quantity | Variable-length quantity | Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte);
display these sequences of octets;
convert these sequences of octets back to numbers, and check that they are equal to original numbers.
| #Go | Go | package main
Β
import (
"fmt"
"encoding/binary"
)
Β
func main() {
buf := make([]byte, binary.MaxVarintLen64)
for _, x := range []int64{0x200000, 0x1fffff} {
v := buf[:binary.PutVarint(buf, x)]
fmt.Printf("%d encodes intoΒ %d bytes:Β %x\n", x, len(v), v)
x, _ = binary.Varint(v)
fmt.Println(x, "decoded")
}
} |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Β Call a function
| #AutoHotkey | AutoHotkey | printAll(args*) {
for k,v in args
t .= v "`n"
MsgBox, %t%
} |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Β Call a function
| #AWK | AWK | function f(a, b, c){
if (a != "") print a
if (b != "") print b
if (c != "") print c
}
Β
BEGIN {
print "[1 arg]"; f(1)
print "[2 args]"; f(1, 2)
print "[3 args]"; f(1, 2, 3)
} |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #Delphi | Delphi | Β
program Vector;
Β
{$APPTYPE CONSOLE}
Β
{$R *.res}
Β
uses
System.Math.Vectors,
SysUtils;
Β
procedure VectorToString(v: TVector);
begin
WriteLn(Format('(%.1f + i%.1f)', [v.X, v.Y]));
end;
Β
var
a, b: TVector;
Β
begin
a := TVector.Create(5, 7);
b := TVector.Create(2, 3);
VectorToString(a + b);
VectorToString(a - b);
VectorToString(a * 11);
VectorToString(a / 2);
Β
ReadLn;
end
Β
.
Β |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | TYPE UByte = BITS 8 FOR [0..255]; |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #Modula-3 | Modula-3 | TYPE UByte = BITS 8 FOR [0..255]; |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #Nim | Nim | type
MyBitfield = object
flag {.bitsize:1.}: cuint |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #ooRexx | ooRexx | default(precision, 1000) |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #PARI.2FGP | PARI/GP | default(precision, 1000) |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #Pascal | Pascal | type
correctInteger = integer attribute (size = 42); |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #Scala | Scala | import java.awt.geom.Ellipse2D
import java.awt.image.BufferedImage
import java.awt.{Color, Graphics, Graphics2D}
Β
import scala.math.sqrt
Β
object Voronoi extends App {
private val (cells, dim) = (100, 1000)
private val rand = new scala.util.Random
private val color = Vector.fill(cells)(rand.nextInt(0x1000000))
private val image = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_RGB)
private val g: Graphics2D = image.createGraphics()
private val px = Vector.fill(cells)(rand.nextInt(dim))
private val py = Vector.fill(cells)(rand.nextInt(dim))
Β
for (x <- 0 until dim;
y <- 0 until dim) {
var n = 0
Β
def distance(x1: Int, x2: Int, y1: Int, y2: Int) =
sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2).toDouble) // Euclidian
Β
for (i <- px.indices
if distance(px(i), x, py(i), y) < distance(px(n), x, py(n), y))
n = i
image.setRGB(x, y, color(n))
}
Β
g.setColor(Color.BLACK)
for (i <- px.indices) g.fill(new Ellipse2D.Double(px(i) - 2.5, py(i) - 2.5, 5, 5))
Β
new javax.swing.JFrame("Voronoi Diagram") {
override def paint(g: Graphics): Unit = {g.drawImage(image, 0, 0, this); ()}
Β
setBounds(0, 0, dim, dim)
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE)
setLocationRelativeTo(null)
setResizable(false)
setVisible(true)
}
Β
} |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test | Verify distribution uniformity/Chi-squared test | Task
Write a function to verify that a given distribution of values is uniform by using the
Ο
2
{\displaystyle \chi ^{2}}
test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%).
The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce.
Reference
Β an entry at the MathWorld website: Β chi-squared distribution.
| #Phix | Phix | with javascript_semantics
function f(atom aa1, t)
return power(t, aa1) * exp(-t)
end function
function simpson38(atom aa1, a, b, integer n)
atom h := (b-a)/n,
h1 := h/3,
tot := f(aa1,a) + f(aa1,b)
for j=3*n-1 to 1 by -1 do
tot += (3-(mod(j,3)=0)) * f(aa1,a+h1*j)
end for
return h*tot/8
end function
--<copy of gamma from Gamma_function#Phix>
sequence c = repeat(0,12)
function gamma(atom z)
atom accm = c[1]
if accm=0 then
accm = sqrt(2*PI)
c[1] = accm
atom k1_factrl = 1 -- (k - 1)!*(-1)^k with 0!==1
for k=2 to 12 do
c[k] = exp(13-k)*power(13-k,k-1.5)/k1_factrl
k1_factrl *= -(k-1)
end for
end if
for k=2 to 12 do
accm += c[k]/(z+k-1)
end for
accm *= exp(-(z+12))*power(z+12,z+0.5) -- Gamma(z+1)
return accm/z
end function
--</copy of gamma>
function gammaIncQ(atom a, x)
atom aa1 := a-1,
y := aa1,
h := 1.5e-2
while f(aa1,y)*(x-y) > 2e-8 and y < x do
y += 0.4
end while
if y > x then y = x end if
return 1 - simpson38(aa1,0,y,floor(y/h/gamma(a)))
end function
function chi2ud(sequence ds)
atom expected = sum(ds)/length(ds),
tot = sum(sq_power(sq_sub(ds,expected),2))
return tot/expected
end function
function chi2p(integer dof, atom distance)
return gammaIncQ(0.5*dof,0.5*distance)
end function
constant sigLevel = 0.05
procedure utest(sequence dset)
printf(1,"Uniform distribution test\n")
integer tot = sum(dset),
dof := length(dset)-1
atom dist := chi2ud(dset),
p := chi2p(dof, dist)
bool sig := p < sigLevel
printf(1," dataset:Β %v\n",{dset})
printf(1," samples: Β %d\n", tot)
printf(1," categories: Β %d\n", length(dset))
printf(1," degrees of freedom: Β %d\n", dof)
printf(1," chi square test statistic:Β %g\n", dist)
printf(1," p-value of test statistic:Β %g\n", p)
printf(1," significant atΒ %.0f%% level? Β %t\n", {sigLevel*100, sig})
printf(1," uniform? Β %t\n",not sig)
end procedure
utest({199809, 200665, 199607, 200270, 199649})
utest({522573, 244456, 139979, 71531, 21461})
|
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a  Vigenère cypher,  both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Β Caesar cipher
Β Rot-13
Β Substitution Cipher
| #J | J | NB.*vig c Vigenère cipher
NB. cipher=. key 0 vig charset plain
NB. plain=. key 1 vig charset cipher
vig=: conjunction define
:
r=. (#y) $ n i.x
n {~ (#n) | (r*_1^m) + n i.y
)
Β
ALPHA=: (65,:26) ];.0 a. NB. Character Set
preprocess=: (#~ e.&ALPHA)@toupper NB. force uppercase and discard non-alpha chars
vigEncryptRC=: 0 vig ALPHA preprocess
vigDecryptRC=: 1 vig ALPHA preprocess |
http://rosettacode.org/wiki/Visualize_a_tree | Visualize a tree | A tree structure Β (i.e. a rooted, connected acyclic graph) Β is often used in programming.
It's often helpful to visually examine such a structure.
There are many ways to represent trees to a reader, such as:
Β indented text Β (Γ la unix tree command)
Β nested HTML tables
Β hierarchical GUI widgets
Β 2D Β or Β 3D Β images
Β etc.
Task
Write a program to produce a visual representation of some tree.
The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly.
Make do with the vague term "friendly" the best you can.
| #Maxima | Maxima | load(graphs)$
Β
g: random_tree(10)$
Β
is_tree(g);
true
Β
draw_graph(g)$ |
http://rosettacode.org/wiki/Visualize_a_tree | Visualize a tree | A tree structure Β (i.e. a rooted, connected acyclic graph) Β is often used in programming.
It's often helpful to visually examine such a structure.
There are many ways to represent trees to a reader, such as:
Β indented text Β (Γ la unix tree command)
Β nested HTML tables
Β hierarchical GUI widgets
Β 2D Β or Β 3D Β images
Β etc.
Task
Write a program to produce a visual representation of some tree.
The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly.
Make do with the vague term "friendly" the best you can.
| #Nim | Nim | import strutils
Β
type
Node[T] = ref object
data: T
left, right: Node[T]
Β
proc n[T](data: T; left, right: Node[T] = nil): Node[T] =
Node[T](data: data, left: left, right: right)
Β
proc indent[T](n: Node[T]): seq[string] =
if n == nil: return @["-- (null)"]
Β
result = @["--" & $n.data]
Β
for a in indent n.left: result.add " |" & a
Β
let r = indent n.right
result.add " `" & r[0]
for a in r[1..r.high]: result.add " " & a
Β
let tree = 1.n(2.n(4.n(7.n),5.n),3.n(6.n(8.n,9.n)))
Β
echo tree.indent.join("\n") |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #Standard_ML | Standard ML | fun dirEntries path =
let
fun loop strm =
case OS.FileSys.readDir strm of
SOME name => nameΒ :: loop strm
| NONE => []
val strm = OS.FileSys.openDir path
in
loop strm before OS.FileSys.closeDir strm
end |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #Tcl | Tcl | foreach filename [glob *.txt] {
puts $filename
} |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. Β These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Β Walk a directory/Non-recursively Β (read a single directory).
| #Objeck | Objeck | use System.IO.File;
Β
class Test {
function : Main(args : String[]) ~ Nil {
if(args->Size() = 2) {
DescendDir(args[0], args[1]);
};
}
Β
function : DescendDir(path : String, pattern : String) ~ Nil {
files := Directory->List(path);
each(i : files) {
file := files[i];
if(<>file->StartsWith('.')) {
dir_path := String->New(path);
dir_path += '/';
dir_path += file;
Β
if(Directory->Exists(dir_path)) {
DescendDir(dir_path, pattern);
}
else if(File->Exists(dir_path) & dir_path->EndsWith(pattern)) {
dir_path->PrintLine();
};
};
};
}
} |
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ββ 9 ββ
8 ββ 8 ββ
7 ββ ββ 7 ββββββββββββ
6 ββ ββ ββ 6 ββββββββββββ
5 ββ ββ ββ ββββ 5 ββββββββββββββββ
4 ββ ββ ββββββββ 4 ββββββββββββββββ
3 ββββββ ββββββββ 3 ββββββββββββββββ
2 ββββββββββββββββ ββ 2 ββββββββββββββββββββ
1 ββββββββββββββββββββ 1 ββββββββββββββββββββ
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
Four Solutions to a Trivial Problem β a Google Tech Talk by Guy Steele
Water collected between towers on Stack Overflow, from which the example above is taken)
An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| #Phix | Phix | with javascript_semantics
function collect_water(sequence heights)
integer res = 0
for i=2 to length(heights)-1 do
integer lm = max(heights[1..i-1]),
rm = max(heights[i+1..$]),
d = min(lm,rm)-heights[i]
res += max(0,d)
end for
return res
end function
constant tests = {{1,5,3,7,2},
{5,3,7,2,6,4,5,9,1,2},
{2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1},
{5,5,5,5},
{5,6,7,8},
{8,7,7,6},
{6,7,10,7,6}}
for i=1 to length(tests) do
sequence ti = tests[i]
printf(1,"%35sΒ :Β %d\n",{sprint(ti),collect_water(ti)})
end for
|
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
| #Action.21 | Action! | TYPE Vector=[INT x,y,z]
Β
PROC CreateVector(INT vx,vy,vz Vector POINTER v)
v.x=vx v.y=vy v.z=vz
RETURN
Β
PROC PrintVector(Vector POINTER v)
PrintF("(%I,%I,%I)",v.x,v.y,v.z)
RETURN
Β
INT FUNC DotProduct(Vector POINTER v1,v2)
INT res
Β
res=v1.x*v2.x Β ;calculation split into parts
res==+v1.y*v2.y Β ;otherwise incorrect result
res==+v1.z*v2.z Β ;is returned
RETURN (res)
Β
PROC CrossProduct(Vector POINTER v1,v2,res)
res.x=v1.y*v2.z Β ;calculation split into parts
res.x==-v1.z*v2.y Β ;otherwise incorrect result
res.y=v1.z*v2.x Β ;is returned
res.y==-v1.x*v2.z
res.z=v1.x*v2.y
res.z==-v1.y*v2.x
RETURN
Β
PROC Main()
Vector a,b,c,d,e
INT res
Β
CreateVector(3,4,5,a)
CreateVector(4,3,5,b)
CreateVector(-5,-12,-13,c)
Β
Print("a=") PrintVector(a) PutE()
Print("b=") PrintVector(b) PutE()
Print("c=") PrintVector(c) PutE()
PutE()
Β
res=DotProduct(a,b)
PrintF("a.b=%I%E",res)
Β
CrossProduct(a,b,d)
Print("axb=") PrintVector(d) PutE()
Β
CrossProduct(b,c,d)
res=DotProduct(a,d)
PrintF("a.(bxc)=%I%E",res)
Β
CrossProduct(b,c,d)
CrossProduct(a,d,e)
Print("ax(bxc)=") PrintVector(e) PutE()
RETURN |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #Python | Python | from collections import Counter
from pprint import pprint as pp
Β
def distcheck(fn, repeats, delta):
'''\
Bin the answers to fn() and check bin counts are within +/- deltaΒ %
of repeats/bincount'''
bin = Counter(fn() for i in range(repeats))
target = repeats // len(bin)
deltacount = int(delta / 100. * target)
assert all( abs(target - count) < deltacount
for count in bin.values() ), "Bin distribution skewed fromΒ %i +/-Β %i:Β %s"Β % (
target, deltacount, [ (key, target - count)
for key, count in sorted(bin.items()) ]
)
pp(dict(bin)) |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #Quackery | Quackery | [ stack [ 0 0 0 0 0 0 0 ] ] is bins ( --> s )
Β
[ 7 times
[ 0 bins take
i poke
bins put ] ] is emptybins ( --> )
Β
[ bins share over peek
1+ bins take rot poke
bins put ] is bincrement ( n --> )
Β
[ emptybins
over 7 / temp put
swap times
[ over do 1 -
bincrement ]
bins share dup echo cr
witheach
[ temp share - abs
over > if
[ say "Number of "
i^ 1+ echo
say "s is sketchy."
cr ] ]
2drop temp release ] is distribution ( x n n --> ) |
http://rosettacode.org/wiki/Variable-length_quantity | Variable-length quantity | Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte);
display these sequences of octets;
convert these sequences of octets back to numbers, and check that they are equal to original numbers.
| #Groovy | Groovy | final RADIX = 7
final MASK = 2**RADIX - 1
Β
def octetify = { n ->
def octets = []
for (def i = n; i != 0; i >>>= RADIX) {
octets << ((byte)((i & MASK) + (octets.empty ? 0Β : MASK + 1)))
}
octets.reverse()
}
Β
def deoctetify = { octets ->
octets.inject(0) { long n, octet ->
(n << RADIX) + ((int)(octet) & MASK)
}
} |
http://rosettacode.org/wiki/Variable-length_quantity | Variable-length quantity | Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte);
display these sequences of octets;
convert these sequences of octets back to numbers, and check that they are equal to original numbers.
| #Haskell | Haskell | import Numeric (readOct, showOct)
import Data.List (intercalate)
Β
to :: Int -> String
to = flip showOct ""
Β
from :: String -> Int
from = fst . head . readOct
Β
main :: IO ()
main =
mapM_
(putStrLn .
intercalate " <-> " . (pure (:) <*> to <*> (return . show . from . to)))
[2097152, 2097151] |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Β Call a function
| #BaCon | BaCon | ' Variadic functions
OPTION BASE 1
SUB demo (VAR arg$ SIZE argc)
LOCAL x
PRINT "Amount of incoming arguments: ", argc
FOR x = 1 TO argc
PRINT arg$[x]
NEXT
END SUB
Β
' No argument
demo(0)
' One argument
demo("abc")
' Three arguments
demo("123", "456", "789") |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Β Call a function
| #BASIC | BASIC | SUB printAll cdecl (count As Integer, ... )
DIM arg AS Any Ptr
DIM i AS Integer
Β
arg = va_first()
FOR i = 1 To count
PRINT va_arg(arg, Double)
arg = va_next(arg, Double)
NEXT i
END SUB
Β
printAll 3, 3.1415, 1.4142, 2.71828 |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #11l | 11l | Int64 i
print(T(i).size)
print(Int64.size) |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #F.23 | F# | open System
Β
let add (ax, ay) (bx, by) =
(ax+bx, ay+by)
Β
let sub (ax, ay) (bx, by) =
(ax-bx, ay-by)
Β
let mul (ax, ay) c =
(ax*c, ay*c)
Β
let div (ax, ay) c =
(ax/c, ay/c)
Β
[<EntryPoint>]
let main _ =
let a = (5.0, 7.0)
let b = (2.0, 3.0)
Β
printfn "%A" (add a b)
printfn "%A" (sub a b)
printfn "%A" (mul a 11.0)
printfn "%A" (div a 2.0)
0 // return an integer exit code |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #Factor | Factor | (scratchpad) USE: math.vectors
(scratchpad) { 1 2 } { 3 4 } v+
Β
--- Data stack:
{ 4 6 } |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #Perl | Perl | with javascript_semantics
requires("1.0.0")
include mpfr.e
mpfr pi = mpfr_init(0,-121) -- 120 dp, +1 for the "3."
mpfr_const_pi(pi)
printf(1,"PI with 120 decimals:Β %s\n\n",mpfr_get_fixed(pi,120))
|
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #Phix | Phix | with javascript_semantics
requires("1.0.0")
include mpfr.e
mpfr pi = mpfr_init(0,-121) -- 120 dp, +1 for the "3."
mpfr_const_pi(pi)
printf(1,"PI with 120 decimals:Β %s\n\n",mpfr_get_fixed(pi,120))
|
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #PicoLisp | PicoLisp | Β
declare i fixed binary (7), /* occupies 1 byte */
j fixed binary (15), /* occupies 2 bytes */
k fixed binary (31), /* occupies 4 bytes */
l fixed binary (63); /* occupies 8 bytes */
Β
declare d fixed decimal (1), /* occupies 1 byte */
e fixed decimal (3), /* occupies 2 bytes */
/* an so on ... */
f fixed decimal (15); /* occupies 8 bytes */
Β
declare b(16) bit (1) unaligned; /* occupies 2 bytes */
declare c(16) bit (1) aligned; /* occupies 16 bytes */
Β
declare x float decimal (6), /* occupies 4 bytes */
y float decimal (16), /* occupies 8 bytes */
z float decimal (33); /* occupies 16 bytes */
Β |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "draw.s7i";
include "keybd.s7i";
Β
const type: point is new struct
var integer: xPos is 0;
var integer: yPos is 0;
var color: col is black;
end struct;
Β
const proc: generateVoronoiDiagram (in integer: width, in integer: height, in integer: numCells) is func
local
var array point: points is 0 times point.value;
var integer: index is 0;
var integer: x is 0;
var integer: y is 0;
var integer: distSquare is 0;
var integer: minDistSquare is 0;
var integer: indexOfNearest is 0;
begin
screen(width, height);
pointsΒ := numCells times point.value;
for index range 1 to numCells do
points[index].xPosΒ := rand(0, width);
points[index].yPosΒ := rand(0, height);
points[index].colΒ := color(rand(0, 65535), rand(0, 65535), rand(0, 65535));
end for;
for y range 0 to height do
for x range 0 to width do
minDistSquareΒ := width ** 2 + height ** 2;
for index range 1 to numCells do
distSquareΒ := (points[index].xPos - x) ** 2 + (points[index].yPos - y) ** 2;
if distSquare < minDistSquare then
minDistSquareΒ := distSquare;
indexOfNearestΒ := index;
end if;
end for;
point(x, y, points[indexOfNearest].col);
end for;
end for;
for index range 1 to numCells do
line(points[index].xPos - 2, points[index].yPos, 4, 0, black);
line(points[index].xPos, points[index].yPos - 2, 0, 4, black);
end for;
end func;
Β
const proc: main is func
begin
generateVoronoiDiagram(500, 500, 25);
KEYBOARDΒ := GRAPH_KEYBOARD;
readln(KEYBOARD);
end func; |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #Sidef | Sidef | require('Imager')
Β
func generate_voronoi_diagram(width, height, num_cells) {
var img = %O<Imager>.new(xsize => width, ysize => height)
var (nx,ny,nr,ng,nb) = 5.of { [] }...
Β
for i in (^num_cells) {
nx << rand(^width)
ny << rand(^height)
nr << rand(^256)
ng << rand(^256)
nb << rand(^256)
}
Β
for y=(^height), x=(^width) {
var j = (^num_cells -> min_by {|i| hypot(nx[i]-x, ny[i]-y) })
img.setpixel(x => x, y => y, color => [nr[j], ng[j], nb[j]])
}
return img
}
Β
var img = generate_voronoi_diagram(500, 500, 25)
img.write(file => 'VoronoiDiagram.png') |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test | Verify distribution uniformity/Chi-squared test | Task
Write a function to verify that a given distribution of values is uniform by using the
Ο
2
{\displaystyle \chi ^{2}}
test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%).
The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce.
Reference
Β an entry at the MathWorld website: Β chi-squared distribution.
| #Python | Python | import math
import random
Β
def GammaInc_Q( a, x):
a1 = a-1
a2 = a-2
def f0( t ):
return t**a1*math.exp(-t)
Β
def df0(t):
return (a1-t)*t**a2*math.exp(-t)
Β
y = a1
while f0(y)*(x-y) >2.0e-8 and y < x: y += .3
if y > x: y = x
Β
h = 3.0e-4
n = int(y/h)
h = y/n
hh = 0.5*h
gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1)))
Β
return gamax/gamma_spounge(a)
Β
c = None
def gamma_spounge( z):
global c
a = 12
Β
if c is None:
k1_factrl = 1.0
c = []
c.append(math.sqrt(2.0*math.pi))
for k in range(1,a):
c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl )
k1_factrl *= -k
Β
accm = c[0]
for k in range(1,a):
accm += c[k] / (z+k)
accm *= math.exp( -(z+a)) * (z+a)**(z+0.5)
return accm/z;
Β
def chi2UniformDistance( dataSet ):
expected = sum(dataSet)*1.0/len(dataSet)
cntrd = (d-expected for d in dataSet)
return sum(x*x for x in cntrd)/expected
Β
def chi2Probability(dof, distance):
return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance)
Β
def chi2IsUniform(dataSet, significance):
dof = len(dataSet)-1
dist = chi2UniformDistance(dataSet)
return chi2Probability( dof, dist ) > significance
Β
dset1 = [ 199809, 200665, 199607, 200270, 199649 ]
dset2 = [ 522573, 244456, 139979, 71531, 21461 ]
Β
for ds in (dset1, dset2):
print "Data set:", ds
dof = len(ds)-1
distance =chi2UniformDistance(ds)
print "dof:Β %d distance:Β %.4f"Β % (dof, distance),
prob = chi2Probability( dof, distance)
print "probability:Β %.4f"%prob,
print "uniform? ", "Yes"if chi2IsUniform(ds,0.05) else "No" |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a  Vigenère cypher,  both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Β Caesar cipher
Β Rot-13
Β Substitution Cipher
| #Java | Java | public class VigenereCipher {
public static void main(String[] args) {
String key = "VIGENERECIPHER";
String ori = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
String enc = encrypt(ori, key);
System.out.println(enc);
System.out.println(decrypt(enc, key));
}
Β
static String encrypt(String text, final String key) {
String res = "";
text = text.toUpperCase();
for (int i = 0, j = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c < 'A' || c > 'Z') continue;
res += (char)((c + key.charAt(j) - 2 * 'A') % 26 + 'A');
j = ++j % key.length();
}
return res;
}
Β
static String decrypt(String text, final String key) {
String res = "";
text = text.toUpperCase();
for (int i = 0, j = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c < 'A' || c > 'Z') continue;
res += (char)((c - key.charAt(j) + 26) % 26 + 'A');
j = ++j % key.length();
}
return res;
}
} |
http://rosettacode.org/wiki/Visualize_a_tree | Visualize a tree | A tree structure Β (i.e. a rooted, connected acyclic graph) Β is often used in programming.
It's often helpful to visually examine such a structure.
There are many ways to represent trees to a reader, such as:
Β indented text Β (Γ la unix tree command)
Β nested HTML tables
Β hierarchical GUI widgets
Β 2D Β or Β 3D Β images
Β etc.
Task
Write a program to produce a visual representation of some tree.
The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly.
Make do with the vague term "friendly" the best you can.
| #Perl | Perl | #!/usr/bin/perl
use warnings;
use strict;
use utf8;
use open OUT => ':utf8', ':std';
Β
sub parse {
my ($tree) = shift;
if (my ($root, $children) = $tree =~ /^(.+?)\((.*)\)$/) {
Β
my $depth = 0;
for my $pos (0 .. length($children) - 1) {
my $char = \substr $children, $pos, 1;
if (0 == $depth and ',' eq $$char) {
$$char = "\x0";
} elsif ('(' eq $$char) {
$depth++;
} elsif (')' eq $$char) {
$depth--;
}
}
return($root, [map parse($_), split /\x0/, $children]);
Β
} else { # Leaf.
return $tree;
}
}
Β
sub output {
my ($parsed, $prefix) = @_;
my $is_root = not defined $prefix;
$prefix //= ' ';
while (my $member = shift @$parsed) {
my $last = !@$parsed || (1 == @$parsed and ref $parsed->[0]);
unless ($is_root) {
substr $prefix, -3, 1, ' ';
substr($prefix, -4, 1) =~ s/β/β/;
substr $prefix, -2, 1, ref $member ? ' ' : 'β' if $last;
}
Β
if (ref $member) {
output($member, $prefix . 'ββ');
} else {
print $prefix, $member, "\n";
}
}
}
Β
my $tree = 'a(b0(c1,c2(d(ef,gh)),c3(i1,i2,i3(jj),i4(kk,m))),b1(C1,C2(D1(E),D2,D3),C3))';
my $parsed = [parse($tree)];
output($parsed); |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #Toka | Toka | needs shell
" ." " .\\.txt$" dir.listByPattern |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #TUSCRIPT | TUSCRIPT | $$ MODE TUSCRIPT
files=FILE_NAMES (+,-std-)
fileswtxt= FILTER_INDEX (files,":*.txt:",-)
txtfiles= SELECT (files,#fileswtxt) |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. Β These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Β Walk a directory/Non-recursively Β (read a single directory).
| #Objective-C | Objective-C | NSString *dir = NSHomeDirectory();
NSDirectoryEnumerator *de = [[NSFileManager defaultManager] enumeratorAtPath:dir];
Β
for (NSString *file in de)
if ([[file pathExtension] isEqualToString:@"mp3"])
NSLog(@"%@", file); |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. Β These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Β Walk a directory/Non-recursively Β (read a single directory).
| #OCaml | OCaml | #!/usr/bin/env ocaml
#load "unix.cma"
#load "str.cma"
open Unix
Β
let walk_directory_tree dir pattern =
let re = Str.regexp pattern in (* pre-compile the regexp *)
let select str = Str.string_match re str 0 in
let rec walk acc = function
| [] -> (acc)
| dir::tail ->
let contents = Array.to_list (Sys.readdir dir) in
let contents = List.rev_map (Filename.concat dir) contents in
let dirs, files =
List.fold_left (fun (dirs,files) f ->
match (stat f).st_kind with
| S_REG -> (dirs, f::files) (* Regular file *)
| S_DIR -> (f::dirs, files) (* Directory *)
| _ -> (dirs, files)
) ([],[]) contents
in
let matched = List.filter (select) files in
walk (matched @ acc) (dirs @ tail)
in
walk [] [dir]
;;
Β
let () =
let results = walk_directory_tree "/usr/local/lib/ocaml" ".*\\.cma" in
List.iter print_endline results;
;; |
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ββ 9 ββ
8 ββ 8 ββ
7 ββ ββ 7 ββββββββββββ
6 ββ ββ ββ 6 ββββββββββββ
5 ββ ββ ββ ββββ 5 ββββββββββββββββ
4 ββ ββ ββββββββ 4 ββββββββββββββββ
3 ββββββ ββββββββ 3 ββββββββββββββββ
2 ββββββββββββββββ ββ 2 ββββββββββββββββββββ
1 ββββββββββββββββββββ 1 ββββββββββββββββββββ
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
Four Solutions to a Trivial Problem β a Google Tech Talk by Guy Steele
Water collected between towers on Stack Overflow, from which the example above is taken)
An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| #Phixmonti | Phixmonti | include ..\Utilitys.pmt
Β
def collect_water
0 var res
len 1 - 2 swap 2 tolist
for
var i
1 i 1 - slice max >ps
len i - 1 + i swap slice max >ps
i get ps> ps> min swap -
0 max res + var res
endfor
drop
res
enddef
Β
( ( 1 5 3 7 2 )
( 5 3 7 2 6 4 5 9 1 2 )
( 2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1 )
( 5 5 5 5 )
( 5 6 7 8 )
( 8 7 7 6 )
( 6 7 10 7 6 ) )
Β
len for
get dup print "Β : " print collect_waterΒ ?
endfor |
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
| #Ada | Ada | with Ada.Text_IO;
Β
procedure Vector is
type Float_Vector is array (Positive range <>) of Float;
package Float_IO is new Ada.Text_IO.Float_IO (Float);
Β
procedure Vector_Put (XΒ : Float_Vector) is
begin
Ada.Text_IO.Put ("(");
for I in X'Range loop
Float_IO.Put (X (I), Aft => 1, Exp => 0);
if I /= X'Last then
Ada.Text_IO.Put (", ");
end if;
end loop;
Ada.Text_IO.Put (")");
end Vector_Put;
Β
-- cross product
function "*" (Left, RightΒ : Float_Vector) return Float_Vector is
begin
if Left'Length /= Right'Length then
raise Constraint_Error with "vectors of different size in dot product";
end if;
if Left'Length /= 3 then
raise Constraint_Error with "dot product only implemented for R**3";
end if;
return Float_Vector'(Left (Left'First + 1) * Right (Right'First + 2) -
Left (Left'First + 2) * Right (Right'First + 1),
Left (Left'First + 2) * Right (Right'First) -
Left (Left'First) * Right (Right'First + 2),
Left (Left'First) * Right (Right'First + 1) -
Left (Left'First + 1) * Right (Right'First));
end "*";
Β
-- scalar product
function "*" (Left, RightΒ : Float_Vector) return Float is
ResultΒ : FloatΒ := 0.0;
I, JΒ : Positive;
begin
if Left'Length /= Right'Length then
raise Constraint_Error with "vectors of different size in scalar product";
end if;
IΒ := Left'First; JΒ := Right'First;
while I <= Left'Last and then J <= Right'Last loop
ResultΒ := Result + Left (I) * Right (J);
IΒ := I + 1; JΒ := J + 1;
end loop;
return Result;
end "*";
Β
-- stretching
function "*" (LeftΒ : Float_Vector; RightΒ : Float) return Float_Vector is
ResultΒ : Float_Vector (Left'Range);
begin
for I in Left'Range loop
Result (I)Β := Left (I) * Right;
end loop;
return Result;
end "*";
Β
AΒ : constant Float_VectorΒ := (3.0, 4.0, 5.0);
BΒ : constant Float_VectorΒ := (4.0, 3.0, 5.0);
CΒ : constant Float_VectorΒ := (-5.0, -12.0, -13.0);
begin
Ada.Text_IO.Put ("A: "); Vector_Put (A); Ada.Text_IO.New_Line;
Ada.Text_IO.Put ("B: "); Vector_Put (B); Ada.Text_IO.New_Line;
Ada.Text_IO.Put ("C: "); Vector_Put (C); Ada.Text_IO.New_Line;
Ada.Text_IO.New_Line;
Ada.Text_IO.Put ("A dot B = "); Float_IO.Put (A * B, Aft => 1, Exp => 0);
Ada.Text_IO.New_Line;
Ada.Text_IO.Put ("A x B = "); Vector_Put (A * B);
Ada.Text_IO.New_Line;
Ada.Text_IO.Put ("A dot (B x C) = "); Float_IO.Put (A * (B * C), Aft => 1, Exp => 0);
Ada.Text_IO.New_Line;
Ada.Text_IO.Put ("A x (B x C) = "); Vector_Put (A * Float_Vector'(B * C));
Ada.Text_IO.New_Line;
end Vector; |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #R | R | distcheck <- function(fn, repetitions=1e4, delta=3)
{
if(is.character(fn))
{
fn <- get(fn)
}
if(!is.function(fn))
{
stop("fn is not a function")
}
samp <- fn(n=repetitions)
counts <- table(samp)
expected <- repetitions/length(counts)
lbound <- expected * (1 - 0.01*delta)
ubound <- expected * (1 + 0.01*delta)
status <- ifelse(counts < lbound, "under",
ifelse(counts > ubound, "over", "okay"))
data.frame(value=names(counts), counts=as.vector(counts), status=status)
}
distcheck(dice7.vec) |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #Racket | Racket | #lang racket
(define (pretty-fraction f)
(if (integer? f) f
(let* ((d (denominator f)) (n (numerator f)) (q (quotient n d)) (r (remainder n d)))
(format "~a ~a" q (/ r d)))))
Β
(define (test-uniformity/naive r n Ξ΄)
(define observation (make-hash))
(for ((_ (in-range n))) (hash-update! observation (r) add1 0))
(define target (/ n (hash-count observation)))
(define max-skew (* n Ξ΄ 1/100))
(define (skewed? v)
(> (abs (- v target)) max-skew))
(let/ec ek
(cons
#t
(for/list ((k (sort (hash-keys observation) <)))
(define v (hash-ref observation k))
(when (skewed? v)
(ek (cons
#f
(format "~a distribution of ~s potentially skewed for ~a. expected ~a got ~a"
'test-uniformity/naive r k (pretty-fraction target) v))))
(cons k v)))))
Β
(define (straight-die)
(min 6 (add1 (random 6))))
Β
(define (crooked-die)
(min 6 (add1 (random 7))))
Β
; Test whether the builtin generator is uniform:
(test-uniformity/naive (curry random 10) 1000 5)
; Test whether a straight die is uniform:
(test-uniformity/naive straight-die 1000 5)
; Test whether a biased die fails:
(test-uniformity/naive crooked-die 1000 5) |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #Raku | Raku | my $d7 = 1..7;
sub roll7 { $d7.roll };
Β
my $threshold = 3;
Β
for 14, 105, 1001, 10003, 100002, 1000006 -> $n
{ dist( $n, $threshold, &roll7 ) };
Β
Β
sub dist ( $n is copy, $threshold, &producer ) {
my @dist;
my $expect = $n / 7;
say "Expect\t",$expect.fmt("%.3f");
Β
loop ($_ = $n; $n; --$n) { @dist[&producer()]++; }
Β
for @dist.kv -> $i, $v is copy {
next unless $i;
$v //= 0;
my $pct = ($v - $expect)/$expect*100;
printf "%d\t%d\t%+.2f%%Β %s\n", $i, $v, $pct,
($pct.abs > $threshold ?? '- skewed' !! '');
}
say '';
} |
http://rosettacode.org/wiki/Variable-length_quantity | Variable-length quantity | Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte);
display these sequences of octets;
convert these sequences of octets back to numbers, and check that they are equal to original numbers.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
every i := 2097152 | 2097151 | 1 | 127 | 128 | 589723405834 | 165 | 256 do
write(image(i)," = ",string2hex(v := uint2vlq(i))," = ",vlq2uint(v))
end
Β
procedure vlq2uint(s) #: decode a variable length quantity
if *s > 0 then {
i := 0
s ? while h := ord(move(1)) do {
if (pos(0) & h > 128) | (not pos(0) & h < 128) then fail
i := 128 * i + h % 128
}
return i
}
end
Β
procedure uint2vlq(i,c) #: encode a whole number as a variable length quantity
if "integer" == type(-1 < i) then
return if i = 0 then
char((/c := 0)) | ""
else
uint2vlq(i/128,1) || char((i % 128) + ((/c := 0) | 128) )
end
Β
procedure string2hex(s) #: convert a string to hex
h := ""
every i := ord(!s) do
h ||:= "0123456789abcdef"[i/16+1] || "0123456789abcdef"[i%16+1]
return h
end |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Β Call a function
| #Batch_File | Batch File | Β
@echo off
Β
:_main
call:_variadicfunc arg1 "arg 2" arg-3
pause>nul
Β
:_variadicfunc
setlocal
for %%i in (%*) do echo %%~i
exit /b
:: Note: if _variadicfunc was called from cmd.exe with arguments parsed to it, it would only need to contain:
:: @forΒ %%i in (%*) do echoΒ %%i
Β |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Β Call a function
| #bc | bc | /* Version a */
define f(a[], l) {
auto i
for (i = 0; i < l; i++) a[i]
}
Β
/* Version b */
define g(a[]) {
auto i
for (i = 0; a[i]Β != -1; i++) a[i]
}
Β
/* Version c */
define h(a[]) {
auto i
Β
for (i = 1; i <= a[0]; i++) a[i]
} |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #ActionScript | ActionScript | Β
package {
Β
import flash.display.Sprite;
import flash.events.Event;
import flash.sampler.getSize;
Β
public class VariableSizeGet extends Sprite {
Β
public function VariableSizeGet() {
if ( stage ) _init();
else addEventListener(Event.ADDED_TO_STAGE, _init);
}
Β
private function _init(e:Event = null):void {
Β
var i:int = 1;
var n:Number = 0.5;
var s:String = "abc";
var b:Boolean = true;
var date:Date = new Date();
Β
trace("An int contains " + getSize(i) + " bytes."); // 4
trace("A Number contains " + getSize(n) + " bytes."); // 8
trace("The string 'abc' contains " + getSize(s) + " bytes."); // 24
trace("A Boolean contains " + getSize(b) + " bytes."); // 4
trace("A Date object contains " + getSize(date) + " bytes."); // 48
Β
}
Β
}
Β
}
Β |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Ada | Ada | Int_BitsΒ : constant IntegerΒ := Integer'size;
Whole_BytesΒ : constant IntegerΒ := Int_Bits / Storage_Unit; -- Storage_Unit is the number of bits per storage element |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #Forth | Forth | : v. swap . .Β ;
: v* swap over * >r * r>Β ;
: v/ swap over / >r / r>Β ;
: v+ >r swap >r + r> r> +Β ;
: v- >r swap >r - r> r> -Β ; |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #Fortran | Fortran | MODULE ROSETTA_VECTOR
IMPLICIT NONE
Β
TYPE VECTOR
REAL :: X, Y
END TYPE VECTOR
Β
Β
INTERFACE OPERATOR(+)
MODULE PROCEDURE VECTOR_ADD
END INTERFACE
Β
INTERFACE OPERATOR(-)
MODULE PROCEDURE VECTOR_SUB
END INTERFACE
Β
INTERFACE OPERATOR(/)
MODULE PROCEDURE VECTOR_DIV
END INTERFACE
Β
INTERFACE OPERATOR(*)
MODULE PROCEDURE VECTOR_MULT
END INTERFACE
Β
CONTAINS
Β
FUNCTION VECTOR_ADD(VECTOR_1, VECTOR_2)
TYPE(VECTOR), INTENT(IN) :: VECTOR_1, VECTOR_2
TYPE(VECTOR) :: VECTOR_ADD
VECTOR_ADD%X = VECTOR_1%X+VECTOR_2%X
VECTOR_ADD%Y = VECTOR_1%Y+VECTOR_2%Y
END FUNCTION VECTOR_ADD
Β
FUNCTION VECTOR_SUB(VECTOR_1, VECTOR_2)
TYPE(VECTOR), INTENT(IN) :: VECTOR_1, VECTOR_2
TYPE(VECTOR) :: VECTOR_SUB
VECTOR_SUB%X = VECTOR_1%X-VECTOR_2%X
VECTOR_SUB%Y = VECTOR_1%Y-VECTOR_2%Y
END FUNCTION VECTOR_SUB
Β
FUNCTION VECTOR_DIV(VEC, SCALAR)
TYPE(VECTOR), INTENT(IN) :: VEC
REAL, INTENT(IN) :: SCALAR
TYPE(VECTOR) :: VECTOR_DIV
VECTOR_DIV%X = VEC%X/SCALAR
VECTOR_DIV%Y = VEC%Y/SCALAR
END FUNCTION VECTOR_DIV
Β
FUNCTION VECTOR_MULT(VEC, SCALAR)
TYPE(VECTOR), INTENT(IN) :: VEC
REAL, INTENT(IN) :: SCALAR
TYPE(VECTOR) :: VECTOR_MULT
VECTOR_MULT%X = VEC%X*SCALAR
VECTOR_MULT%Y = VEC%Y*SCALAR
END FUNCTION VECTOR_MULT
Β
FUNCTION FROM_RTHETA(R, THETA)
REAL :: R, THETA
TYPE(VECTOR) :: FROM_RTHETA
FROM_RTHETA%X = R*SIN(THETA)
FROM_RTHETA%Y = R*COS(THETA)
END FUNCTION FROM_RTHETA
Β
FUNCTION FROM_XY(X, Y)
REAL :: X, Y
TYPE(VECTOR) :: FROM_XY
FROM_XY%X = X
FROM_XY%Y = Y
END FUNCTION FROM_XY
Β
FUNCTION PRETTY_PRINT(VEC)
TYPE(VECTOR), INTENT(IN) :: VEC
CHARACTER(LEN=100) PRETTY_PRINT
WRITE(PRETTY_PRINT,"(A, F0.5, A, F0.5, A)") "[", VEC%X, ", ", VEC%Y, "]"
END FUNCTION PRETTY_PRINT
END MODULE ROSETTA_VECTOR
Β
PROGRAM VECTOR_DEMO
USE ROSETTA_VECTOR
IMPLICIT NONE
Β
TYPE(VECTOR) :: VECTOR_1, VECTOR_2
REAL, PARAMETER :: PI = 4*ATAN(1.0)
REAL :: SCALAR
Β
SCALAR = 2.0
Β
VECTOR_1 = FROM_XY(2.0, 3.0)
VECTOR_2 = FROM_RTHETA(2.0, PI/6.0)
Β
WRITE(*,*) "VECTOR_1 (X: 2.0, Y: 3.0) Β : ", PRETTY_PRINT(VECTOR_1)
WRITE(*,*) "VECTOR_2 (R: 2.0, THETA: PI/6)Β : ", PRETTY_PRINT(VECTOR_2)
WRITE(*,*) NEW_LINE('A')
WRITE(*,*) "VECTOR_1 + VECTOR_2 = ", PRETTY_PRINT(VECTOR_1+VECTOR_2)
WRITE(*,*) "VECTOR_1 - VECTOR_2 = ", PRETTY_PRINT(VECTOR_1-VECTOR_2)
WRITE(*,*) "VECTOR_1 / 2.0 = ", PRETTY_PRINT(VECTOR_1/SCALAR)
WRITE(*,*) "VECTOR_1 * 2.0 = ", PRETTY_PRINT(VECTOR_1*SCALAR)
END PROGRAM VECTOR_DEMO |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #PL.2FI | PL/I | Β
declare i fixed binary (7), /* occupies 1 byte */
j fixed binary (15), /* occupies 2 bytes */
k fixed binary (31), /* occupies 4 bytes */
l fixed binary (63); /* occupies 8 bytes */
Β
declare d fixed decimal (1), /* occupies 1 byte */
e fixed decimal (3), /* occupies 2 bytes */
/* an so on ... */
f fixed decimal (15); /* occupies 8 bytes */
Β
declare b(16) bit (1) unaligned; /* occupies 2 bytes */
declare c(16) bit (1) aligned; /* occupies 16 bytes */
Β
declare x float decimal (6), /* occupies 4 bytes */
y float decimal (16), /* occupies 8 bytes */
z float decimal (33); /* occupies 16 bytes */
Β |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #PureBasic | PureBasic | Β
EnableExplicit
Β
Structure AllTypes
b.b
a.a
w.w
u.u
c.c ; character typeΒ : 1 byte on x86, 2 bytes on x64
l.l
i.i ; integer typeΒ : 4 bytes on x86, 8 bytes on x64
q.q
f.f
d.d
s.s ; pointer to string on heapΒ : pointer size same as integer
z.s{2} ; fixed length string of 2 characters, stored inline
EndStructure
Β
If OpenConsole()
Define at.AllTypes
PrintN("Size of types in bytes (x64)")
PrintN("")
PrintN("byte = " + SizeOf(at\b))
PrintN("ascii = " + SizeOf(at\a))
PrintN("word = " + SizeOf(at\w))
PrintN("unicode = " + SizeOf(at\u))
PrintN("character = " + SizeOf(at\c))
PrintN("long = " + SizeOf(at\l))
PrintN("integer = " + SizeOf(at\i))
PrintN("quod = " + SizeOf(at\q))
PrintN("float = " + SizeOf(at\f))
PrintN("double = " + SizeOf(at\d))
PrintN("string = " + SizeOf(at\s))
PrintN("string{2} = " + SizeOf(at\z))
PrintN("---------------")
PrintN("AllTypes = " + SizeOf(at))
PrintN("")
PrintN("Press any key to close the console")
Repeat: Delay(10)Β : Until Inkey() <> ""
CloseConsole()
EndIf
Β
Β |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #Tcl | Tcl | package require Tk
proc r to {expr {int(rand()*$to)}}; # Simple helper
Β
proc voronoi {photo pointCount} {
for {set i 0} {$i < $pointCount} {incr i} {
lappend points [r [image width $photo]] [r [image height $photo]]
}
foreach {x y} $points {
lappend colors [format "#%02x%02x%02x" [r 256] [r 256] [r 256]]
}
set initd [expr {[image width $photo] + [image height $photo]}]
for {set i 0} {$i < [image width $photo]} {incr i} {
for {set j 0} {$j < [image height $photo]} {incr j} {
set color black
set d $initd
foreach {x y} $points c $colors {
set h [expr {hypot($x-$i,$y-$j)}]
### Other interesting metrics
#set h [expr {abs($x-$i)+abs($y-$j)}]
#set h [expr {(abs($x-$i)**3+abs($y-$j)**3)**0.3}]
if {$d > $h} {set d $h;set color $c}
}
$photo put $color -to $i $j
}
# To display while generating, uncomment this line and the other one so commented
#if {$i%4==0} {update idletasks}
}
}
Β
# Generate a 600x400 Voronoi diagram with 60 random points
image create photo demo -width 600 -height 400
pack [label .l -image demo]
# To display while generating, uncomment this line and the other one so commented
#update
voronoi demo 60 |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test | Verify distribution uniformity/Chi-squared test | Task
Write a function to verify that a given distribution of values is uniform by using the
Ο
2
{\displaystyle \chi ^{2}}
test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%).
The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce.
Reference
Β an entry at the MathWorld website: Β chi-squared distribution.
| #R | R | Β
dset1=c(199809,200665,199607,200270,199649)
dset2=c(522573,244456,139979,71531,21461)
Β
chi2IsUniform<-function(dataset,significance=0.05){
chi2IsUniform=(chisq.test(dataset)$p.value>significance)
}
Β
for (ds in list(dset1,dset2)){
print(c("Data set:",ds))
print(chisq.test(ds))
print(paste("uniform?",chi2IsUniform(ds)))
}
Β |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a  Vigenère cypher,  both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Β Caesar cipher
Β Rot-13
Β Substitution Cipher
| #JavaScript | JavaScript | // helpers
// helper
function ordA(a) {
return a.charCodeAt(0) - 65;
}
Β
// vigenere
function vigenere(text, key, decode) {
var i = 0, b;
key = key.toUpperCase().replace(/[^A-Z]/g, '');
return text.toUpperCase().replace(/[^A-Z]/g, '').replace(/[A-Z]/g, function(a) {
b = key[i++ % key.length];
return String.fromCharCode(((ordA(a) + (decode ? 26 - ordA(b) : ordA(b))) % 26 + 65));
});
}
Β
// example
var text = "The quick brown fox Jumped over the lazy Dog the lazy dog lazy dog dog";
var key = 'alex';
var enc = vigenere(text,key);
var dec = vigenere(enc,key,true);
Β
console.log(enc);
console.log(dec); |
http://rosettacode.org/wiki/Visualize_a_tree | Visualize a tree | A tree structure Β (i.e. a rooted, connected acyclic graph) Β is often used in programming.
It's often helpful to visually examine such a structure.
There are many ways to represent trees to a reader, such as:
Β indented text Β (Γ la unix tree command)
Β nested HTML tables
Β hierarchical GUI widgets
Β 2D Β or Β 3D Β images
Β etc.
Task
Write a program to produce a visual representation of some tree.
The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly.
Make do with the vague term "friendly" the best you can.
| #Phix | Phix | --
-- demo\rosetta\VisualiseTree.exw
--
with javascript_semantics
-- To the theme tune of the Milk Tray Ad iyrt,
-- All because the Windows console hates utf8:
constant TL = '\#DA', -- aka 'β'
VT = '\#B3', -- aka 'β'
BL = '\#C0', -- aka 'β'
HZ = '\#C4', -- aka 'β'
HS = "\#C4" -- (string version of HZ)
function w1252_to_utf8(string s)
if platform()!=WINDOWS then
s = substitute_all(s,{ TL, VT, BL, HZ},
{"β","β","β","β"})
end if
return s
end function
--</hates utf8>
procedure visualise_tree(object tree, string root=HS)
if atom(tree) then
puts(1,"<empty>\n")
else
object {v,l,r} = tree
integer g = root[$]
if sequence(l) then
root[$] = iff(g=TL or g=HZ?' ':VT)
visualise_tree(l,root&TL)
end if
root[$] = g
printf(1,"%s%d\n",{w1252_to_utf8(root),v})
if sequence(r) then
root[$] = iff(g=TL?VT:' ')
visualise_tree(r,root&BL)
end if
end if
end procedure
function rand_tree(integer low, integer high)
for i=1 to 2 do
integer v = rand(high-low+1)-1+low
if v!=low
and v!=high then
return {v,rand_tree(low,v),rand_tree(v,high)}
end if
end for
return 0
end function
object tree = rand_tree(0,20) -- (can be 0, <1% chance)
visualise_tree(tree)
--pp(tree,{pp_Nest,10})
{} = wait_key()
|
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #TXR | TXR | (glob "/etc/*.conf") |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #UNIX_Shell | UNIX Shell | ls -d *.c # *.c files in current directory
(cd mydir && ls -d *.c) # *.c files in mydir |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. Β These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Β Walk a directory/Non-recursively Β (read a single directory).
| #ooRexx | ooRexx | /* REXX ---------------------------------------------------------------
* List all file names on my disk D: that contain the string TTTT
*--------------------------------------------------------------------*/
call SysFileTree "d:\*.*", "file", "FS" -- F get all Files
-- S search subdirectories
Say file.0 'files on disk'
do i=1 to file.0
If pos('TTTT',translate(file.i))>0 Then
say file.i
end |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. Β These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Β Walk a directory/Non-recursively Β (read a single directory).
| #Oz | Oz | declare
[Path] = {Module.link ['x-oz://system/os/Path.ozf']}
[Regex] = {Module.link ['x-oz://contrib/regex']}
Β
proc {WalkDirTree Root Pattern Proc}
proc {Walk R}
Entries = {Path.readdir R}
Files = {Filter Entries Path.isFile}
MatchingFiles = {Filter Files fun {$ File} {Regex.search Pattern File} \= false end}
Subdirs = {Filter Entries Path.isDir}
in
{ForAll MatchingFiles Proc}
{ForAll Subdirs Walk}
end
in
{Walk Root}
end
in
{WalkDirTree "." ".*\\.oz$" System.showInfo} |
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ββ 9 ββ
8 ββ 8 ββ
7 ββ ββ 7 ββββββββββββ
6 ββ ββ ββ 6 ββββββββββββ
5 ββ ββ ββ ββββ 5 ββββββββββββββββ
4 ββ ββ ββββββββ 4 ββββββββββββββββ
3 ββββββ ββββββββ 3 ββββββββββββββββ
2 ββββββββββββββββ ββ 2 ββββββββββββββββββββ
1 ββββββββββββββββββββ 1 ββββββββββββββββββββ
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
Four Solutions to a Trivial Problem β a Google Tech Talk by Guy Steele
Water collected between towers on Stack Overflow, from which the example above is taken)
An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| #PicoLisp | PicoLisp | (de water (Lst)
(sum
'((A)
(cnt
nT
(clip (mapcar '((B) (>= B A)) Lst)) ) )
(range 1 (apply max Lst)) ) )
(println
(mapcar
water
(quote
(1 5 3 7 2)
(5 3 7 2 6 4 5 9 1 2)
(2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1)
(5 5 5 5)
(5 6 7 8)
(8 7 7 6)
(6 7 10 7 6) ) ) ) |
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
| #ALGOL_68 | ALGOL 68 | MODE FIELD = INT;
FORMAT field fmt = $g(-0)$;
Β
MODE VEC = [3]FIELD;
FORMAT vec fmt = $"("f(field fmt)", "f(field fmt)", "f(field fmt)")"$;
Β
PROC crossp = (VEC a, b)VEC:(
#Cross product of two 3D vectors#
CO ASSERT(LWB a = LWB b AND UPB a = UPB b AND UPB b = 3 # "For 3D vectors only" #); CO
(a[2]*b[3] - a[3]*b[2], a[3]*b[1] - a[1]*b[3], a[1]*b[2] - a[2]*b[1])
);
Β
PRIO MAXLWB = 8, MINUPB=8;
Β
OP MAXLWB = (VEC a, b)INT: (LWB a<LWB b|LWB a|LWB b);
OP MINUPB = (VEC a, b)INT: (UPB a>UPB b|UPB a|UPB b);
Β
PROC dotp = (VEC a, b)FIELD:(
#Dot product of two vectors#
FIELD sum := 0;
FOR i FROM a MAXLWB b TO a MINUPB b DO sum +:= a[i]*b[i] OD;
sum
);
Β
PROC scalartriplep = (VEC a, b, c)VEC:(
#Scalar triple product of three vectors: "a . (b x c)"#
dotp(a, crossp(b, c))
);
Β
PROC vectortriplep = (VEC a, b, c)VEC:(
#Vector triple product of three vectors: "a x (b x c)"#
crossp(a, crossp(b, c))
);
Β
# Declare some useful operators #
PRIO DOT = 5, X = 5;
OP (VEC, VEC)FIELD DOT = dotp;
OP (VEC, VEC)VEC X = crossp;
Β
main:(
VEC a=(3, 4, 5), b=(4, 3, 5), c=(-5, -12, -13);
printf(($"a = "f(vec fmt)"; b = "f(vec fmt)"; c = "f(vec fmt)l$ , a, b, c));
printf($"Using PROCedures:"l$);
printf(($"a . b = "f(field fmt)l$, dotp(a,b)));
printf(($"a x b = "f(vec fmt)l$, crossp(a,b)));
printf(($"a . (b x c) = "f(field fmt)l$, scalartriplep(a, b, c)));
printf(($"a x (b x c) = "f(vec fmt)l$, vectortriplep(a, b, c)));
printf($"Using OPerators:"l$);
printf(($"a . b = "f(field fmt)l$, a DOT b));
printf(($"a x b = "f(vec fmt)l$, a X b));
printf(($"a . (b x c) = "f(field fmt)l$, a DOT (b X c)));
printf(($"a x (b x c) = "f(vec fmt)l$, a X (b X c)))
) |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #REXX | REXX | /*REXX program simulates a number of trials of a random digit and show it's skewΒ %. */
parse arg func times delta seed . /*obtain arguments (options) from C.L. */
if func=='' | func=="," then func= 'RANDOM' /*function not specified? Use default.*/
if times=='' | times=="," then times= 1000000 /*times " " " " */
if delta=='' | delta=="," then delta= 1/2 /*delta% " " " " */
if datatype(seed, 'W') then call random ,,seed /*use some RAND seed for repeatability.*/
highDig= 9 /*use this var for the highest digit. */
!.= 0 /*initialize all possible random trials*/
do times /* [β] perform a bunch of trials. */
if func=='RANDOM' thenΒ ?= random(highDig) /*use RANDOM function.*/
else interpret '?=' func "(0,"highDig')' /* " specified " */
Β !.?=Β !.? + 1 /*bump the invocation counter.*/
end /*times*/ /* [β] store trials ββββΊ pigeonholes. */
/* [β] compute the digit's skewness. */
g= times / (1 + highDig) /*calculate number of each digit throw.*/
w= max(9, length( commas(times) ) ) /*maximum length of number of trials.*/
pad= left('', 9) /*this is used for output indentation. */
say pad 'digit' center(" hits", w) ' skew ' "skewΒ %" 'result' /*header. */
say sep /*display a separator line. */
/** [β] show header and the separator.*/
do k=0 to highDig /*process each of the possible digits. */
skew= g -Β !.k /*calculate the skew for the digit. */
skewPC= (1 - (g - abs(skew)) / g) * 100 /* " " " percentage for dig*/
say pad center(k, 5) right( commas(!.k), w) right(skew, 6) ,
right( format(skewPC, , 3), 6) center( word('ok skewed', 1+(skewPC>delta)), 6)
end /*k*/
say sep /*display a separator line. */
y= 5+1+w+1+6+1+6+1+6 /*width + seps*/
say pad center(" (with " commas(times) ' trials)' , y) /*# trials. */
say pad center(" (skewed when exceeds " delta'%)' , y) /*skewed note.*/
exit 0 /*stick a fork in it, we're all done. */
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
commas: parse arg _; do jc=length(_)-3 to 1 by -3; _=insert(',', _, jc); end; return _
sep: say pad 'βββββ' center('', w, 'β') 'ββββββ' "ββββββ" 'ββββββ'; return |
http://rosettacode.org/wiki/Variable-length_quantity | Variable-length quantity | Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte);
display these sequences of octets;
convert these sequences of octets back to numbers, and check that they are equal to original numbers.
| #J | J | N=: 128x
v2i=: (N&| N&#./.~ [: +/\ _1 |. N&>)@i.~&a.
i2v=: a. {~ [:;}.@(N+//.@,:N&#.inv)&.>
ifv=: v2iΒ :. i2v
vfi=: i2vΒ :. v2i |
http://rosettacode.org/wiki/Variable-length_quantity | Variable-length quantity | Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte);
display these sequences of octets;
convert these sequences of octets back to numbers, and check that they are equal to original numbers.
| #Java | Java | public class VLQCode
{
public static byte[] encode(long n)
{
int numRelevantBits = 64 - Long.numberOfLeadingZeros(n);
int numBytes = (numRelevantBits + 6) / 7;
if (numBytes == 0)
numBytes = 1;
byte[] output = new byte[numBytes];
for (int i = numBytes - 1; i >= 0; i--)
{
int curByte = (int)(n & 0x7F);
if (i != (numBytes - 1))
curByte |= 0x80;
output[i] = (byte)curByte;
n >>>= 7;
}
return output;
}
Β
public static long decode(byte[] b)
{
long n = 0;
for (int i = 0; i < b.length; i++)
{
int curByte = b[i] & 0xFF;
n = (n << 7) | (curByte & 0x7F);
if ((curByte & 0x80) == 0)
break;
}
return n;
}
Β
public static String byteArrayToString(byte[] b)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < b.length; i++)
{
if (i > 0)
sb.append(", ");
String s = Integer.toHexString(b[i] & 0xFF);
if (s.length() < 2)
s = "0" + s;
sb.append(s);
}
return sb.toString();
}
Β
public static void main(String[] args)
{
long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L };
for (long n : testNumbers)
{
byte[] encoded = encode(n);
long decoded = decode(encoded);
System.out.println("Original input=" + n + ", encoded = [" + byteArrayToString(encoded) + "], decoded=" + decoded + ", " + ((n == decoded) ? "OK" : "FAIL"));
}
}
}
Β |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Β Call a function
| #BCPL | BCPL | get "libhdr"
Β
// A, B, C, etc are dummy arguments. If more are needed, more can be added.
// Eventually you will run into the compiler limit.
let foo(num, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O) be
// The arguments can be indexed starting from the first one.
for i=1 to num do writef("%S*N", (@num)!i)
Β
// You can pass as many arguments as you want. The declaration above guarantees
// that at least the first 16 arguments (including the number) will be available,
// but you certainly needn't use them all.
let start() be
foo(5, "Mary", "had", "a", "little", "lamb") |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Β Call a function
| #BQN | BQN | Fun1 β β’ShowΒ¨
Fun2 β {β’ShowΒ¨π©}
Fun3 β { 1=β π©Β ? β’Show π©; "too many arguments "Β ! π©} |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #ALGOL_68 | ALGOL 68 | INT i; BYTES b; # typically INT and BYTES are the same size #
STRING s:="DCLXVI", [666]CHAR c;
print((
"sizeof INT i =",bytes width, new line,
"UPB STRING s =",UPB s, new line,
"UPB []CHAR c =",UPB c, new line
)) |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #AutoHotkey | AutoHotkey | VarSetCapacity(Var, 10240000) ; allocate 10 megabytes
MsgBoxΒ % size := VarSetCapacity(Var) ; 10240000 |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Babel | Babel | main:
{ (1 2 (3 4) 5 6)
dup mu disp
dup nva disp
dup npt disp
dup nlf disp
dup nin disp
dup nhref disp
dup nhword disp }
Β
disp!Β : {Β %d cr << }
Β |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Β
Type Vector
As Double x, y
Declare Operator Cast() As String
End Type
Β
Operator Vector.Cast() As String
Return "[" + Str(x) + ", " + Str(y) + "]"
End Operator
Β
Operator + (vec1 As Vector, vec2 As Vector) As Vector
Return Type<Vector>(vec1.x + vec2.x, vec1.y + vec2.y)
End Operator
Β
Operator - (vec1 As Vector, vec2 As Vector) As Vector
Return Type<Vector>(vec1.x - vec2.x, vec1.y - vec2.y)
End Operator
Β
Operator * (vec As Vector, scalar As Double) As Vector
Return Type<Vector>(vec.x * scalar, vec.y * scalar)
End Operator
Β
Operator / (vec As Vector, scalar As Double) As Vector
' No need to check for division by zero as we're using Doubles
Return Type<Vector>(vec.x / scalar, vec.y / scalar)
End Operator
Β
Dim v1 As Vector = (5, 7)
Dim v2 As Vector = (2, 3)
Print v1; " + "; v2; " = "; v1 + v2
Print v1; " - "; v2; " = "; v1 - v2
Print v1; " * "; 11; " = "; v1 * 11.0
Print v1; " / "; 2; " = "; v1 / 2.0
Print
Print "Press any key to quit"
Sleep |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #Python | Python | /*REXX program demonstrates on setting a variable (using a "minimum var size".*/
numeric digits 100 /*default: 9 (decimal digs) for numbers*/
Β
/*ββ 1 2 3 4 5 6 7ββ*/
/*ββ1234567890123456789012345678901234567890123456789012345678901234567890ββ*/
Β
z = 12345678901111111112222222222333333333344444444445555555555.66
n =-12345678901111111112222222222333333333344444444445555555555.66
Β
/* [β] these #'s are stored as coded. */
/*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #Racket | Racket | /*REXX program demonstrates on setting a variable (using a "minimum var size".*/
numeric digits 100 /*default: 9 (decimal digs) for numbers*/
Β
/*ββ 1 2 3 4 5 6 7ββ*/
/*ββ1234567890123456789012345678901234567890123456789012345678901234567890ββ*/
Β
z = 12345678901111111112222222222333333333344444444445555555555.66
n =-12345678901111111112222222222333333333344444444445555555555.66
Β
/* [β] these #'s are stored as coded. */
/*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #Raku | Raku | /*REXX program demonstrates on setting a variable (using a "minimum var size".*/
numeric digits 100 /*default: 9 (decimal digs) for numbers*/
Β
/*ββ 1 2 3 4 5 6 7ββ*/
/*ββ1234567890123456789012345678901234567890123456789012345678901234567890ββ*/
Β
z = 12345678901111111112222222222333333333344444444445555555555.66
n =-12345678901111111112222222222333333333344444444445555555555.66
Β
/* [β] these #'s are stored as coded. */
/*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #REXX | REXX | /*REXX program demonstrates on setting a variable (using a "minimum var size".*/
numeric digits 100 /*default: 9 (decimal digs) for numbers*/
Β
/*ββ 1 2 3 4 5 6 7ββ*/
/*ββ1234567890123456789012345678901234567890123456789012345678901234567890ββ*/
Β
z = 12345678901111111112222222222333333333344444444445555555555.66
n =-12345678901111111112222222222333333333344444444445555555555.66
Β
/* [β] these #'s are stored as coded. */
/*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #Scala | Scala | /* Ranges for variables of the primitive numeric types */
println(s"A Byte variable has a range ofΒ : ${Byte.MinValue} to ${Byte.MaxValue}")
println(s"A Short variable has a range ofΒ : ${Short.MinValue} to ${Short.MaxValue}")
println(s"An Int variable has a range ofΒ : ${Int.MinValue} to ${Int.MaxValue}")
println(s"A Long variable has a range ofΒ : ${Long.MinValue} to ${Long.MaxValue}")
println(s"A Float variable has a range ofΒ : ${Float.MinValue} to ${Float.MaxValue}")
println(s"A Double variable has a range ofΒ : ${Double.MinValue} to ${Double.MaxValue}") |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #Wren | Wren | import "graphics" for Canvas, Color
import "dome" for Window
import "random" for Random
Β
class Game {
static init() {
Window.title = "Voronoi diagram"
var cells = 70
var size = 700
Window.resize(size, size)
Canvas.resize(size, size)
voronoi(cells, size)
}
Β
static update() {}
Β
static draw(alpha) {}
Β
static distSq(x1, x2, y1, y2) { (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) }
Β
static voronoi(cells, size) {
var r = Random.new()
var px = List.filled(cells, 0)
var py = List.filled(cells, 0)
var cl = List.filled(cells, 0)
for (i in 0...cells) {
px[i] = r.int(size)
py[i] = r.int(size)
cl[i] = Color.rgb(r.int(256), r.int(256), r.int(256))
}
for (x in 0...size) {
for (y in 0...size) {
var n = 0
for (i in 0...cells) {
if (distSq(px[i], x, py[i], y) < distSq(px[n], x, py[n], y)) n = i
}
Canvas.pset(x, y, cl[n])
}
}
for (i in 0...cells) {
Canvas.circlefill(px[i], py[i], 2, Color.black)
}
}
} |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test | Verify distribution uniformity/Chi-squared test | Task
Write a function to verify that a given distribution of values is uniform by using the
Ο
2
{\displaystyle \chi ^{2}}
test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%).
The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce.
Reference
Β an entry at the MathWorld website: Β chi-squared distribution.
| #Racket | Racket | Β
#lang racket
(require
racket/flonum (planet williams/science:4:5/science)
(only-in (planet williams/science/unsafe-ops-utils) real->float))
Β
; (chi^2-goodness-of-fit-test observed expected df)
; Given: observed, a sequence of observed frequencies
; expected, a sequence of expected frequencies
; df, the degrees of freedom
; Result: P-value = 1-chi^2cdf(X^2,df) , the p-value
(define (chi^2-goodness-of-fit-test observed expected df)
(define X^2 (for/sum ([o observed] [e expected])
(/ (sqr (- o e)) e)))
(- 1.0 (chi-squared-cdf X^2 df)))
Β
(define (is-uniform? rand n Ξ±)
Β ; Use significance level Ξ± to test whether
Β ; n small random numbers generated by rand
Β ; have a uniform distribution.
Β
Β ; Observed values:
(define o (make-vector 10 0))
Β ; generate n random integers from 0 to 9.
(for ([_ (+ n 1)])
(define r (rand 10))
(vector-set! o r (+ (vector-ref o r) 1)))
Β ; Expected values:
(define ex (make-vector 10 (/ n 10)))
Β
Β ; Calculate the P-value:
(define P (chi^2-goodness-of-fit-test o ex (- n 1)))
Β
Β ; If the P-value is larger than Ξ± we accept the
Β ; hypothesis that the numbers are distributed uniformly.
(> P Ξ±))
Β
; Test whether the builtin generator is uniform:
(is-uniform? random 1000 0.05)
; Test whether the constant generator fails:
(is-uniform? (Ξ»(_) 5) 1000 0.05)
Β |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test | Verify distribution uniformity/Chi-squared test | Task
Write a function to verify that a given distribution of values is uniform by using the
Ο
2
{\displaystyle \chi ^{2}}
test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%).
The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce.
Reference
Β an entry at the MathWorld website: Β chi-squared distribution.
| #Raku | Raku | sub incomplete-Ξ³-series($s, $z) {
my \numers = $z X** 1..*;
my \denoms = [\*] $s X+ 1..*;
my $M = 1 + [+] (numers Z/ denoms) ... * < 1e-6;
$z**$s / $s * exp(-$z) * $M;
}
Β
sub postfix:<!>(Int $n) { [*] 2..$n }
Β
sub Ξ-of-half(Int $n where * > 0) {
($n %% 2) ?? (($_-1)! given $n div 2)
!! ((2*$_)! / (4**$_ * $_!) * sqrt(pi) given ($n-1) div 2);
}
Β
# degrees of freedom constrained due to numerical limitations
sub chi-squared-cdf(Int $k where 1..200, $x where * >= 0) {
my $f = $k < 20 ?? 20 !! 10;
given $x {
when 0 { 0.0 }
when * < $k + $f*sqrt($k) { incomplete-Ξ³-series($k/2, $x/2) / Ξ-of-half($k) }
default { 1.0 }
}
}
Β
sub chi-squared-test(@bins, :$significance = 0.05) {
my $n = +@bins;
my $N = [+] @bins;
my $expected = $N / $n;
my $chi-squared = [+] @bins.map: { ($^bin - $expected)**2 / $expected }
my $p-value = 1 - chi-squared-cdf($n-1, $chi-squared);
return (:$chi-squared, :$p-value, :uniform($p-value > $significance));
}
Β
for [< 199809 200665 199607 200270 199649 >],
[< 522573 244456 139979 71531 21461 >]
-> $dataset
{
my %t = chi-squared-test($dataset);
say 'data: ', $dataset;
say "ΟΒ² = {%t<chi-squared>}, p-value = {%t<p-value>.fmt('%.4f')}, uniform = {%t<uniform>}";
} |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a  Vigenère cypher,  both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Β Caesar cipher
Β Rot-13
Β Substitution Cipher
| #jq | jq | def vigenere(text; key; encryptp):
# retain alphabetic characters only
def n:
ascii_upcase | explode | map(select(65 <= . and . <= 90)) | [., length];
(text | n) as [$xtext, $length]
| (key | n) as [$xkey, $keylength]
| reduce range(0; $length) as $i (null;
($iΒ % $keylength) as $ki
| . + [if encryptp
then (($xtext[$i] + $xkey[$ki] - 130)Β % 26) + 65
else (($xtext[$i] - $xkey[$ki] + 26)Β % 26) + 65
end] )
| implode;
Β
# Input: sample text
def example($key):
vigenere(.; $key; true)
| . as $encoded
| ., vigenere($encoded; $key; false)Β ;
Β
"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
| (., example("VIGENERECIPHER")),
"",
(., example("ROSETTACODE")) |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a  Vigenère cypher,  both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Β Caesar cipher
Β Rot-13
Β Substitution Cipher
| #Jsish | Jsish | /* Vigenère cipher, in Jsish */
"use strict";
Β
function ordA(a:string):number {
return a.charCodeAt(0) - 65;
}
Β
// vigenere
function vigenereCipher(text:string, key:string, decode:boolean=false):string {
var i = 0, b;
key = key.toUpperCase().replace(/[^A-Z]/g, '');
return text.toUpperCase().replace(/[^A-Z]/g, '').replace(/[A-Z]/g,
function(a:string, idx:number, str:string) {
b = key[i++ % key.length];
return String.fromCharCode(((ordA(a) + (decode ? 26 - ordA(b) : ordA(b))) % 26 + 65));
});
}
Β
provide('vigenereCipher', 1);
Β
if (Interp.conf('unitTest')) {
var text = "The quick brown fox Jumped over the lazy Dog the lazy dog lazy dog dog";
var key = 'jsish';
var enc = vigenereCipher(text, key);
; text;
; enc;
; vigenereCipher(enc, key, true);
}
Β
/*
=!EXPECTSTART!=
text ==> The quick brown fox Jumped over the lazy Dog the lazy dog lazy dog dog
enc ==> CZMIBRUSTYXOVXVGBCEWNVWNLALPWSJRGVVPLPWSJRGVVPDIRFMGOVVP
vigenere(enc, key, true) ==> THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGTHELAZYDOGLAZYDOGDOG
=!EXPECTEND!=
*/ |
http://rosettacode.org/wiki/Visualize_a_tree | Visualize a tree | A tree structure Β (i.e. a rooted, connected acyclic graph) Β is often used in programming.
It's often helpful to visually examine such a structure.
There are many ways to represent trees to a reader, such as:
Β indented text Β (Γ la unix tree command)
Β nested HTML tables
Β hierarchical GUI widgets
Β 2D Β or Β 3D Β images
Β etc.
Task
Write a program to produce a visual representation of some tree.
The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly.
Make do with the vague term "friendly" the best you can.
| #PicoLisp | PicoLisp | (view '(1 (2 (3 (4) (5) (6 (7))) (8 (9)) (10)) (11 (12) (13)))) |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #UnixPipes | UnixPipes | ls | grep '\.c$' |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #VBScript | VBScript | Β
Sub show_files(folder_path,pattern)
Set objfso = CreateObject("Scripting.FileSystemObject")
For Each file In objfso.GetFolder(folder_path).Files
If InStr(file.Name,pattern) Then
WScript.StdOut.WriteLine file.Name
End If
Next
End Sub
Β
Call show_files("C:\Windows",".exe")
Β |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. Β These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Β Walk a directory/Non-recursively Β (read a single directory).
| #Perl | Perl | use File::Find qw(find);
my $dir = '.';
my $pattern = 'foo';
my $callback = sub { print $File::Find::name, "\n" if /$pattern/ };
find $callback, $dir; |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. Β These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Β Walk a directory/Non-recursively Β (read a single directory).
| #Phix | Phix | function find_pfile(string pathname, sequence dirent)
if match("pfile.e",dirent[D_NAME]) then
-- return pathname&dirent[D_NAME] -- as below
?pathname&"\\"&dirent[D_NAME]
end if
return 0 -- non-zero terminates scan
end function
?walk_dir("C:\\Program Files (x86)\\Phix",find_pfile,1)
|
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ββ 9 ββ
8 ββ 8 ββ
7 ββ ββ 7 ββββββββββββ
6 ββ ββ ββ 6 ββββββββββββ
5 ββ ββ ββ ββββ 5 ββββββββββββββββ
4 ββ ββ ββββββββ 4 ββββββββββββββββ
3 ββββββ ββββββββ 3 ββββββββββββββββ
2 ββββββββββββββββ ββ 2 ββββββββββββββββββββ
1 ββββββββββββββββββββ 1 ββββββββββββββββββββ
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
Four Solutions to a Trivial Problem β a Google Tech Talk by Guy Steele
Water collected between towers on Stack Overflow, from which the example above is taken)
An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| #Python | Python | def water_collected(tower):
N = len(tower)
highest_left = [0] + [max(tower[:n]) for n in range(1,N)]
highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]
water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)
for n in range(N)]
print("highest_left: ", highest_left)
print("highest_right: ", highest_right)
print("water_level: ", water_level)
print("tower_level: ", tower)
print("total_water: ", sum(water_level))
print("")
return sum(water_level)
Β
towers = [[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
Β
[water_collected(tower) for tower in towers] |
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
| #ALGOL_W | ALGOL W | begin
Β % define the Vector record type Β %
record Vector( integer X, Y, Z );
Β
Β % calculates the dot product of two Vectors Β %
integer procedure dotProduct( reference(Vector) value A, B )Β ;
( X(A) * X(B) ) + ( Y(A) * Y(B) ) + ( Z(A) * Z(B) );
Β
Β % calculates the cross product or two Vectors Β %
reference(Vector) procedure crossProduct( reference(Vector) value A, B )Β ;
Vector( ( Y(A) * Z(B) ) - ( Z(A) * Y(B) )
, ( Z(A) * X(B) ) - ( X(A) * Z(B) )
, ( X(A) * Y(B) ) - ( Y(A) * X(B) )
);
Β
Β % calculates the scaler triple product of two vectors Β %
integer procedure scalerTripleProduct( reference(Vector) value A, B, C )Β ;
dotProduct( A, crossProduct( B, C ) );
Β
Β % calculates the vector triple product of two vectors Β %
reference(Vector) procedure vectorTripleProduct( reference(Vector) value A, B, C )Β ;
crossProduct( A, crossProduct( B, C ) );
Β
Β % test the Vector routines Β %
begin
procedure writeonVector( reference(Vector) value v )Β ;
writeon( "(", X(v), ", ", Y(v), ", ", Z(v), ")" );
Β
Reference(Vector) a, b, c;
Β
aΒ := Vector( 3, 4, 5 );
bΒ := Vector( 4, 3, 5 );
cΒ := Vector( -5, -12, -13 );
Β
i_wΒ := 1; s_wΒ := 0;Β % set output formatting Β %
Β
write( " a: " ); writeonVector( a );
write( " b: " ); writeonVector( b );
write( " c: " ); writeonVector( c );
write( " a . b: ", dotProduct( a, b ) );
write( " a x b: " ); writeonVector( crossProduct( a, b ) );
write( "a . ( b x c ): ", scalerTripleProduct( a, b, c ) );
write( "a x ( b x c ): " ); writeonVector( vectorTripleProduct( a, b, c ) )
end
end. |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #Ring | Ring | Β
# ProjectΒ : Verify distribution uniformity/Naive
Β
maxrnd = 7
for r = 2 to 5
check = distcheck(pow(10,r), 0.05)
see "over " + pow(10,r) + " runs dice5 " + nl
if check
see "failed distribution check with " + check + " bin(s) out of range" + nl
else
see "passed distribution check" + nl
ok
next
Β
func distcheck(repet, delta)
m = 1
s = 0
bins = list(maxrnd)
for i = 1 to repet
r = dice5() + 1
bins[r] = bins[r] + 1
if r>m m = r ok
next
for i = 1 to m
if bins[i]/(repet/m) > 1+delta s = s + 1 ok
if bins[i]/(repet/m) < 1-delta s = s + 1 ok
next
return s
Β
func dice5
return random(5)
Β |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #Ruby | Ruby | def distcheck(n, delta=1)
unless block_given?
raise ArgumentError, "pass a block to this method"
end
Β
h = Hash.new(0)
n.times {h[ yield ] += 1}
Β
target = 1.0 * n / h.length
h.each do |key, value|
if (value - target).abs > 0.01 * delta * n
raise StandardError,
"distribution potentially skewed for '#{key}': expected around #{target}, got #{value}"
end
end
Β
puts h.sort.map{|k, v| "#{k} #{v}"}
end
Β
if __FILE__ == $0
begin
distcheck(100_000) {rand(10)}
distcheck(100_000) {rand > 0.95}
rescue StandardError => e
p e
end
end |
http://rosettacode.org/wiki/Variable_declaration_reset | Variable declaration reset | A decidely non-challenging task to highlight a potential difference between programming languages.
Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based.
The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration.
There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences.
Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say)
// int prev // crashes with unassigned variable
int prev = -1 // predictably no output
If your programming language does not support block scope (eg assembly) it should be omitted from this task.
| #ALGOL_68 | ALGOL 68 | BEGIN
[]INT s = ( 1, 2, 2, 3, 4, 4, 5 );
FOR i FROM LWB s TO UPB s DO
INT curr := s[ i ], prev;
IF IF i > LWB s THEN curr = prev ELSE FALSE FI THEN
print( ( i, newline ) )
FI;
prev := curr
OD
END |
http://rosettacode.org/wiki/Variable-length_quantity | Variable-length quantity | Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte);
display these sequences of octets;
convert these sequences of octets back to numbers, and check that they are equal to original numbers.
| #JavaScript | JavaScript | const RADIX = 7;
const MASK = 2**RADIX - 1;
Β
const octetify = (n)=> {
if (n >= 2147483648) {
throw new RangeError("Variable Length Quantity not supported for numbers >= 2147483648");
}
const octets = [];
for (let i = n; i != 0; i >>>= RADIX) {
octets.push((((i & MASK) + (octets.empty ? 0 : (MASK + 1)))));
}
octets.reverse();
return octets;
};
Β
const deoctetify = (octets)=>
octets.reduce((n, octet)=>
(n << RADIX) + (octet & MASK)
, 0);
Β
// Test (assuming Node.js)
Β
const assert = require("assert");
const testNumbers = [ 0x200000, 0x1fffff, 1, 127, 128, 2147483647 /*, 589723405834*/ ]
Β
testNumbers.forEach((number)=> {
const octets = octetify(number)
console.log(octets);
const got_back_number = deoctetify(octets)
assert.strictEqual(got_back_number, number);
}); |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.