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/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #BASIC | BASIC | 10 DIM A%(10): REM the array size is 10 integers
20 DIM B(10): REM the array will hold 10 floating point values
30 DIM C$(12): REM a character array of 12 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.
| #C | C | #include <stdint.h>
int_least32_t foo; |
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.
| #Raku | Raku | use Image::PNG::Portable;
my @bars = '▁▂▃▅▆▇▇▆▅▃▂▁'.comb;
my %type = ( # Voronoi diagram type distance calculation
'Taxicab' => sub ($px, $py, $x, $y) { ($px - $x).abs + ($py - $y).abs },
'Euclidean' => sub ($px, $py, $x, $y) { ($px - $x)² + ($py - $y)² },
'Minkowski' => sub ($px, $py, $x, $y) { ($px - $x)³.abs + ($py - $y)³.abs },
);
my $width = 400;
my $height = 400;
my $dots = 30;
my @domains = map { Hash.new(
'x' => (5..$width-5).roll,
'y' => (5..$height-5).roll,
'rgb' => [(64..255).roll xx 3]
) }, ^$dots;
for %type.keys -> $type {
print "\nGenerating $type diagram... ", ' ' x @bars;
my $img = voronoi(@domains, :w($width), :h($height), :$type);
@domains.map: *.&dot($img);
$img.write: "Voronoi-{$type}-perl6.png";
}
sub voronoi (@domains, :$w, :$h, :$type) {
my $png = Image::PNG::Portable.new: :width($w), :height($h);
(^$w).race.map: -> $x {
print "\b" x 2+@bars, @bars.=rotate(1).join , ' ';
for ^$h -> $y {
my ($, $i) = min @domains.map: { %type{$type}(%($_)<x>, %($_)<y>, $x, $y), $++ };
$png.set: $x, $y, |@domains[$i]<rgb>
}
}
$png
}
sub dot (%h, $png, $radius = 3) {
for (%h<x> X+ -$radius .. $radius) X (%h<y> X+ -$radius .. $radius) -> ($x, $y) {
$png.set($x, $y, 0, 0, 0) if ( %h<x> - $x + (%h<y> - $y) * i ).abs <= $radius;
}
}
|
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.
| #Julia | Julia | # v0.6
using Distributions
function eqdist(data::Vector{T}, α::Float64=0.05)::Bool where T <: Real
if ! (0 ≤ α ≤ 1); error("α must be in [0, 1]") end
exp = mean(data)
chisqval = sum((x - exp) ^ 2 for x in data) / exp
pval = ccdf(Chisq(2), chisqval)
return pval > α
end
data1 = [199809, 200665, 199607, 200270, 199649]
data2 = [522573, 244456, 139979, 71531, 21461]
for data in (data1, data2)
println("Data:\n$data")
println("Hypothesis test: the original population is ", (eqdist(data) ? "" : "not "), "uniform.\n")
end |
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.
| #Kotlin | Kotlin | // version 1.1.51
typealias Func = (Double) -> Double
fun gammaLanczos(x: Double): Double {
var xx = x
val p = doubleArrayOf(
0.99999999999980993,
676.5203681218851,
-1259.1392167224028,
771.32342877765313,
-176.61502916214059,
12.507343278686905,
-0.13857109526572012,
9.9843695780195716e-6,
1.5056327351493116e-7
)
val g = 7
if (xx < 0.5) return Math.PI / (Math.sin(Math.PI * xx) * gammaLanczos(1.0 - xx))
xx--
var a = p[0]
val t = xx + g + 0.5
for (i in 1 until p.size) a += p[i] / (xx + i)
return Math.sqrt(2.0 * Math.PI) * Math.pow(t, xx + 0.5) * Math.exp(-t) * a
}
fun integrate(a: Double, b: Double, n: Int, f: Func): Double {
val h = (b - a) / n
var sum = 0.0
for (i in 0 until n) {
val x = a + i * h
sum += (f(x) + 4.0 * f(x + h / 2.0) + f(x + h)) / 6.0
}
return sum * h
}
fun gammaIncompleteQ(a: Double, x: Double): Double {
val aa1 = a - 1.0
fun f0(t: Double) = Math.pow(t, aa1) * Math.exp(-t)
val h = 1.5e-2
var y = aa1
while ((f0(y) * (x - y) > 2.0e-8) && y < x) y += 0.4
if (y > x) y = x
return 1.0 - integrate(0.0, y, (y / h).toInt(), ::f0) / gammaLanczos(a)
}
fun chi2UniformDistance(ds: DoubleArray): Double {
val expected = ds.average()
val sum = ds.map { val x = it - expected; x * x }.sum()
return sum / expected
}
fun chi2Probability(dof: Int, distance: Double) =
gammaIncompleteQ(0.5 * dof, 0.5 * distance)
fun chiIsUniform(ds: DoubleArray, significance: Double):Boolean {
val dof = ds.size - 1
val dist = chi2UniformDistance(ds)
return chi2Probability(dof, dist) > significance
}
fun main(args: Array<String>) {
val dsets = listOf(
doubleArrayOf(199809.0, 200665.0, 199607.0, 200270.0, 199649.0),
doubleArrayOf(522573.0, 244456.0, 139979.0, 71531.0, 21461.0)
)
for (ds in dsets) {
println("Dataset: ${ds.asList()}")
val dist = chi2UniformDistance(ds)
val dof = ds.size - 1
print("DOF: $dof Distance: ${"%.4f".format(dist)}")
val prob = chi2Probability(dof, dist)
print(" Probability: ${"%.6f".format(prob)}")
val uniform = if (chiIsUniform(ds, 0.05)) "Yes" else "No"
println(" Uniform? $uniform\n")
}
} |
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
| #Factor | Factor | USING: arrays ascii formatting kernel math math.functions
math.order sequences ;
IN: rosetta-code.vigenere-cipher
: mult-pad ( key input -- x )
[ length ] bi@ 2dup < [ swap ] when / ceiling ;
: lengthen-pad ( key input -- rep-key input )
[ mult-pad ] 2keep [ <repetition> concat ] dip
[ length ] keep [ head ] dip ;
: normalize ( str -- only-upper-letters )
>upper [ LETTER? ] filter ;
: vigenere-encrypt ( key input -- ecrypted )
[ normalize ] bi@ lengthen-pad
[ [ CHAR: A - ] map ] bi@ [ + 26 mod CHAR: A + ] 2map ;
: vigenere-decrypt ( key input -- decrypted )
[ normalize ] bi@ lengthen-pad [ [ CHAR: A - ] map ] bi@
[ - 26 - abs 26 mod CHAR: A + ] 2map ;
: main ( -- )
"Vigenere cipher" dup
"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
2dup "Key: %s\nInput: %s\n" printf
vigenere-encrypt dup "Encrypted: %s\n" printf
vigenere-decrypt "Decrypted: %s\n" printf ;
MAIN: main |
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
| #Fortran | Fortran | program vigenere_cipher
implicit none
character(80) :: plaintext = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!", &
ciphertext = ""
character(14) :: key = "VIGENERECIPHER"
call encrypt(plaintext, ciphertext, key)
write(*,*) plaintext
write(*,*) ciphertext
call decrypt(ciphertext, plaintext, key)
write(*,*) plaintext
contains
subroutine encrypt(intxt, outtxt, k)
character(*), intent(in) :: intxt, k
character(*), intent(out) :: outtxt
integer :: chrn
integer :: cp = 1, kp = 1
integer :: i
outtxt = ""
do i = 1, len(trim(intxt))
select case(intxt(i:i))
case ("A":"Z", "a":"z")
select case(intxt(i:i))
case("a":"z")
chrn = iachar(intxt(i:i)) - 32
case default
chrn = iachar(intxt(i:i))
end select
outtxt(cp:cp) = achar(modulo(chrn + iachar(k(kp:kp)), 26) + 65)
cp = cp + 1
kp = kp + 1
if(kp > len(k)) kp = kp - len(k)
end select
end do
end subroutine
subroutine decrypt(intxt, outtxt, k)
character(*), intent(in) :: intxt, k
character(*), intent(out) :: outtxt
integer :: chrn
integer :: cp = 1, kp = 1
integer :: i
outtxt = ""
do i = 1, len(trim(intxt))
chrn = iachar(intxt(i:i))
outtxt(cp:cp) = achar(modulo(chrn - iachar(k(kp:kp)), 26) + 65)
cp = cp + 1
kp = kp + 1
if(kp > len(k)) kp = kp - len(k)
end do
end subroutine
end program |
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.
| #jq | jq | 0
├─ 1
├─ 2
└─ 3
|
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).
| #Raven | Raven | 'dir://.' open each as item
item m/\.txt$/ if "%(item)s\n" print |
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).
| #REXX | REXX | /*REXX program shows files in directory tree that match a given criteria*/
parse arg xdir; if xdir='' then xdir='\' /*Any DIR? Use default.*/
@.=0 /*default in case ADDRESS fails. */
trace off /*suppress REXX err msg for fails*/
address system 'DIR' xdir '/b /s' with output stem @. /*issue DIR cmd.*/
if rc\==0 then do /*an error happened?*/
say '***error!*** from DIR' xDIR /*indicate que pasa.*/
say 'return code=' rc /*show the Ret Code.*/
exit rc /*exit with the RC.*/
end /* [↑] bad address.*/
#[email protected] /*number of entries.*/
if #==0 then #=' no ' /*use a word, ¬zero.*/
say center('directory ' xdir " has " # ' matching entries.',79,'─')
do j=1 for #; say @.j; end /*show files that met criteria. */
exit @.0+rc /*stick a fork in it, we're done.*/ |
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).
| #Lasso | Lasso | // care only about visible files and filter out any directories
define dir -> eachVisibleFilePath() => {
return with name in self -> eachEntry where #name -> second != io_dir_dt_dir where not(#name -> first -> beginswith('.')) select .makeFullPath(#name -> first)
}
// care only about visible directories and filter out any files
define dir -> eachVisibleDir() => {
return with name in self -> eachEntry where #name -> second == io_dir_dt_dir where not(#name -> first -> beginswith('.')) select dir(.makeFullPath(#name -> first + '/'))
}
// Recursively walk the directory tree and find all files and directories
// return only paths to files
define dir -> eachVisibleFilePathRecursive(-dirFilter = void) => {
local(files = .eachVisibleFilePath)
with dir in .eachVisibleDir
where !#dirFilter || #dirFilter(#dir -> realPath)
do {
#files = tie(#files, #dir -> eachVisibleFilePathRecursive(-dirFilter = #dirFilter))
}
return #files
}
local(matchingfilenames = array)
with filepath in dir('/') -> eachVisibleFilePathRecursive
where #filepath -> endswith('.lasso')
let filename = #filepath -> split('/') -> last
do #matchingfilenames -> insert(#filename)
#matchingfilenames |
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).
| #LiveCode | LiveCode | function pathsForDirectoryAndWildcardPattern pDirectory, pWildcardPattern
-- returns a return-delimited list of long file names
-- the last character in the list is a return, unless the list is empty
filter files(pDirectory) with pWildcardPattern
repeat for each line tFile in it
put pDirectory & slash & tFile & cr after tPaths
end repeat
filter folders(pDirectory) without ".."
repeat for each line tFolder in it
put pathsForDirectoryAndWildcardPattern(pDirectory & slash & tFolder, pWildcardPattern) after tPaths
end repeat
return tPaths
end pathsForDirectoryAndWildcardPattern |
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.
| #Lua | Lua | function waterCollected(i,tower)
local length = 0
for _ in pairs(tower) do
length = length + 1
end
local wu = 0
repeat
local rht = length - 1
while rht >= 0 do
if tower[rht + 1] > 0 then
break
end
rht = rht - 1
end
if rht < 0 then
break
end
local bof = 0
local col = 0
while col <= rht do
if tower[col + 1] > 0 then
tower[col + 1] = tower[col + 1] - 1
bof = bof + 1
elseif bof > 0 then
wu = wu + 1
end
col = col + 1
end
if bof < 2 then
break
end
until false
if wu == 0 then
print(string.format("Block %d does not hold any water.", i))
else
print(string.format("Block %d holds %d water units.", i, wu))
end
end
function main()
local 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}
}
for i,tbl in pairs(towers) do
waterCollected(i,tbl)
end
end
main() |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #Perl | Perl | $| = 1;
my @info = `xrandr -q`;
$info[0] =~ /current (\d+) x (\d+)/;
my $current = "$1x$2";
my @resolutions;
for (@info) {
push @resolutions, $1 if /^\s+(\d+x\d+)/
}
system("xrandr -s $resolutions[-1]");
print "Current resolution $resolutions[-1].\n";
for (reverse 1 .. 9) {
print "\rChanging back in $_ seconds...";
sleep 1;
}
system("xrandr -s $current");
print "\rResolution returned to $current.\n"; |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #Phix | Phix | without js -- (system, system_exec, sleep)
if platform()=LINUX then
{} = system_exec("xrandr -s 640x480")
sleep(3)
{} = system_exec("xrandr -s 1280x960")
else -- WINDOWS
puts(1,"") -- (ensure console exists)
system("mode CON: COLS=40 LINES=25")
sleep(3)
system("mode CON: COLS=80 LINES=25")
end if
|
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #Python | Python | import win32api
import win32con
import pywintypes
devmode=pywintypes.DEVMODEType()
devmode.PelsWidth=640
devmode.PelsHeight=480
devmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT
win32api.ChangeDisplaySettings(devmode,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 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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | SetAttributes[CheckDistribution, HoldFirst]
CheckDistribution[function_,number_,delta_] :=(Print["Expected: ", N[number/7], ", Generated :",
Transpose[Tally[Table[function, {number}]]][[2]] // Sort]; If[(Max[#]-Min[#])&
[Transpose[Tally[Table[function, {number}]]][[2]]] < delta*number/700, "Flat", "Skewed"]) |
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
| #Nim | Nim | import tables
proc checkDist(f: proc(): int; repeat: Positive; tolerance: float) =
var counts: CountTable[int]
for _ in 1..repeat:
counts.inc f()
let expected = (repeat / counts.len).toInt # Rounded to nearest.
let allowedDelta = (expected.toFloat * tolerance / 100).toInt
var maxDelta = 0
for val, count in counts.pairs:
let d = abs(count - expected)
if d > maxDelta: maxDelta = d
let status = if maxDelta <= allowedDelta: "passed" else: "failed"
echo "Checking ", repeat, " values with a tolerance of ", tolerance, "%."
echo "Random generator ", status, " the uniformity test."
echo "Max delta encountered = ", maxDelta, " Allowed delta = ", allowedDelta
when isMainModule:
import random
randomize()
proc rand5(): int = rand(1..5)
checkDist(rand5, 1_000_000, 0.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
| #OCaml | OCaml | let distcheck fn n ?(delta=1.0) () =
let h = Hashtbl.create 5 in
for i = 1 to n do
let v = fn() in
let n =
try Hashtbl.find h v
with Not_found -> 0
in
Hashtbl.replace h v (n+1)
done;
Hashtbl.iter (fun v n -> Printf.printf "%d => %d\n%!" v n) h;
let target = (float n) /. float (Hashtbl.length h) in
Hashtbl.iter (fun key value ->
if abs_float(float value -. target) > 0.01 *. delta *. (float n)
then (Printf.eprintf
"distribution potentially skewed for '%d': expected around %f, got %d\n%!"
key target value)
) h;
;; |
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.
| #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
#include <vector>
std::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << "[ ";
if (it != end) {
os << std::setfill('0') << std::setw(2) << (uint32_t)*it;
it = std::next(it);
}
while (it != end) {
os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it;
it = std::next(it);
}
return os << " ]";
}
std::vector<uint8_t> to_seq(uint64_t x) {
int i;
for (i = 9; i > 0; i--) {
if (x & 127ULL << i * 7) {
break;
}
}
std::vector<uint8_t> out;
for (int j = 0; j <= i; j++) {
out.push_back(((x >> ((i - j) * 7)) & 127) | 128);
}
out[i] ^= 128;
return out;
}
uint64_t from_seq(const std::vector<uint8_t> &seq) {
uint64_t r = 0;
for (auto b : seq) {
r = (r << 7) | (b & 127);
}
return r;
}
int main() {
std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL };
for (auto x : src) {
auto s = to_seq(x);
std::cout << std::hex;
std::cout << "seq from " << x << ' ' << s << " back: " << from_seq(s) << '\n';
std::cout << std::dec;
}
return 0;
} |
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
| #ActionScript | ActionScript | public function printArgs(... args):void
{
for (var i:int = 0; i < args.length; i++)
trace(args[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
| #Ada | Ada | with Ada.Strings.Unbounded, Ada.Text_IO;
procedure Variadic is
subtype U_String is Ada.Strings.Unbounded.Unbounded_String;
use type U_String;
function "+"(S: String) return U_String
renames Ada.Strings.Unbounded.To_Unbounded_String;
function "-"(U: U_String) return String
renames Ada.Strings.Unbounded.To_String;
type Variadic_Array is array(Positive range <>) of U_String;
procedure Print_Line(Params: Variadic_Array) is
begin
for I in Params'Range loop
Ada.Text_IO.Put(-Params(I));
if I < Params'Last then
Ada.Text_IO.Put(" ");
end if;
end loop;
Ada.Text_IO.New_Line;
end Print_Line;
begin
Print_Line((+"Mary", +"had", +"a", +"little", +"lamb.")); -- print five strings
Print_Line((1 => +"Rosetta Code is cooool!")); -- print one string
end; |
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
| #BQN | BQN | 5‿7 + 2‿3
⟨7 10⟩
5‿7 - 2‿3
⟨3 4⟩
5‿7 × 11
⟨55 77⟩
5‿7 ÷ 2
⟨2.5 3.5⟩ |
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
| #C | C |
#include<stdio.h>
#include<math.h>
#define pi M_PI
typedef struct{
double x,y;
}vector;
vector initVector(double r,double theta){
vector c;
c.x = r*cos(theta);
c.y = r*sin(theta);
return c;
}
vector addVector(vector a,vector b){
vector c;
c.x = a.x + b.x;
c.y = a.y + b.y;
return c;
}
vector subtractVector(vector a,vector b){
vector c;
c.x = a.x - b.x;
c.y = a.y - b.y;
return c;
}
vector multiplyVector(vector a,double b){
vector c;
c.x = b*a.x;
c.y = b*a.y;
return c;
}
vector divideVector(vector a,double b){
vector c;
c.x = a.x/b;
c.y = a.y/b;
return c;
}
void printVector(vector a){
printf("%lf %c %c %lf %c",a.x,140,(a.y>=0)?'+':'-',(a.y>=0)?a.y:fabs(a.y),150);
}
int main()
{
vector a = initVector(3,pi/6);
vector b = initVector(5,2*pi/3);
printf("\nVector a : ");
printVector(a);
printf("\n\nVector b : ");
printVector(b);
printf("\n\nSum of vectors a and b : ");
printVector(addVector(a,b));
printf("\n\nDifference of vectors a and b : ");
printVector(subtractVector(a,b));
printf("\n\nMultiplying vector a by 3 : ");
printVector(multiplyVector(a,3));
printf("\n\nDividing vector b by 2.5 : ");
printVector(divideVector(b,2.5));
return 0;
}
|
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.
| #C.2B.2B | C++ | #include <boost/cstdint.hpp>
boost::int_least32_t foo; |
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.
| #D | D | typedef long[0] zeroLength ;
writefln(zeroLength.sizeof) ; // print 0 |
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.
| #Erlang | Erlang | 15> <<1:11>>.
<<0,1: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.
| #ERRE | ERRE | DIM A%[10] ! the array size is 10 integers
DIM B[10] ! the array will hold 10 floating point values
DIM C$[12] ! a character array of 12 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.
| #Fortran | Fortran | program setsize
implicit none
integer, parameter :: p1 = 6
integer, parameter :: p2 = 12
integer, parameter :: r1 = 30
integer, parameter :: r2 = 1000
integer, parameter :: r3 = 2
integer, parameter :: r4 = 4
integer, parameter :: r5 = 8
integer, parameter :: r6 = 16
integer, parameter :: rprec1 = selected_real_kind(p1, r1)
integer, parameter :: rprec2 = selected_real_kind(p2, r1)
integer, parameter :: rprec3 = selected_real_kind(p2, r2)
integer, parameter :: iprec1 = selected_int_kind(r3)
integer, parameter :: iprec2 = selected_int_kind(r4)
integer, parameter :: iprec3 = selected_int_kind(r5)
integer, parameter :: iprec4 = selected_int_kind(r6)
real(rprec1) :: n1
real(rprec2) :: n2
real(rprec3) :: n3
integer(iprec1) :: n4
integer(iprec2) :: n5
integer(iprec3) :: n6
integer(iprec4) :: n7
character(30) :: form
form = "(a7, i11, i10, i6, i9, i8)"
write(*, "(a)") "KIND NAME KIND NUMBER PRECISION RANGE "
write(*, "(a)") " min set min set"
write(*, "(a)") "______________________________________________________"
write(*, form) "rprec1", kind(n1), p1, precision(n1), r1, range(n1)
write(*, form) "rprec2", kind(n2), p2, precision(n2), r1, range(n2)
write(*, form) "rprec3", kind(n3), p2, precision(n3), r2, range(n3)
write(*,*)
form = "(a7, i11, i25, i8)"
write(*, form) "iprec1", kind(n4), r3, range(n4)
write(*, form) "iprec2", kind(n5), r4, range(n5)
write(*, form) "iprec3", kind(n6), r5, range(n6)
write(*, form) "iprec4", kind(n7), r6, range(n7)
end program |
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.
| #Red | Red | Red [
Source: https://github.com/vazub/rosetta-red
Tabs: 4
Needs: 'View
]
comment {
This is a naive and therefore inefficient approach. For production-related tasks,
a proper full implementation of Fortune's algorithm should be preferred.
}
canvas: 500x500
num-points: 50
diagram-l1: make image! canvas
diagram-l2: make image! canvas
distance: function [
"Find Taxicab (d1) and Euclidean (d2) distances between two points"
pt1 [pair!]
pt2 [pair!]
][
d1: (absolute (pt1/x - pt2/x)) + absolute (pt1/y - pt2/y)
d2: square-root ((pt1/x - pt2/x) ** 2 + ((pt1/y - pt2/y) ** 2))
reduce [d1 d2]
]
;-- Generate random origin points with respective region colors
points: collect [
random/seed now/time/precise
loop num-points [
keep random canvas
keep random white
]
]
;-- Color each pixel, based on region it belongs to
repeat y canvas/y [
repeat x canvas/x [
coord: as-pair x y
min-dist: distance 1x1 canvas
color-l1: color-l2: none
foreach [point color] points [
d: distance point coord
if d/1 < min-dist/1 [min-dist/1: d/1 color-l1: color]
if d/2 < min-dist/2 [min-dist/2: d/2 color-l2: color]
]
poke diagram-l1 coord color-l1
poke diagram-l2 coord color-l2
]
]
;-- Draw origin points for regions
foreach [point color] points [
draw diagram-l1 compose [circle (point) 1]
draw diagram-l2 compose [circle (point) 1]
]
;-- Put results on screen
view [
title "Voronoi Diagram"
image diagram-l1 image diagram-l2
]
|
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.
| #ReScript | ReScript | let n_sites = 60
let size_x = 640
let size_y = 480
let rand_int_range = (a, b) => a + Random.int(b - a + 1)
let dist_euclidean = (x, y) => { (x * x + y * y) }
let dist_minkowski = (x, y) => { (x * x * x + y * y * y) }
let dist_taxicab = (x, y) => { abs(x) + abs(y) }
let dist_f = dist_euclidean
let dist_f = dist_minkowski
let dist_f = dist_taxicab
let nearest_site = (site, x, y) => {
let ret = ref(0)
let dist = ref(0)
Js.Array2.forEachi(site, ((sx, sy), k) => {
let d = dist_f((x - sx), (y - sy))
if (k == 0 || d < dist.contents) {
dist.contents = d
ret.contents = k
}
})
ret.contents
}
let gen_map = (site, rgb) => {
let nearest = Belt.Array.make((size_x * size_y), 0)
let buf = Belt.Array.make((3 * size_x * size_y), 0)
for y in 0 to size_y - 1 {
for x in 0 to size_x - 1 {
nearest[y * size_x + x] = nearest_site(site, x, y)
}
}
for i in 0 to (size_y * size_x) - 1 {
let j = i * 3
let (r, g, b) = rgb[nearest[i]]
buf[j+0] = r
buf[j+1] = g
buf[j+2] = b
}
Printf.printf("P3\n%d %d\n255\n", size_x, size_y)
Js.Array2.forEach(buf, (d) => Printf.printf("%d\n", d))
}
{
Random.self_init ();
let site =
Belt.Array.makeBy(n_sites, (i) => {
(Random.int(size_x),
Random.int(size_y))
})
let rgb =
Belt.Array.makeBy(n_sites, (i) => {
(rand_int_range( 50, 120),
rand_int_range( 80, 180),
rand_int_range(140, 240))
})
gen_map(site, rgb)
}
|
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | discreteUniformDistributionQ[data_, {min_Integer, max_Integer}, confLevel_: .05] :=
If[$VersionNumber >= 8,
confLevel <= PearsonChiSquareTest[data, DiscreteUniformDistribution[{min, max}]],
Block[{v, k = max - min, n = Length@data},
v = (k + 1) (Plus @@ (((Length /@ Split[Sort@data]))^2))/n - n;
GammaRegularized[k/2, 0, v/2] <= 1 - confLevel]]
discreteUniformDistributionQ[data_] :=discreteUniformDistributionQ[data, data[[Ordering[data][[{1, -1}]]]]] |
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.
| #Nim | Nim | import lenientops, math, stats, strformat, sugar
func simpson38(f: (float) -> float; a, b: float; n: int): float =
let h = (b - a) / n
let h1 = h / 3
var sum = f(a) + f(b)
for i in countdown(3 * n - 1, 1):
if i mod 3 == 0:
sum += 2 * f(a + h1 * i)
else:
sum += 3 * f(a + h1 * i)
result = h * sum / 8
func gammaIncQ(a, x: float): float =
let aa1 = a - 1
func f(t: float): float = pow(t, aa1) * exp(-t)
var y = aa1
let h = 1.5e-2
while f(y) * (x - y) > 2e-8 and y < x:
y += 0.4
if y > x: y = x
result = 1 - simpson38(f, 0, y, (y / h / gamma(a)).toInt)
func chi2ud(ds: openArray[int]): float =
let expected = mean(ds)
var s = 0.0
for d in ds:
let x = d.toFloat - expected
s += x * x
result = s / expected
func chi2p(dof: int; distance: float): float =
gammaIncQ(0.5 * dof, 0.5 * distance)
const SigLevel = 0.05
proc utest(dset: openArray[int]) =
echo "Uniform distribution test"
let s = sum(dset)
echo " dataset:", dset
echo " samples: ", s
echo " categories: ", dset.len
let dof = dset.len - 1
echo " degrees of freedom: ", dof
let dist = chi2ud(dset)
echo " chi square test statistic: ", dist
let p = chi2p(dof, dist)
echo " p-value of test statistic: ", p
let sig = p < SigLevel
echo &" significant at {int(SigLevel * 100)}% level? {sig}"
echo &" uniform? {not sig}\n"
for dset in [[199809, 200665, 199607, 200270, 199649],
[522573, 244456, 139979, 71531, 21461]]:
utest(dset) |
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
| #FreeBASIC | FreeBASIC |
Function Filtrar(cadorigen As String) As String
Dim As String letra
Dim As String filtrado = ""
For i As Integer = 1 To Len(cadorigen)
letra = Ucase(Mid(cadorigen, i, 1))
If Instr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", letra) Then filtrado += letra
Next i
Return filtrado
End Function
Function Encriptar(texto As String, llave As String) As String
texto = Filtrar(texto)
Dim As String mSS, kSS, letra, cifrado = ""
Dim As Integer m, k, c, j = 1
For i As Integer = 1 To Len(texto)
mSS = Mid(texto, i, 1)
m = Asc(mSS) - Asc("A")
kSS = Mid(llave, j, 1)
k = Asc(kSS) - Asc("A")
j = (j Mod Len(llave)) + 1
c = (m + k) Mod 26
letra = Chr(Asc("A") + c)
cifrado += letra
Next i
Return cifrado
End Function
Function DesEncriptar(texto As String, llave As String) As String
Dim As String mSS, kSS, letra, descifrado = ""
Dim As Integer m, k, c, j = 1
For i As Integer = 1 To Len(texto)
mSS = Mid(texto, i, 1)
m = Asc(mSS) - Asc("A")
kSS = Mid(llave, j, 1)
k = Asc(kSS) - Asc("A")
j = (j Mod Len(llave)) + 1
c = (m - k + 26) Mod 26
letra = Chr(Asc("A")+c)
descifrado += letra
Next i
Return descifrado
End Function
Dim Shared As String llave
llave = Filtrar("vigenerecipher")
Dim As String cadorigen = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
Print cadorigen
Print llave
Dim As String cadcifrada = Encriptar(cadorigen, llave)
Print " Cifrado: "; cadcifrada
Print "Descifrado: "; DesEncriptar(cadcifrada, llave)
Sleep
|
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.
| #Julia | Julia | using Gadfly, LightGraphs, GraphPlot
gx = kronecker(5, 12, 0.57, 0.19, 0.19)
gplot(gx)
|
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.
| #Kotlin | Kotlin | // version 1.2.0
import java.util.Random
class Stem(var str: String? = null, var next: Stem? = null)
const val SDOWN = " |"
const val SLAST = " `"
const val SNONE = " "
val rand = Random()
fun tree(root: Int, head: Stem?) {
val col = Stem()
var head2 = head
var tail = head
while (tail != null) {
print(tail.str)
if (tail.next == null) break
tail = tail.next
}
println("--$root")
if (root <= 1) return
if (tail != null && tail.str == SLAST) tail.str = SNONE
if (tail == null) {
head2 = col
tail = head2
}
else {
tail.next = col
}
var root2 = root
while (root2 != 0) { // make a tree by doing something random
val r = 1 + rand.nextInt(root2)
root2 -= r
col.str = if (root2 != 0) SDOWN else SLAST
tree(r, head2)
}
tail.next = null
}
fun main(args: Array<String>) {
val n = 8
tree(n, null)
} |
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).
| #Ring | Ring |
###---------------------------------------
### Directory Tree Walk
### Look for FileType for Music and Video
fileType = [".avi", ".mp4", ".mpg", ".mkv", ".mp3", ".wmv" ]
dirList = []
musicList = []
###---------------------------------------
### Main
###-----------------------------------
### Start at this directory
searchVideoMusic("C:\Users\Umberto\")
see nl +"Number of Music and Videos files: " +len(musicList) +nl +nl
see musicList
See nl +"Finished" +nl
###=======================================
### Search for Video and Music files
Func searchVideoMusic(startDir)
ChDir(startDir + "Music") ### <<<== add Music subpath C:\Users\Umberto\Music
listDir( CurrentDir() )
ChDir(startDir + "Videos") ### <<<== add Videos subpath C:\Users\Umberto\Videos
listDir( CurrentDir() )
for searchDir in dirList ### Search Directory List for Music and Videos files
listDir(searchDir)
next
###==============================
### Find Files in Directory
Func listDir(dirName)
ChDir(dirName)
Try
###-------------------------------------
### Get SubDirectories
myListSub = Dir( CurrentDir() )
Catch
###-------------------------------------
### Error, Couldn't open the directory
See "ListDir Catch! " + CurrentDir() +" --- "+ cCatchError +nl
return
Done
for x in myListSub
if x[2]
thisDir = x[1]
if thisDir[1] = "."
### Do Nothing. Ignore dot.name
else
see nl +"Dir: " + CurrentDir() +"\"+ thisDir + nl
###----------------------------------------
### Directory Walk add to directory list
Add( dirList, (CurrentDir() +"\"+ thisDir))
ok
else
thisFile = x[1]
###-------------------------------
### Add Music or Video file type
for thisType in fileType
if ( substr(thisFile, thisType) ) ### <<<== Type of File from List
see " File: " + thisFile + nl
Add(musicList, (CurrentDir() +"\"+ thisFile))
ok
next
ok
next
return
###===============================================
|
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).
| #Ruby | Ruby | # Files under this directory:
Dir.glob('*') { |file| puts file }
# Files under path '/foo/bar':
Dir.glob( File.join('/foo/bar', '*') ) { |file| puts file }
# As a method
def file_match(pattern=/\.txt/, path='.')
Dir[File.join(path,'*')].each do |file|
puts file if file =~ pattern
end
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).
| #Lua | Lua | local lfs = require("lfs")
-- This function takes two arguments:
-- - the directory to walk recursively;
-- - an optional function that takes a file name as argument, and returns a boolean.
function find(self, fn)
return coroutine.wrap(function()
for f in lfs.dir(self) do
if f ~= "." and f ~= ".." then
local _f = self .. "/" .. f
if not fn or fn(_f) then
coroutine.yield(_f)
end
if lfs.attributes(_f, "mode") == "directory" then
for n in find(_f, fn) do
coroutine.yield(n)
end
end
end
end
end)
end
-- Examples
-- List all files and directories
for f in find("directory") do
print(f)
end
-- List lua files
for f in find("directory", function(self) return self:match("%.lua$") end) do
print(f)
end
-- List directories
for f in find("directory", function(self) return "directory" == lfs.attributes(self, "mode") end) do
print(f)
end |
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.
| #M2000_Interpreter | M2000 Interpreter |
Module Water {
Flush ' empty stack
Data (1, 5, 3, 7, 2)
Data (5, 3, 7, 2, 6, 4, 5, 9, 1, 2)
Data (2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1)
Data (5, 5, 5, 5), (5, 6, 7, 8),(8, 7, 7, 6)
Data (6, 7, 10, 7, 6)
bars=stack.size ' mark stack frame
Dim bar()
for bar=1 to bars
bar()=Array ' pop an array from stack
acc=0
For i=1 to len(bar())-2
level1=bar(i)
level2=level1
m=each(bar(), i+1, 1)
while m
if array(m)>level1 then level1=array(m)
End While
n=each(bar(), i+1, -1)
while n
if array(n)>level2 then level2=array(n)
End While
acc+=max.data(min(level1, level2)-bar(i), 0)
Next i
Data acc ' push to end value
Next bar
finalwater=[] ' is a stack object
Print finalwater
}
Water
|
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #QBasic | QBasic | 'QBasic can switch VGA modes
SCREEN 18 'Mode 12h 640x480 16 colour graphics |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #Raku | Raku | my @info = QX('xrandr -q').lines;
@info[0] ~~ /<?after 'current '>(\d+) ' x ' (\d+)/;
my $current = "$0x$1";
my @resolutions;
@resolutions.push: $0 if $_ ~~ /^\s+(\d+'x'\d+)/ for @info;
QX("xrandr -s @resolutions[*-1]");
say "Current resolution {@resolutions[*-1]}.";
for 9 ... 1 {
print "\rChanging back in $_ seconds...";
sleep 1;
}
QX("xrandr -s $current");
say "\rResolution returned to {$current}. "; |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #REXX | REXX | /*REXX program to switch video display modes based on columns and lines.*/
parse arg cols lines .
'MODE' "CON: COLS="cols 'LINES='lines
/*stick a fork in it, we're done.*/ |
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
| #PARI.2FGP | PARI/GP | dice5()=random(5)+1;
dice7()={
my(t);
while((t=dice5()*5+dice5()) > 26,);
t\3-1
};
cumChi2(chi2,dof)={
my(g=gamma(dof/2));
incgam(dof/2,chi2/2,g)/g
};
test(f,n,alpha=.05)={
v=vector(n,i,f());
my(s,ave,dof,chi2,p);
s=sum(i=1,n,v[i],0.);
ave=s/n;
dof=n-1;
chi2=sum(i=1,n,(v[i]-ave)^2)/ave;
p=cumChi2(chi2,dof);
if(p<alpha,
error("Not flat enough, significance only "p)
,
print("Flat with significance "p);
)
};
test(dice7, 10^5)
test(()->if(random(1000),random(1000),1), 10^5) |
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.
| #C.23 | C# | namespace Vlq
{
using System;
using System.Collections.Generic;
using System.Linq;
public static class VarLenQuantity
{
public static ulong ToVlq(ulong integer)
{
var array = new byte[8];
var buffer = ToVlqCollection(integer)
.SkipWhile(b => b == 0)
.Reverse()
.ToArray();
Array.Copy(buffer, array, buffer.Length);
return BitConverter.ToUInt64(array, 0);
}
public static ulong FromVlq(ulong integer)
{
var collection = BitConverter.GetBytes(integer).Reverse();
return FromVlqCollection(collection);
}
public static IEnumerable<byte> ToVlqCollection(ulong integer)
{
if (integer > Math.Pow(2, 56))
throw new OverflowException("Integer exceeds max value.");
var index = 7;
var significantBitReached = false;
var mask = 0x7fUL << (index * 7);
while (index >= 0)
{
var buffer = (mask & integer);
if (buffer > 0 || significantBitReached)
{
significantBitReached = true;
buffer >>= index * 7;
if (index > 0)
buffer |= 0x80;
yield return (byte)buffer;
}
mask >>= 7;
index--;
}
}
public static ulong FromVlqCollection(IEnumerable<byte> vlq)
{
ulong integer = 0;
var significantBitReached = false;
using (var enumerator = vlq.GetEnumerator())
{
int index = 0;
while (enumerator.MoveNext())
{
var buffer = enumerator.Current;
if (buffer > 0 || significantBitReached)
{
significantBitReached = true;
integer <<= 7;
integer |= (buffer & 0x7fUL);
}
if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))
break;
}
}
return integer;
}
public static void Main()
{
var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };
foreach (var original in integers)
{
Console.WriteLine("Original: 0x{0:X}", original);
//collection
var seq = ToVlqCollection(original);
Console.WriteLine("Sequence: 0x{0}", seq.Select(b => b.ToString("X2")).Aggregate(string.Concat));
var decoded = FromVlqCollection(seq);
Console.WriteLine("Decoded: 0x{0:X}", decoded);
//ints
var encoded = ToVlq(original);
Console.WriteLine("Encoded: 0x{0:X}", encoded);
decoded = FromVlq(encoded);
Console.WriteLine("Decoded: 0x{0:X}", decoded);
Console.WriteLine();
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
} |
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
| #Aime | Aime | void
f(...)
{
integer i;
i = 0;
while (i < count()) {
o_text($i);
o_byte('\n');
i += 1;
}
}
integer
main(void)
{
f("Mary", "had", "a", "little", "lamb");
return 0;
} |
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
| #ALGOL_68 | ALGOL 68 | main:(
MODE STRINT = UNION(STRING, INT, PROC(REF FILE)VOID, VOID);
PROC print strint = (FLEX[]STRINT argv)VOID: (
FOR i TO UPB argv DO
CASE argv[i] IN
(INT i):print(whole(i,-1)),
(STRING s):print(s),
(PROC(REF FILE)VOID f):f(stand out),
(VOID):print(error char)
ESAC;
IF i NE UPB argv THEN print((" ")) FI
OD
);
print strint(("Mary","had",1,"little",EMPTY,new line))
) |
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
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
namespace RosettaVectors
{
public class Vector
{
public double[] store;
public Vector(IEnumerable<double> init)
{
store = init.ToArray();
}
public Vector(double x, double y)
{
store = new double[] { x, y };
}
static public Vector operator+(Vector v1, Vector v2)
{
return new Vector(v1.store.Zip(v2.store, (a, b) => a + b));
}
static public Vector operator -(Vector v1, Vector v2)
{
return new Vector(v1.store.Zip(v2.store, (a, b) => a - b));
}
static public Vector operator *(Vector v1, double scalar)
{
return new Vector(v1.store.Select(x => x * scalar));
}
static public Vector operator /(Vector v1, double scalar)
{
return new Vector(v1.store.Select(x => x / scalar));
}
public override string ToString()
{
return string.Format("[{0}]", string.Join(",", store));
}
}
class Program
{
static void Main(string[] args)
{
var v1 = new Vector(5, 7);
var v2 = new Vector(2, 3);
Console.WriteLine(v1 + v2);
Console.WriteLine(v1 - v2);
Console.WriteLine(v1 * 11);
Console.WriteLine(v1 / 2);
// Works with arbitrary size vectors, too.
var lostVector = new Vector(new double[] { 4, 8, 15, 16, 23, 42 });
Console.WriteLine(lostVector * 7);
Console.ReadLine();
}
}
}
|
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.
| #Free_Pascal | Free Pascal | type
{$packEnum 4}
enum = (x, y, z); |
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.
| #FreeBASIC | FreeBASIC | package main
import (
"fmt"
"unsafe"
)
func main() {
i := 5 // default type is int
r := '5' // default type is rune (which is int32)
f := 5. // default type is float64
c := 5i // default type is complex128
fmt.Println("i:", unsafe.Sizeof(i), "bytes")
fmt.Println("r:", unsafe.Sizeof(r), "bytes")
fmt.Println("f:", unsafe.Sizeof(f), "bytes")
fmt.Println("c:", unsafe.Sizeof(c), "bytes")
iMin := int8(5)
rMin := byte('5')
fMin := float32(5.)
cMin := complex64(5i)
fmt.Println("iMin:", unsafe.Sizeof(iMin), "bytes")
fmt.Println("rMin:", unsafe.Sizeof(rMin), "bytes")
fmt.Println("fMin:", unsafe.Sizeof(fMin), "bytes")
fmt.Println("cMin:", unsafe.Sizeof(cMin), "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.
| #Ring | Ring |
# Project : Voronoi diagram
load "guilib.ring"
load "stdlib.ring"
paint = null
new qapp
{
spots = 100
leftside = 400
rightside = 400
locx = list(spots)
locy = list(spots)
rgb = newlist(spots,3)
seal = newlist(leftside, rightside)
reach = newlist(leftside, rightside)
win1 = new qwidget() {
setwindowtitle("Voronoi diagram")
setgeometry(100,100,800,600)
label1 = new qlabel(win1) {
setgeometry(10,10,800,600)
settext("")
}
new qpushbutton(win1) {
setgeometry(150,550,100,30)
settext("draw")
setclickevent("draw()")
}
show()
}
exec()
}
func draw
p1 = new qpicture()
color = new qcolor() {
setrgb(0,0,255,255)
}
pen = new qpen() {
setcolor(color)
setwidth(1)
}
paint = new qpainter() {
begin(p1)
setpen(pen)
for i =1 to spots
locx[i] = floor(leftside * randomf())
locy[i] = floor(rightside * randomf())
rgb[i][1] = floor(256 * randomf())
rgb[i][2] = floor(256 * randomf())
rgb[i][3] = floor(256 * randomf())
next
for x = 1 to leftside
for y = 1 to rightside
reach[x][y] = pow((locx[1] - x),2) + pow((locy[1] - y),2)
seal[x][y] = 1
next
next
for i = 2 to spots
for x = locx[i] to 0 step -1
if not (chkpos(i,x,1, rightside-1))
exit
ok
next
for x = locx[i] + 1 to leftside - 1
if not (chkpos(i, x, 1, rightside-1))
exit
ok
next
next
for x = 1 to leftside
for y = 1 to rightside
c1 = rgb[seal[x][y]][1]
c2 = rgb[seal[x][y]][2]
c3 = rgb[seal[x][y]][3]
color = new qcolor() { setrgb(c1,c2,c3,255) }
pen = new qpen() { setcolor(color) setwidth(10) }
setpen(pen)
starty = y
nearest = seal[x][y]
for y = (y + 1) to rightside
if seal[x][y] != nearest
y = y - 1
exit
ok
next
paint.drawline(x,starty,x,y + 1)
next
next
endpaint()
}
label1 { setpicture(p1) show() }
return
func chkpos(site,x,starty,endy)
chkpos = 0
dxsqr = 0
dxsqr = pow((locx[site]- x),2)
for y = starty to endy
dsqr = pow((locy[site] - y),2) + dxsqr
if x <= leftside and y <= leftside and x > 0 and y > 0
if dsqr <= reach[x][y]
reach[x][y] = dsqr
seal[x][y] = site
chkpos = 1
ok
ok
next
return chkpos
func randomf()
decimals(10)
str = "0."
for i = 1 to 10
nr = random(9)
str = str + string(nr)
next
return number(str)
|
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.
| #OCaml | OCaml | let sqr x = x *. x
let chi2UniformDistance distrib =
let count, len = Array.fold_left (fun (s, c) e -> s + e, succ c)
(0, 0) distrib in
let expected = float count /. float len in
let distance = Array.fold_left (fun s e ->
s +. sqr (float e -. expected) /. expected
) 0. distrib in
let dof = float (pred len) in
dof, distance
let chi2Proba dof distance =
Gsl_sf.gamma_inc_Q (0.5 *. dof) (0.5 *. distance)
let chi2IsUniform distrib significance =
let dof, distance = chi2UniformDistance distrib in
let likelihoodOfRandom = chi2Proba dof distance in
likelihoodOfRandom > significance
let _ =
List.iter (fun distrib ->
let dof, distance = chi2UniformDistance distrib in
Printf.printf "distribution ";
Array.iter (Printf.printf "\t%d") distrib;
Printf.printf "\tdistance %g" distance;
Printf.printf "\t[%g > 0.05]" (chi2Proba dof distance);
if chi2IsUniform distrib 0.05 then Printf.printf " fair\n"
else Printf.printf " unfair\n"
)
[
[| 199809; 200665; 199607; 200270; 199649 |];
[| 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
| #Go | Go | package main
import "fmt"
type vkey string
func newVigenère(key string) (vkey, bool) {
v := vkey(upperOnly(key))
return v, len(v) > 0 // key length 0 invalid
}
func (k vkey) encipher(pt string) string {
ct := upperOnly(pt)
for i, c := range ct {
ct[i] = 'A' + (c-'A'+k[i%len(k)]-'A')%26
}
return string(ct)
}
func (k vkey) decipher(ct string) (string, bool) {
pt := make([]byte, len(ct))
for i := range pt {
c := ct[i]
if c < 'A' || c > 'Z' {
return "", false // invalid ciphertext
}
pt[i] = 'A' + (c-k[i%len(k)]+26)%26
}
return string(pt), true
}
// upperOnly extracts letters A-Z, a-z from a string and
// returns them all upper case in a byte slice.
// Useful for vkey constructor and encipher function.
func upperOnly(s string) []byte {
u := make([]byte, 0, len(s))
for i := 0; i < len(s); i++ {
c := s[i]
if c >= 'A' && c <= 'Z' {
u = append(u, c)
} else if c >= 'a' && c <= 'z' {
u = append(u, c-32)
}
}
return u
}
const testKey = "Vigenère Cipher"
const testPT = `Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!`
func main() {
fmt.Println("Supplied key: ", testKey)
v, ok := newVigenère(testKey)
if !ok {
fmt.Println("Invalid key")
return
}
fmt.Println("Effective key:", v)
fmt.Println("Plain text:", testPT)
ct := v.encipher(testPT)
fmt.Println("Enciphered:", ct)
dt, ok := v.decipher(ct)
if !ok {
fmt.Println("Invalid ciphertext")
return
}
fmt.Println("Deciphered:", dt)
} |
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.
| #Lingo | Lingo | -- parent script "TreeItem"
-- (minimal implementation with direct property access)
property name
property children
on new (me, itemName)
me.name = itemName
me.children = []
return me
end
on addChild (me, child)
me.children.add(child)
end
-- print a tree
on printTree (me, treeItem, indent)
if voidP(treeItem) then treeItem = me
if voidP(indent) then indent = ""
put indent&treeItem.name
repeat with c in treeItem.children
me.printTree(c, indent&" ")
end repeat
end |
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.
| #Lua | Lua | function makeTree(v,ac)
if type(ac) == "table" then
return {value=v,children=ac}
else
return {value=v}
end
end
function printTree(t,last,prefix)
if last == nil then
printTree(t, false, '')
else
local current = ''
local next = ''
if last then
current = prefix .. '\\-' .. t.value
next = prefix .. ' '
else
current = prefix .. '|-' .. t.value
next = prefix .. '| '
end
print(current:sub(3))
if t.children ~= nil then
for k,v in pairs(t.children) do
printTree(v, k == #t.children, next)
end
end
end
end
printTree(
makeTree('A', {
makeTree('B0', {
makeTree('C1'),
makeTree('C2', {
makeTree('D', {
makeTree('E1'),
makeTree('E2'),
makeTree('E3')
})
}),
makeTree('C3', {
makeTree('F1'),
makeTree('F2'),
makeTree('F3', {makeTree('G')}),
makeTree('F4', {
makeTree('H1'),
makeTree('H2')
})
})
}),
makeTree('B1',{
makeTree('K1'),
makeTree('K2', {
makeTree('L1', {makeTree('M')}),
makeTree('L2'),
makeTree('L3')
}),
makeTree('K3')
})
})
) |
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).
| #Run_BASIC | Run BASIC | files #g, DefaultDir$ + "\*.jpg" ' find all jpg files
if #g HASANSWER() then
count = #g rowcount() ' get count of files
for i = 1 to count
if #g hasanswer() then 'retrieve info for next file
#g nextfile$() 'print name of file
print #g NAME$()
end if
next
end if
wait |
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).
| #Rust | Rust | extern crate docopt;
extern crate regex;
extern crate rustc_serialize;
use docopt::Docopt;
use regex::Regex;
const USAGE: &'static str = "
Usage: rosetta <pattern>
Walks the directory tree starting with the current working directory and
print filenames matching <pattern>.
";
#[derive(Debug, RustcDecodable)]
struct Args {
arg_pattern: String,
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
let re = Regex::new(&args.arg_pattern).unwrap();
let paths = std::fs::read_dir(".").unwrap();
for path in paths {
let path = path.unwrap().path();
let path = path.to_str().unwrap();
if re.is_match(path) {
println!("{}", path);
}
}
} |
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).
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | FileNames["*"]
FileNames["*.png", $RootDirectory]
FileNames["*", {"*"}, Infinity] |
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).
| #MATLAB_.2F_Octave | MATLAB / Octave | function walk_a_directory_recursively(d, pattern)
f = dir(fullfile(d,pattern));
for k = 1:length(f)
fprintf('%s\n',fullfile(d,f(k).name));
end;
f = dir(d);
n = find([f.isdir]);
for k=n(:)'
if any(f(k).name~='.')
walk_a_directory_recursively(fullfile(d,f(k).name), pattern);
end;
end;
end; |
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[waterbetween]
waterbetween[h_List] := Module[{mi, ma, ch},
{mi, ma} = MinMax[h];
Sum[
ch = h - i;
Count[
Flatten@
Position[
ch, _?Negative], _?(Between[
MinMax[Position[ch, _?NonNegative]]])]
,
{i, mi + 1, ma}
]
]
h = {{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}};
waterbetween /@ h |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #Ring | Ring |
system("mode 40, 25")
|
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #Scala | Scala | object VideoDisplayModes extends App {
import java.util.Scanner
def runSystemCommand(command: String) {
val proc = Runtime.getRuntime.exec(command)
val a: Unit = {
val a = new Scanner(proc.getInputStream)
while (a.hasNextLine) println(a.nextLine())
}
proc.waitFor()
println()
}
// query supported display modes
runSystemCommand("xrandr -q")
Thread.sleep(3000)
// change display mode to 1024x768 say (no text output)
runSystemCommand("xrandr -s 1024x768")
Thread.sleep(3000)
// change it back again to 1366x768 (or whatever is optimal for your system)
runSystemCommand("xrandr -s 1366x768")
} |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #smart_BASIC | smart BASIC | GRAPHICS
FILL RECT 50,50 SIZE 50
GRAPHICS MODE CLEAR
FILL RECT 50,50 SIZE 25 |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #UNIX_Shell | UNIX Shell | $ xrandr -q |
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
| #Perl | Perl | sub roll7 { 1+int rand(7) }
sub roll5 { 1+int rand(5) }
sub roll7_5 {
while(1) {
my $d7 = (5*&roll5 + &roll5 - 6) % 8;
return $d7 if $d7;
}
}
my $threshold = 5;
print dist( $_, $threshold, \&roll7 ) for <1001 1000006>;
print dist( $_, $threshold, \&roll7_5 ) for <1001 1000006>;
sub dist {
my($n, $threshold, $producer) = @_;
my @dist;
my $result;
my $expect = $n / 7;
$result .= sprintf "%10d expected\n", $expect;
for (1..$n) { @dist[&$producer]++; }
for my $i (1..7) {
my $v = @dist[$i];
my $pct = ($v - $expect)/$expect*100;
$result .= sprintf "%d %8d %6.1f%%%s\n", $i, $v, $pct, (abs($pct) > $threshold ? ' - skewed' : '');
}
return $result . "\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.
| #D | D | import std.stdio, std.string, std.file, std.algorithm;
/// Variable length quantity (unsigned long, max 63-bit).
struct VLQ {
ulong value;
// This allows VLQ to work like an ulong.
alias value this;
uint extract(in ubyte[] v) pure
in {
assert(v.length > 0);
} body {
immutable limit = min(v.length - 1, 8);
ulong t = 0;
size_t idx = 0;
while ((idx < limit) && ((v[idx] & 0x80) > 0))
t = (t << 7) | (0x7f & v[idx++]);
if (idx > limit)
throw new Exception(
"Too large for ulong or invalid format.");
else
value = (t << 7) | v[idx];
return idx + 1;
}
VLQ from(in ubyte[] v) pure {
extract(v);
return this;
}
@property ubyte[] toVLQ() const pure {
ubyte[] v = [0x7f & value];
for (ulong k = value >>> 7; k > 0; k >>>= 7)
v ~= (k & 0x7f) | 0x80;
if (v.length > 9)
throw new Exception("Too large value.");
v.reverse();
return v;
}
static ulong[] split(in ubyte[] b) pure {
ulong[] res;
VLQ v;
for (size_t i = 0; i < b.length; ) {
i += v.extract(b[i .. $]);
res ~= v.value;
}
return res;
}
string toString() const pure /*nothrow*/ {
return format("(%(%02X:%))", this.toVLQ);
}
}
void main() { // VLQ demo code.
VLQ a = VLQ(0x7f),
b = VLQ(0x4000),
c;
writefln("a:%8x = %s\nb:%8x = %s\nc:%8x = %s",
a.value, a, b.value, b, c.value, c);
// Some operations.
c = (a + 1) * b;
a = c - 1;
b = VLQ().from(a.toVLQ);
a <<= 1;
// Convert ulong to octet sequence.
writefln("\na:%8x = %s\nb:%8x = %s\nc:%8x = %s",
a.value, a, b.value, b, c.value, c);
// Write them to a binary file.
std.file.write("vlqtest.bin", a.toVLQ ~ b.toVLQ ~ c.toVLQ);
// Read them back.
const buf = cast(ubyte[])std.file.read("vlqtest.bin");
writefln("\nFile length: %d bytes.", buf.length);
// Convert octet sequence to ulongs.
foreach (immutable i, immutable v; VLQ.split(buf))
writefln("%d:%8x = %s", i + 1, v, VLQ(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
| #AppleScript | AppleScript | use framework "Foundation"
-- positionalArgs :: [a] -> String
on positionalArgs(xs)
-- follow each argument with a line feed
map(my putStrLn, xs) as string
end positionalArgs
-- namedArgs :: Record -> String
on namedArgs(rec)
script showKVpair
on |λ|(k)
my putStrLn(k & " -> " & keyValue(rec, k))
end |λ|
end script
-- follow each argument name and value with line feed
map(showKVpair, allKeys(rec)) as string
end namedArgs
-- TEST
on run
intercalate(linefeed, ¬
{positionalArgs(["alpha", "beta", "gamma", "delta"]), ¬
namedArgs({epsilon:27, zeta:48, eta:81, theta:8, iota:1})})
--> "alpha
-- beta
-- gamma
-- delta
--
-- epsilon -> 27
-- eta -> 81
-- iota -> 1
-- zeta -> 48
-- theta -> 8
-- "
end run
-- GENERIC FUNCTIONS
-- putStrLn :: a -> String
on putStrLn(a)
(a as string) & linefeed
end putStrLn
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- allKeys :: Record -> [String]
on allKeys(rec)
(current application's NSDictionary's dictionaryWithDictionary:rec)'s allKeys() as list
end allKeys
-- keyValue :: Record -> String -> Maybe String
on keyValue(rec, strKey)
set ca to current application
set v to (ca's NSDictionary's dictionaryWithDictionary:rec)'s objectForKey:strKey
if v is not missing value then
item 1 of ((ca's NSArray's arrayWithObject:v) as list)
else
missing value
end if
end keyValue
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn |
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
| #C.2B.2B | C++ | #include <iostream>
#include <cmath>
#include <cassert>
using namespace std;
#define PI 3.14159265359
class Vector
{
public:
Vector(double ix, double iy, char mode)
{
if(mode=='a')
{
x=ix*cos(iy);
y=ix*sin(iy);
}
else
{
x=ix;
y=iy;
}
}
Vector(double ix,double iy)
{
x=ix;
y=iy;
}
Vector operator+(const Vector& first)
{
return Vector(x+first.x,y+first.y);
}
Vector operator-(Vector first)
{
return Vector(x-first.x,y-first.y);
}
Vector operator*(double scalar)
{
return Vector(x*scalar,y*scalar);
}
Vector operator/(double scalar)
{
return Vector(x/scalar,y/scalar);
}
bool operator==(Vector first)
{
return (x==first.x&&y==first.y);
}
void v_print()
{
cout << "X: " << x << " Y: " << y;
}
double x,y;
};
int main()
{
Vector vec1(0,1);
Vector vec2(2,2);
Vector vec3(sqrt(2),45*PI/180,'a');
vec3.v_print();
assert(vec1+vec2==Vector(2,3));
assert(vec1-vec2==Vector(-2,-1));
assert(vec1*5==Vector(0,5));
assert(vec2/2==Vector(1,1));
return 0;
}
|
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.
| #Go | Go | package main
import (
"fmt"
"unsafe"
)
func main() {
i := 5 // default type is int
r := '5' // default type is rune (which is int32)
f := 5. // default type is float64
c := 5i // default type is complex128
fmt.Println("i:", unsafe.Sizeof(i), "bytes")
fmt.Println("r:", unsafe.Sizeof(r), "bytes")
fmt.Println("f:", unsafe.Sizeof(f), "bytes")
fmt.Println("c:", unsafe.Sizeof(c), "bytes")
iMin := int8(5)
rMin := byte('5')
fMin := float32(5.)
cMin := complex64(5i)
fmt.Println("iMin:", unsafe.Sizeof(iMin), "bytes")
fmt.Println("rMin:", unsafe.Sizeof(rMin), "bytes")
fmt.Println("fMin:", unsafe.Sizeof(fMin), "bytes")
fmt.Println("cMin:", unsafe.Sizeof(cMin), "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.
| #Haskell | Haskell |
import Data.Int
import Foreign.Storable
task name value = putStrLn $ name ++ ": " ++ show (sizeOf value) ++ " byte(s)"
main = do
let i8 = 0::Int8
let i16 = 0::Int16
let i32 = 0::Int32
let i64 = 0::Int64
let int = 0::Int
task "Int8" i8
task "Int16" i16
task "Int32" i32
task "Int64" i64
task "Int" int
|
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.
| #Ruby | Ruby | # frozen_string_literal: true
require_relative 'raster_graphics'
class ColourPixel < Pixel
def initialize(x, y, colour)
@colour = colour
super x, y
end
attr_accessor :colour
def distance_to(px, py)
Math.hypot(px - x, py - y)
end
end
width = 300
height = 200
npoints = 20
pixmap = Pixmap.new(width, height)
@bases = npoints.times.collect do |_i|
ColourPixel.new(
3 + rand(width - 6), 3 + rand(height - 6), # provide a margin to draw a circle
RGBColour.new(rand(256), rand(256), rand(256))
)
end
pixmap.each_pixel do |x, y|
nearest = @bases.min_by { |base| base.distance_to(x, y) }
pixmap[x, y] = nearest.colour
end
@bases.each do |base|
pixmap[base.x, base.y] = RGBColour::BLACK
pixmap.draw_circle(base, 2, RGBColour::BLACK)
end
pixmap.save_as_png('voronoi_rb.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.
| #PARI.2FGP | PARI/GP | cumChi2(chi2,dof)={
my(g=gamma(dof/2));
incgam(dof/2,chi2/2,g)/g
};
test(v,alpha=.05)={
my(chi2,p,s=sum(i=1,#v,v[i]),ave=s/#v);
print("chi^2 statistic: ",chi2=sum(i=1,#v,(v[i]-ave)^2)/ave);
print("p-value: ",p=cumChi2(chi2,#v-1));
if(p<alpha,
print("Significant at the alpha = "alpha" level: not uniform");
,
print("Not significant at the alpha = "alpha" level: uniform");
)
};
test([199809, 200665, 199607, 200270, 199649])
test([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
| #Haskell | Haskell | import Data.Char
import Text.Printf
-- Perform encryption or decryption, depending on f.
crypt f key = map toLetter . zipWith f (cycle key)
where toLetter = chr . (+) (ord 'A')
-- Encrypt or decrypt one letter.
enc k c = (ord k + ord c) `mod` 26
dec k c = (ord c - ord k) `mod` 26
-- Given a key, encrypt or decrypt an input string.
encrypt = crypt enc
decrypt = crypt dec
-- Convert a string to have only upper case letters.
convert = map toUpper . filter isLetter
main :: IO ()
main = do
let key = "VIGENERECIPHER"
text = "Beware the Jabberwock, my son! The jaws that bite, "
++ "the claws that catch!"
encr = encrypt key $ convert text
decr = decrypt key encr
printf " Input: %s\n Key: %s\nEncrypted: %s\nDecrypted: %s\n"
text key encr decr |
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.
| #Maple | Maple | T := GraphTheory:-Graph([1, 2, 3, 4, 5], {{1, 2}, {2, 3}, {2, 4}, {4, 5}}):
GraphTheory:-DrawGraph(T, style = tree); |
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).
| #Scala | Scala | import java.io.File
val dir = new File("/foo/bar").list()
dir.filter(file => file.endsWith(".mp3")).foreach(println) |
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).
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "osfiles.s7i";
const proc: main is func
local
var string: fileName is "";
begin
for fileName range readDir(".") do
if endsWith(fileName, ".sd7") then
writeln(fileName);
end if;
end for;
end func; |
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).
| #MAXScript | MAXScript | fn walkDir dir pattern =
(
dirArr = GetDirectories (dir + "\\*")
for d in dirArr do
(
join dirArr (getDirectories (d + "\\*"))
)
append dirArr (dir + "\\") -- Need to include the original top level directory
for f in dirArr do
(
print (getFiles (f + pattern))
)
)
walkDir "C:" "*.txt" |
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).
| #MoonScript | MoonScript | lfs = require "lfs"
-- This function takes two arguments:
-- - the directory to walk recursively;
-- - an optional function that takes a file name as argument, and returns a boolean.
find = (fn) => coroutine.wrap ->
for f in lfs.dir @
if f ~= "." and f ~= ".."
_f = @.."/"..f
coroutine.yield _f if not fn or fn _f
if lfs.attributes(_f, "mode") == "directory"
coroutine.yield n for n in find _f, fn
-- Examples
-- List all files
print f for f in find "templates"
-- List moonscript files
print f for f in find "templates", => @\match "%.moon$"
-- List directories
print f for f in find "templates", => "directory" == lfs.attributes @, "mode" |
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.
| #Nim | Nim | import math, sequtils, sugar
proc water(barChart: seq[int], isLeftPeak = false, isRightPeak = false): int =
if len(barChart) <= 2:
return
if isLeftPeak and isRightPeak:
return sum(barChart[1..^2].map(x=>min(barChart[0], barChart[^1])-x))
var i: int
if isLeftPeak:
i = maxIndex(barChart[1..^1])+1
else:
i = maxIndex(barChart[0..^2])
return water(barChart[0..i], isLeftPeak, true)+water(barChart[i..^1], true, isRightPeak)
const barCharts = [
@[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]]
const waterUnits = barCharts.map(chart=>water(chart, false, false))
echo(waterUnits)
|
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #Wren | Wren | /* video_display_modes.wren */
class C {
foreign static xrandr(args)
foreign static usleep(usec)
}
// query supported display modes
C.xrandr("-q")
C.usleep(3000)
// change display mode to 1368x768
System.print("\nChanging to 1368 x 768 mode.")
C.xrandr("-s 1368x768")
C.usleep(3000)
// change it back again to 1920x1080
System.print("\nReverting to 1920 x 1080 mode.")
C.xrandr("-s 1920x1080") |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #XPL0 | XPL0 | code SetVid=45;
SetVid(Mode) |
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
| #Phix | Phix | with javascript_semantics
function check(integer fid, range, iterations, atom delta)
--
-- fid: routine_id of function that yields integer 1..range
-- range: the maximum value that is returned from fid
-- iterations: number of iterations to test
-- delta: variance, for example 0.005 means 0.5%
--
-- returns -1/0/1 for impossible/not flat/flat.
--
atom av = iterations/range -- average/expected value
if floor(av)<av-delta*av
or ceil(av)>av+delta*av then
return -1 -- impossible
end if
sequence counts = repeat(0,range)
for i=1 to iterations do
integer cdx = fid()
counts[cdx] += 1
end for
atom max_delta = max(sq_abs(sq_sub(counts,av)))
return max_delta<delta*av
end function
function rand7()
return rand(7)
end function
constant flats = {"impossible","not flat","flat"}
for p=2 to 7 do
integer n = power(10,p)
-- n = n+7-remainder(n,7)
integer flat = check(rand7, 7, n, 0.005)
printf(1,"%d iterations: %s\n",{n,flats[flat+2]})
end for
|
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.
| #Erlang | Erlang | 7> binary:encode_unsigned(2097152).
<<32,0,0>>
8> binary:decode_unsigned(<<32,0,0>>).
2097152
13> binary:encode_unsigned(16#1fffff).
<<31,255,255>>
14> binary:decode_unsigned(<<31,255,255>>).
2097151
|
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.
| #Euphoria | Euphoria | function vlq_encode(integer n)
sequence s
s = {}
while n > 0 do
s = prepend(s, #80 * (length(s) > 0) + and_bits(n, #7F))
n = floor(n / #80)
end while
if length(s) = 0 then
s = {0}
end if
return s
end function
function vlq_decode(sequence s)
integer n
n = 0
for i = 1 to length(s) do
n *= #80
n += and_bits(s[i], #7F)
if not and_bits(s[i], #80) then
exit
end if
end for
return n
end function
function svlg(sequence s)
sequence out
out = ""
for i = 1 to length(s) do
out &= sprintf("#%02x:", {s[i]})
end for
return out[1..$-1]
end function
constant testNumbers = { #200000, #1FFFFF, 1, 127, 128 }
sequence s
for i = 1 to length(testNumbers) do
s = vlq_encode(testNumbers[i])
printf(1, "#%02x -> %s -> #%02x\n", {testNumbers[i], svlg(s), vlq_decode(s)})
end for |
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
| #Applesoft_BASIC | Applesoft BASIC | 10 P$(0) = STR$(5)
20 P$(1) = "MARY"
30 P$(2) = "HAD"
40 P$(3) = "A"
50 P$(4) = "LITTLE"
60 P$(5) = "LAMB"
70 GOSUB 90"VARIADIC FUNCTION
80 END
90 FOR I = 1 TO VAL(P$(0)) : ? P$(I) : P$(I) = "" : NEXT I : P$(0) = "" : RETURN |
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
| #Arturo | Arturo | ;-------------------------------------------
; a quasi-variadic function
;-------------------------------------------
variadic: function [args][
loop args 'arg [
print arg
]
]
; calling function with one block param
; and the arguments inside
variadic ["one" 2 "three"]
;-------------------------------------------
; a function with optional attributes
;-------------------------------------------
variable: function [args][
print ["args:" args]
if? attr? "with" [
print ["with:" attr "with"]
]
else [
print "without attributes"
]
]
variable "yes"
variable.with:"something" "yes!" |
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
| #CLU | CLU | % Parameterized vector class
vector = cluster [T: type] is make, add, sub, mul, div,
get_x, get_y, to_string
% The inner type must support basic math
where T has add: proctype (T,T) returns (T)
signals (overflow, underflow),
sub: proctype (T,T) returns (T)
signals (overflow, underflow),
mul: proctype (T,T) returns (T)
signals (overflow, underflow),
div: proctype (T,T) returns (T)
signals (zero_divide, overflow, underflow)
rep = struct [x,y: T]
% instantiate
make = proc (x,y: T) returns (cvt)
return(rep${x:x, y:y})
end make
% vector addition and subtraction
add = proc (a,b: cvt) returns (cvt)
signals (overflow, underflow)
return(rep${x: up(a).x + up(b).x,
y: up(a).y + up(b).y})
resignal overflow, underflow
end add
sub = proc (a,b: cvt) returns (cvt)
signals (overflow, underflow)
return(rep${x: up(a).x - up(b).x,
y: up(a).y - up(b).y})
resignal overflow, underflow
end sub
% scalar multiplication and division
mul = proc (a: cvt, b: T) returns (cvt)
signals (overflow, underflow)
return(rep${x: up(a).x*b, y: up(a).y*b})
resignal overflow, underflow
end mul
div = proc (a: cvt, b: T) returns (cvt)
signals (zero_divide, overflow, underflow)
return(rep${x: up(a).x/b, y: up(a).y/b})
resignal zero_divide, overflow, underflow
end div
% accessors
get_x = proc (v: cvt) returns (T) return(v.x) end get_x
get_y = proc (v: cvt) returns (T) return(v.y) end get_y
% we can't just use T$unparse for pretty-printing, since
% for floats it always prints the exponential form, and
% that's not very pretty.
% passing in a conversion function at the moment of
% generating the string form is the least bad way.
to_string = proc (v: cvt, f: proctype (T) returns (string))
returns (string)
return("(" || f(v.x) || ", " || f(v.y) || ")")
end to_string
end vector
% this function formats a real somewhat neatly without needing
% extra parameters
format_real = proc (r: real) returns (string)
return(f_form(r, 2, 4))
end format_real
start_up = proc ()
vr = vector[real] % use real numbers
po: stream := stream$primary_output()
% vectors
a: vr := vr$make(5.0, 7.0)
b: vr := vr$make(2.0, 3.0)
% do some math
a_plus_b: vr := a + b
a_minus_b: vr := a - b
a_times_11: vr := a * 11.0
a_div_2: vr := a / 2.0
% show the results
stream$putl(po, " a = " || vr$to_string(a, format_real))
stream$putl(po, " b = " || vr$to_string(b, format_real))
stream$putl(po, " a + b = " || vr$to_string(a_plus_b, format_real))
stream$putl(po, " a - b = " || vr$to_string(a_minus_b, format_real))
stream$putl(po, "a * 11 = " || vr$to_string(a_times_11, format_real))
stream$putl(po, " a / 2 = " || vr$to_string(a_div_2, format_real))
end start_up |
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
| #D | D | import std.stdio;
void main() {
writeln(VectorReal(5, 7) + VectorReal(2, 3));
writeln(VectorReal(5, 7) - VectorReal(2, 3));
writeln(VectorReal(5, 7) * 11);
writeln(VectorReal(5, 7) / 2);
}
alias VectorReal = Vector!real;
struct Vector(T) {
private T x, y;
this(T x, T y) {
this.x = x;
this.y = y;
}
auto opBinary(string op : "+")(Vector rhs) const {
return Vector(x + rhs.x, y + rhs.y);
}
auto opBinary(string op : "-")(Vector rhs) const {
return Vector(x - rhs.x, y - rhs.y);
}
auto opBinary(string op : "/")(T denom) const {
return Vector(x / denom, y / denom);
}
auto opBinary(string op : "*")(T mult) const {
return Vector(x * mult, y * mult);
}
void toString(scope void delegate(const(char)[]) sink) const {
import std.format;
sink.formattedWrite!"(%s, %s)"(x, y);
}
} |
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.
| #Icon_and_Unicon | Icon and Unicon | L := list(10) # 10 element list |
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.
| #J | J | v=: '' |
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.
| #Julia | Julia | types = [Bool, Char, Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64]
for t in types
println("For type ", lpad(t,6), " size is $(sizeof(t)) 8-bit bytes, or ",
lpad(string(8*sizeof(t)), 2), " bits.")
end
primitive type MyInt24 24 end
println("\nFor the 24-bit user defined type MyInt24, size is ", sizeof(MyInt24), " 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.
| #Kotlin | Kotlin | // version 1.0.6
fun main(args: Array<String>) {
/* ranges for variables of the primitive numeric types */
println("A Byte variable has a range of : ${Byte.MIN_VALUE} to ${Byte.MAX_VALUE}")
println("A Short variable has a range of : ${Short.MIN_VALUE} to ${Short.MAX_VALUE}")
println("An Int variable has a range of : ${Int.MIN_VALUE} to ${Int.MAX_VALUE}")
println("A Long variable has a range of : ${Long.MIN_VALUE} to ${Long.MAX_VALUE}")
println("A Float variable has a range of : ${Float.MIN_VALUE} to ${Float.MAX_VALUE}")
println("A Double variable has a range of : ${Double.MIN_VALUE} to ${Double.MAX_VALUE}")
} |
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.
| #Run_BASIC | Run BASIC | graphic #g, 400,400
#g flush()
spots = 100
leftSide = 400
rightSide = 400
dim locX(spots)
dim locY(spots)
dim rgb(spots,3)
dim seal(leftSide, rightSide)
dim reach(leftSide, rightSide)
for i =1 to spots
locX(i) = int(leftSide * rnd(1))
locY(i) = int(rightSide * rnd(1))
rgb(i,1) = int(256 * rnd(1))
rgb(i,2) = int(256 * rnd(1))
rgb(i,3) = int(256 * rnd(1))
#g color(rgb(i,1),rgb(i,2),rgb(i,3))
#g set(locX(i),locY(i))
next i
#g size(1)
' find reach to the first site
for x = 0 to leftSide - 1
for y = 0 to rightSide - 1
reach(x, y) = (locX(1) - x) ^ 2 + (locY(1) - y) ^ 2
seal(x, y) = 1
next y
next x
#g color("darkblue")
' spots other than 1st spot
for i = 2 to spots
for x = locX(i) to 0 step -1 ' looking left
if not(chkPos(i,x,0, rightSide - 1)) then exit for
next x
for x = locX(i) + 1 to leftSide - 1 ' looking right
if not(chkPos(i, x, 0, rightSide - 1)) then exit for
next x
next i
for x = 0 to leftSide - 1
for y = 0 to rightSide - 1
c1 = rgb(seal(x, y),1)
c2 = rgb(seal(x, y),2)
c3 = rgb(seal(x, y),3)
#g color(c1,c2,c3)
startY = y
nearest = seal(x, y)
for y = y + 1 to rightSide
if seal(x, y) <> nearest then y = y - 1 : exit for
next y
#g line(x,startY,x,y + 1)
next y
next x
#g color("black")
#g size(4)
for i =1 to spots
#g set(locX(i),locY(i))
next i
render #g
end
function chkPos(site, x, startY, endY)
dxSqr = (locX(site) - x) ^ 2
for y = startY to endY
dSqr = (locY(site) - y) ^ 2 + dxSqr
if dSqr <= reach(x, y) then
reach(x,y) = dSqr
seal(x,y) = site
chkPos = 1
end if
next y
end function |
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.
| #Rust | Rust | extern crate piston;
extern crate opengl_graphics;
extern crate graphics;
extern crate touch_visualizer;
#[cfg(feature = "include_sdl2")]
extern crate sdl2_window;
extern crate getopts;
extern crate voronoi;
extern crate rand;
use touch_visualizer::TouchVisualizer;
use opengl_graphics::{ GlGraphics, OpenGL };
use graphics::{ Context, Graphics };
use piston::window::{ Window, WindowSettings };
use piston::input::*;
use piston::event_loop::*;
#[cfg(feature = "include_sdl2")]
use sdl2_window::Sdl2Window as AppWindow;
use voronoi::{voronoi, Point, make_polygons};
use rand::Rng;
static DEFAULT_WINDOW_HEIGHT: u32 = 600;
static DEFAULT_WINDOW_WIDTH: u32 = 600;
struct Settings {
lines_only: bool,
random_count: usize
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let mut opts = getopts::Options::new();
opts.optflag("l", "lines_only", "Don't color polygons, just outline them");
opts.optopt("r", "random_count", "On keypress \"R\", put this many random points on-screen", "RANDOMCOUNT");
let matches = opts.parse(&args[1..]).expect("Failed to parse args");
let settings = Settings{
lines_only: matches.opt_present("l"),
random_count: match matches.opt_str("r") {
None => { 50 },
Some(s) => { s.parse().expect("Random count of bad format") }
}
};
event_loop(&settings);
}
fn random_point() -> [f64; 2] {
[rand::thread_rng().gen_range(0., DEFAULT_WINDOW_HEIGHT as f64), rand::thread_rng().gen_range(0., DEFAULT_WINDOW_WIDTH as f64)]
}
fn random_color() -> [f32; 4] {
[rand::random::<f32>(), rand::random::<f32>(), rand::random::<f32>(), 1.0]
}
fn random_voronoi(dots: &mut Vec<[f64;2]>, colors: &mut Vec<[f32;4]>, num: usize) {
dots.clear();
colors.clear();
for _ in 0..num {
dots.push(random_point());
colors.push(random_color());
}
}
fn event_loop(settings: &Settings) {
let opengl = OpenGL::V3_2;
let mut window: AppWindow = WindowSettings::new("Interactive Voronoi", [DEFAULT_WINDOW_HEIGHT, DEFAULT_WINDOW_WIDTH])
.exit_on_esc(true).opengl(opengl).build().unwrap();
let ref mut gl = GlGraphics::new(opengl);
let mut touch_visualizer = TouchVisualizer::new();
let mut events = Events::new(EventSettings::new().lazy(true));
let mut dots = Vec::new();
let mut colors = Vec::new();
let mut mx = 0.0;
let mut my = 0.0;
while let Some(e) = events.next(&mut window) {
touch_visualizer.event(window.size(), &e);
if let Some(button) = e.release_args() {
match button {
Button::Keyboard(key) => {
if key == piston::input::keyboard::Key::N { dots.clear(); colors.clear(); }
if key == piston::input::keyboard::Key::R { random_voronoi(&mut dots, &mut colors, settings.random_count); }
}
Button::Mouse(_) => {
dots.push([mx, my]);
colors.push(random_color());
},
_ => ()
}
};
e.mouse_cursor(|x, y| {
mx = x;
my = y;
});
if let Some(args) = e.render_args() {
gl.draw(args.viewport(), |c, g| {
graphics::clear([1.0; 4], g);
let mut vor_pts = Vec::new();
for d in &dots {
vor_pts.push(Point::new(d[0], d[1]));
}
if vor_pts.len() > 0 {
let vor_diagram = voronoi(vor_pts, DEFAULT_WINDOW_WIDTH as f64);
let vor_polys = make_polygons(&vor_diagram);
for (i, poly) in vor_polys.iter().enumerate() {
if settings.lines_only {
draw_lines_in_polygon(poly, &c, g);
} else {
draw_polygon(poly, &c, g, colors[i]);
}
}
}
for d in &dots {
draw_ellipse(&d, &c, g);
}
});
}
}
}
fn draw_lines_in_polygon<G: Graphics>(
poly: &Vec<Point>,
c: &Context,
g: &mut G,
)
{
let color = [0.0, 0.0, 1.0, 1.0];
for i in 0..poly.len()-1 {
graphics::line(
color,
2.0,
[poly[i].x.into(), poly[i].y.into(), poly[i+1].x.into(), poly[i+1].y.into()],
c.transform,
g
)
}
}
fn draw_polygon<G: Graphics>(
poly: &Vec<Point>,
c: &Context,
g: &mut G,
color: [f32; 4]
) {
let mut polygon_points: Vec<[f64; 2]> = Vec::new();
for p in poly {
polygon_points.push([p.x.into(), p.y.into()]);
}
graphics::polygon(
color,
polygon_points.as_slice(),
c.transform,
g
)
}
fn draw_ellipse<G: Graphics>(
cursor: &[f64; 2],
c: &Context,
g: &mut G,
) {
let color = [0.0, 0.0, 0.0, 1.0];
graphics::ellipse(
color,
graphics::ellipse::circle(cursor[0], cursor[1], 4.0),
c.transform,
g
);
}
|
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.
| #Perl | Perl | use List::Util qw(sum reduce);
use constant pi => 3.14159265;
sub incomplete_G_series {
my($s, $z) = @_;
my $n = 10;
push @numers, $z**$_ for 1..$n;
my @denoms = $s+1;
push @denoms, $denoms[-1]*($s+$_) for 2..$n;
my $M = 1;
$M += $numers[$_-1]/$denoms[$_-1] for 1..$n;
$z**$s / $s * exp(-$z) * $M;
}
sub G_of_half {
my($n) = @_;
if ($n % 2) { f(2*$_) / (4**$_ * f($_)) * sqrt(pi) for int ($n-1) / 2 }
else { f(($n/2)-1) }
}
sub f { reduce { $a * $b } 1, 1 .. $_[0] } # factorial
sub chi_squared_cdf {
my($k, $x) = @_;
my $f = $k < 20 ? 20 : 10;
if ($x == 0) { 0.0 }
elsif ($x < $k + $f*sqrt($k)) { incomplete_G_series($k/2, $x/2) / G_of_half($k) }
else { 1.0 }
}
sub chi_squared_test {
my(@bins) = @_;
$significance = 0.05;
my $n = @bins;
my $N = sum @bins;
my $expected = $N / $n;
my $chi_squared = sum map { ($_ - $expected)**2 / $expected } @bins;
my $p_value = 1 - chi_squared_cdf($n-1, $chi_squared);
return $chi_squared, $p_value, $p_value > $significance ? 'True' : 'False';
}
for $dataset ([199809, 200665, 199607, 200270, 199649], [522573, 244456, 139979, 71531, 21461]) {
printf "C2 = %10.3f, p-value = %.3f, uniform = %s\n", chi_squared_test(@$dataset);
} |
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
| #Icon_and_Unicon | Icon and Unicon | procedure main()
ptext := "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
write("Key = ",ekey := "VIGENERECIPHER")
write("Plain Text = ",ptext)
write("Normalized = ",GFormat(ptext := NormalizeText(ptext)))
write("Enciphered = ",GFormat(ctext := Vignere("e",ekey,ptext)))
write("Deciphered = ",GFormat(ptext := Vignere("d",ekey,ctext)))
end
procedure Vignere(mode,ekey,ptext,alpha) #: Vignere cipher
/alpha := &ucase # default
if *alpha ~= *cset(alpha) then runerr(205,alpha) # no dups
alpha ||:= alpha # unobstructed
every ctext:="" & p:=ptext[i := 1 to *ptext] & k:=ekey[(i-1)%*ekey+1] do
case mode of {
"e"|"encrypt":
ctext||:=map(p,alpha[1+:*alpha/2],alpha[find(k,alpha)+:(*alpha/2)])
"d"|"decrypt":
ctext||:=map(p,alpha[find(k,alpha)+:(*alpha/2)],alpha[1+:*alpha/2])
default: runerr(205,mode)
}
return ctext
end |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | edges = {1 \[DirectedEdge] 2, 1 \[DirectedEdge] 3, 2 \[DirectedEdge] 4, 2 \[DirectedEdge] 5,
3 \[DirectedEdge] 6, 4 \[DirectedEdge] 7};
t = TreeGraph[edges, GraphStyle -> "VintageDiagram"] |
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).
| #Sidef | Sidef | '*.p[lm]'.glob.each { |file| say file } # Perl files under this directory |
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).
| #Smalltalk | Smalltalk | (Directory name: 'a_directory')
allFilesMatching: '*.st' do: [ :f | (f name) displayNl ] |
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).
| #Nanoquery | Nanoquery | import Nanoquery.IO
def get_files(dirname)
local_filenames = new(File).listDir(dirname)
filenames = {}
for i in range(0, len(local_filenames) - 1)
if len(local_filenames) > 0
if not new(File, local_filenames[i]).isDir()
filenames.append(local_filenames[i])
else
filenames += get_files(local_filenames[i])
end
end
end
return filenames
end
f = new(File)
for file in get_files("/")
if lower(f.getExtension(file)) = ".mp3"
println file
end
end |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.