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 ... | #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 ██ ... | #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;
$_->{LEVE... |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would repr... | #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) =... |
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 ... | #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 ... | #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)
... |
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 (209... | #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)
... |
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... | #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);
VectorToSt... |
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))
... |
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 distribut... | #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
... |
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 ... | #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 c... |
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 ... | #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 ... | #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 inde... |
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.
... | #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.
... | #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 ... | #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->St... |
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 ██ ... | #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
con... |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would repr... | #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 i... |
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 ... | #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 / 1... |
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 ... | #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
ove... |
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 (209... | #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... |
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 (209... | #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... | #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 ... |
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... | #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), ... |
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
... |
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)
... |
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 distribut... | #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
h... |
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 ... | #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(e... |
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 ... | #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;
... |
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.
... | #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.
... | #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 ... | #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 ... | #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.rea... |
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 ██ ... | #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 )... |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would repr... | #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)... |
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 ... | #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)
... |
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 ... | #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... |
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 ... | #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... |
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 (209... | #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 (p... |
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);
}
... |
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... | #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... | #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 VECTO... |
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), ... |
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, sto... |
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... |
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 distribut... | #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?",chi2IsUn... |
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 ... | #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 Str... |
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 ... | #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 '─'
... |
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.
... | #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.
... | #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 ... | #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 ... |
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 ... | #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 P... |
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 ██ ... | #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)
... |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would repr... | #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[... |
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 ... | #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... |
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 (209... | #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 (209... | #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 curBy... |
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)
... |
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... | #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
Operat... |
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──*... |
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──*... |
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──*... |
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──*... |
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}")
prin... |
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)
}
s... |
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 distribut... | #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
; ... |
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 distribut... | #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)! giv... |
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 ... | #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
... |
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 ... | #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(/[... |
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 ... | #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.
... | #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.
... | #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 ... | #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 ... | #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 ██ ... | #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)
... |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would repr... | #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... |
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 ... | #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
... |
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 ... | #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 potential... |
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 ... | #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 (209... | #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)))));
}
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.