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/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 ██ ...
#D
D
import std.stdio;   void main() { int i = 1; int[][] tba = [ [ 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 ] ];   foreach (t...
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 ...
#C
C
#include <stdlib.h> #include <stdio.h> #include <math.h>   inline int rand5() { int r, rand_max = RAND_MAX - (RAND_MAX % 5); while ((r = rand()) >= rand_max); return r / (rand_max / 5) + 1; }   inline int rand5_7() { int r; while ((r = rand5() * 5 + rand5()) >= 27); return r / 3 - 1; }   /* assumes gen() returns ...
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.
#Liberty_BASIC
Liberty BASIC
  WindowWidth =600 WindowHeight =600   sites = 100 xEdge = 400 yEdge = 400 graphicbox #w.gb1, 10, 10, xEdge, yEdge   open "Voronoi neighbourhoods" for window as #w   #w "trapclose quit" #w.gb1 "down ; fill black ; size 4" #w.gb1 "font courier_new 12"   dim townX( sites), townY( sites), col$( sites)   for i =1 to s...
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 ...
#BASIC256
BASIC256
  function Filtrar(cadorigen) filtrado = "" for i = 1 to length(cadorigen) letra = upper(mid(cadorigen, i, 1)) if instr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", letra) then filtrado += letra next i return filtrado end function   function Encriptar(texto, llave) texto = Filtrar(texto) cifrado = "" j = 1 for i = 1 to le...
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 ...
#D
D
import std.stdio, std.conv, std.algorithm, std.array;   struct Node(T) { T value; Node* left, right; }   string[] treeIndent(T)(in Node!T* t) pure nothrow @safe { if (!t) return ["-- (null)"]; const tr = t.right.treeIndent; return "--" ~ t.value.text ~ t.left.treeIndent.map!q{" |" ~ a}.array ~ ...
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. ...
#M2000_Interpreter
M2000 Interpreter
  Module Show_Files_Standard { \\ we get more (include hidden too) Module InnerWay (folder_path$, pattern$){ olddir$=dir$ dir folder_path$ \\ clear menu list Menu \\ + place export to menu, without showing \\ ! sort to name ...
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. ...
#MACRO-10
MACRO-10
  TITLE DIRWLK - Directory Walker SUBTTL PDP-10 Assembly Language (MACRO-10 @ TOPS-20). KJX 2022.   SEARCH MONSYM,MACSYM  ;Get system-call names. .REQUIRE SYS:MACREL  ;Macros: TMSG, EJSHLT, etc.   STDAC.  ;Define standard register nam...
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis
Vigenère cipher/Cryptanalysis
Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text: MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS...
#Perl
Perl
use strict; use warnings; use feature 'say';   # from Wikipedia my %English_letter_freq = ( E => 12.70, L => 4.03, Y => 1.97, P => 1.93, T => 9.06, A => 8.17, O => 7.51, I => 6.97, N => 6.75, S => 6.33, H => 6.09, R => 5.99, D => 4.25, C => 2.78, U => 2.76, M => 2.41, W => 2.36, F => 2.23, ...
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   ...
#Delphi
Delphi
  program Walk_a_directory;   {$APPTYPE CONSOLE} {$R *.res}   uses System.IOUtils;   var Files: TArray<string>; FileName, Directory: string;   begin Directory := TDirectory.GetCurrentDirectory; // dir = '.', work to Files := TDirectory.GetFiles(Directory, '*.*', TSearchOption.soAllDirectories);   for FileN...
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   ...
#E
E
def walkTree(directory, pattern) { for name => file in directory { if (name =~ rx`.*$pattern.*`) { println(file.getPath()) } if (file.isDirectory()) { walkTree(file, pattern) } } }
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 ██ ...
#Erlang
Erlang
  -module(watertowers). -export([towers/1, demo/0]).   towers(List) -> element(2, tower(List, 0)).   tower([], _) -> {0,0}; tower([H|T], MaxLPrev) -> MaxL = max(MaxLPrev, H), {MaxR, WaterAcc} = tower(T, MaxL), {max(MaxR,H), WaterAcc+max(0, min(MaxR,MaxL)-H)}.   demo() -> Cases = [[1, 5, 3, 7, 2], ...
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 ...
#C.2B.2B
C++
#include <map> #include <iostream> #include <cmath>   template<typename F> bool test_distribution(F f, int calls, double delta) { typedef std::map<int, int> distmap; distmap dist;   for (int i = 0; i < calls; ++i) ++dist[f()];   double mean = 1.0/dist.size();   bool good = true;   for (distmap::iterato...
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 ...
#Clojure
Clojure
(defn verify [rand n & [delta]] (let [rands (frequencies (repeatedly n rand)) avg (/ (reduce + (map val rands)) (count rands)) max-delta (* avg (or delta 1/10)) acceptable? #(<= (- avg max-delta) % (+ avg max-delta))] (for [[num count] (sort rands)] [num count (acceptable? count)])))...
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.
#Lua
Lua
  function love.load( ) love.math.setRandomSeed( os.time( ) ) --set the random seed keys = { } --an empty table where we will store key presses number_cells = 50 --the number of cells we want in our diagram --draw the voronoi diagram to a canvas voronoiDiagram = generateVoronoi( love.graphics.getWidth( ), love.gra...
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at t...
#11l
11l
V MULTIPLICATION_TABLE = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], [2, 3, 4, 0, 1, 7, 8, 9, 5, 6], [3, 4, 0, 1, 2, 8, 9, 5, 6, 7], [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], [5, ...
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 ...
#BBC_BASIC
BBC BASIC
key$ = "LEMON" plaintext$ = "ATTACK AT DAWN" ciphertext$ = FNencrypt(plaintext$, key$) PRINT "Key = """ key$ """" PRINT "Plaintext = """ plaintext$ """" PRINT "Ciphertext = """ ciphertext$ """" PRINT "Decrypted = """ FNdecrypt(ciphertext$, key$) """" END   DEF FNe...
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 ...
#Befunge
Befunge
"VIGENERECIPHER">>>>1\:!v>"A"-\:00p0v >>!#:0#-0#1g#,*#<+:v:-1$_^#!:\+1g00p< \"{"\v>9+2*%"A"+^>$>~>:48*\`#@_::"`"` *84*`<^4+"4"+g0\_^#!+`*55\`\0::-"A"-*
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 ...
#Delphi
Delphi
  program Visualize_a_tree;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type TNode = record _label: string; children: TArray<Integer>; end;   TTree = TArray<TNode>;   TTreeHelper = record helper for TTree procedure AddNode(lb: string; chl: TArray<Integer> = []); end;   procedure Vis(t: TTree)...
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. ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
FileNames["*"] FileNames["*.png", $RootDirectory]
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. ...
#MAXScript
MAXScript
getFiles "C:\\*.txt"
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis
Vigenère cipher/Cryptanalysis
Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text: MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS...
#Phix
Phix
-- -- demo\rosetta\Cryptanalysis.exw -- with javascript_semantics atom t0 = time() constant ciphertext = substitute_all(""" MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS FGRPH JOOFW GUBY...
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   ...
#Elixir
Elixir
defmodule Walk_directory do def recursive(dir \\ ".") do Enum.each(File.ls!(dir), fn file -> IO.puts fname = "#{dir}/#{file}" if File.dir?(fname), do: recursive(fname) end) end end   Walk_directory.recursive
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   ...
#Emacs_Lisp
Emacs Lisp
ELISP> (directory-files-recursively "/tmp/el" "\\.el$") ("/tmp/el/1/c.el" "/tmp/el/a.el" "/tmp/el/b.el")
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 ██ ...
#F.23
F#
  (* A solution I'd show to Euclid !!!!. Nigel Galloway May 4th., 2017 *) let solve n = let (n,_)::(i,e)::g = n|>List.sortBy(fun n->(-(snd n))) let rec fn i g e l = match e with | (n,e)::t when n < i -> fn n g t (l+(i-n-1)*e) | (n,e)::t when n > g -> fn i n t (l+(n-g-1)*e) | (n,t)::e -> f...
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 ...
#Common_Lisp
Common Lisp
(defun check-distribution (function n &optional (delta 1.0)) (let ((bins (make-hash-table))) (loop repeat n do (incf (gethash (funcall function) bins 0))) (loop with target = (/ n (hash-table-count bins)) for key being each hash-key of bins using (hash-value value) when (> (abs (- value ta...
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 ...
#D
D
import std.stdio, std.string, std.math, std.algorithm, std.traits;   /** Bin the answers to fn() and check bin counts are within +/- delta % of repeats/bincount. */ void distCheck(TF)(in TF func, in int nRepeats, in double delta) /*@safe*/ if (isCallable!TF) { int[int] counts; foreach (immutable i; 0 .. nRepeat...
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Needs["ComputationalGeometry`"] DiagramPlot[{{4.4, 14}, {6.7, 15.25}, {6.9, 12.8}, {2.1, 11.1}, {9.5, 14.9}, {13.2, 11.9}, {10.3, 12.3}, {6.8, 9.5}, {3.3, 7.7}, {0.6, 5.1}, {5.3, 2.4}, {8.45, 4.7}, {11.5, 9.6}, {13.8, 7.3}, {12.9, 3.1}, {11, 1.1}}]
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at t...
#C
C
#include <assert.h> #include <stdbool.h> #include <stdio.h> #include <string.h>   static const int d[][10] = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, {...
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 ...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <ctype.h> #include <getopt.h>   #define NUMLETTERS 26 #define BUFSIZE 4096   char *get_input(void);   int main(int argc, char *argv[]) { char const usage[] = "Usage: vinigere [-d] key"; char sign = 1; char const plainm...
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 ...
#Elena
Elena
import system'routines; import extensions;   class Node { string theValue; Node[] theChildren;   constructor new(string value, Node[] children) { theValue := value;   theChildren := children; }   constructor new(string value) <= new(value, new Node[](0));   constructo...
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 ...
#Erlang
Erlang
9> io:fwrite("~1p", [{1, 2, {30, 40}, {{500, 600}, 70}}]). {1, 2, {30, 40}, {{500, 600}, 70}}
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. ...
#Nanoquery
Nanoquery
import Nanoquery.IO   for fname in new(File).listDir("/foo/bar") if lower(new(File, fname).getExtension()) = ".mp3" println filename end end
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. ...
#Nemerle
Nemerle
using System.Console; using System.IO;   module DirWalk { Main() : void { def files = Directory.GetFiles(@"C:\MyDir"); // retrieves only files def files_subs = Directory.GetFileSystemEntries(@"C:\MyDir"); // also retrieves (but does not enter) sub-directories ...
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis
Vigenère cipher/Cryptanalysis
Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text: MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS...
#Python
Python
from string import uppercase from operator import itemgetter   def vigenere_decrypt(target_freqs, input): nchars = len(uppercase) ordA = ord('A') sorted_targets = sorted(target_freqs)   def frequency(input): result = [[c, 0.0] for c in uppercase] for c in input: result[c - or...
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   ...
#Erlang
Erlang
  walk_dir(Path, Pattern) -> filelib:fold_files( Path, Pattern, true, % Recurse fun(File, Accumulator) -> [File|Accumulator] 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 ██ ...
#Factor
Factor
USING: formatting kernel math.statistics math.vectors sequences ;   : area ( seq -- n ) [ cum-max ] [ <reversed> cum-max reverse vmin ] [ v- sum ] tri ;   { { 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 } } [ du...
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 ...
#Elixir
Elixir
defmodule VerifyDistribution do def naive( generator, times, delta_percent ) do dict = Enum.reduce( List.duplicate(generator, times), Map.new, &update_counter/2 ) values = Map.values(dict) average = Enum.sum( values ) / map_size( dict ) delta = average * (delta_percent / 100) fun = fn {_key, value...
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 ...
#Erlang
Erlang
  -module( verify_distribution_uniformity ).   -export( [naive/3] ).   naive( Generator, Times, Delta_percent ) -> Dict = lists:foldl( fun update_counter/2, dict:new(), lists:duplicate(Times, Generator) ), Values = [dict:fetch(X, Dict) || X <- dict:fetch_keys(Dict)], Average = lists:sum( Values ) / dict:siz...
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.
#.D0.9C.D0.9A-61.2F52
МК-61/52
0 П4 0 П5 ИП0 1 - x^2 ИП1 1 - x^2 + КвКор П3 9 П6 КИП6 П8 {x} 2 10^x * П9 [x] ИП5 - x^2 ИП9 {x} 2 10^x * ИП4 - x^2 + КвКор П9 ИП3 - x<0 47 ИП9 П3 ИП6 П7 ИП6 ИП2 - 9 - x>=0 17 КИП7 [x] С/П КИП5 ИП5 ИП1 - x>=0 04 КИП4 ИП4 ИП0 - x>=0 02
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.
#Nim
Nim
  from sequtils import newSeqWith from random import rand, randomize from times import now import libgd   const img_width = 400 img_height = 300 nSites = 20   proc dot(x, y: int): int = x * x + y * y   proc generateVoronoi(img: gdImagePtr) =   randomize(cast[int64](now()))   # random sites let sx = newSeqW...
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at t...
#F.23
F#
  // Verhoeff algorithm. Nigel Galloway: August 26th., 2021 let d,inv,p=let d=[|0;1;2;3;4;5;6;7;8;9;1;2;3;4;0;6;7;8;9;5;2;3;4;0;1;7;8;9;5;6;3;4;0;1;2;8;9;5;6;7;4;0;1;2;3;9;5;6;7;8;5;9;8;7;6;0;4;3;2;1;6;5;9;8;7;1;0;4;3;2;7;6;5;9;8;2;1;0;4;3;8;7;6;5;9;3;2;1;0;4;9;8;7;6;5;4;3;2;1;0|] let p=[|0;1;2;3;4;5;6;7;8;...
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 ...
#C.23
C#
  using System;   namespace VigenereCipher { class VCipher { public string encrypt(string txt, string pw, int d) { int pwi = 0, tmp; string ns = ""; txt = txt.ToUpper(); pw = pw.ToUpper(); foreach (char t in txt) { ...
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 ...
#F.23
F#
type tree = | T of string * tree list   let prefMid = seq { yield "├─"; while true do yield "│ " } let prefEnd = seq { yield "└─"; while true do yield " " } let prefNone = seq { while true do yield "" }   let c2 x y = Seq.map2 (fun u v -> String.concat "" [u; v]) x y   let rec visualize (T(label, children)) pre = ...
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. ...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   import java.util.List   runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method getFileNames(dirname, pattern) public static returns List dir = File(dirname) contents = dir.list() ...
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. ...
#Nim
Nim
import os   for file in walkFiles "/foo/bar/*.mp3": echo file
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis
Vigenère cipher/Cryptanalysis
Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text: MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS...
#Racket
Racket
  #lang at-exp racket   (define max-keylen 30)   (define text @~a{MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB ...
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis
Vigenère cipher/Cryptanalysis
Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text: MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS...
#Raku
Raku
# from Wikipedia constant %English-letter-freq = ( E => 12.70, L => 4.03, Y => 1.97, P => 1.93, T => 9.06, A => 8.17, O => 7.51, I => 6.97, N => 6.75, S => 6.33, H => 6.09, R => 5.99, D => 4.25, C => 2.78, U => 2.76, M => 2.41, W => 2.36, F => 2.23, G => 2.02, B => 1.29, V => 0.98, K...
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   ...
#F.23
F#
open System.IO   let rec getAllFiles dir pattern = seq { yield! Directory.EnumerateFiles(dir, pattern) for d in Directory.EnumerateDirectories(dir) do yield! getAllFiles d pattern }   getAllFiles "c:\\temp" "*.xml" |> Seq.iter (printfn "%s")
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 ██ ...
#FreeBASIC
FreeBASIC
type tower hght as uinteger posi as uinteger end type   sub shellsort( a() as tower ) 'quick and dirty shellsort, not the focus of this exercise dim as uinteger gap = ubound(a), i, j, n=ubound(a) dim as tower temp do gap = int(gap / 2.2) if gap=0 then gap=1 for i=gap to ...
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 ...
#Euler_Math_Toolbox
Euler Math Toolbox
  >function checkrandom (frand$, n:index, delta:positive real) ... $ v=zeros(1,n); $ loop 1 to n; v{#}=frand$(); end; $ K=max(v); $ fr=getfrequencies(v,1:K); $ return max(fr/n-1/K)<delta/sqrt(n); $ endfunction >function dice () := intrandom(1,1,6); >checkrandom("dice",1000000,1) 1 >wd = 0|((1:6)+[-0.01,0.01,0,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 ...
#Factor
Factor
USING: kernel random sequences assocs locals sorting prettyprint math math.functions math.statistics math.vectors math.ranges ; IN: rosetta-code.dice7   ! Output a random integer 1..5. : dice5 ( -- x ) 5 [1,b] random ;   ! Output a random integer 1..7 using dice5 as randomness source. : dice7 ( -- x ) 0 [ dup 2...
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.
#OCaml
OCaml
let n_sites = 220   let size_x = 640 let size_y = 480   let sq2 ~x ~y = (x * x + y * y)   let rand_int_range a b = a + Random.int (b - a + 1)   let nearest_site ~site ~x ~y = let ret = ref 0 in let dist = ref 0 in Array.iteri (fun k (sx, sy) -> let d = sq2 (x - sx) (y - sy) in if k = 0 || d < !dist th...
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at t...
#Go
Go
package main   import "fmt"   var d = [][]int{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2...
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 ...
#C.2B.2B
C++
#include <iostream> #include <string> using namespace std;   class Vigenere { public: string key;   Vigenere(string key) { for(int i = 0; i < key.size(); ++i) { if(key[i] >= 'A' && key[i] <= 'Z') this->key += key[i]; else if(key[i] >= 'a' && key[i] <= 'z') this->key += key[i] +...
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 ...
#Factor
Factor
USE: literals   CONSTANT: mammals { "mammals" { "deer" "gorilla" "dolphin" } } CONSTANT: reptiles { "reptiles" { "turtle" "lizard" "snake" } }   { "animals" ${ mammals reptiles } } dup . 10 margin set .
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. ...
#Objeck
Objeck
use IO;   bundle Default { class Test { function : Main(args : System.String[]) ~ Nil { dir := Directory->List("/src/code"); for(i := 0; i < dir->Size(); i += 1;) { if(dir[i]->EndsWith(".obs")) { dir[i]->PrintLine(); }; }; } } }
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. ...
#Objective-C
Objective-C
NSString *dir = @"/foo/bar";   // Pre-OS X 10.5 NSArray *contents = [[NSFileManager defaultManager] directoryContentsAtPath:dir]; // OS X 10.5+ NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dir error:NULL];   for (NSString *file in contents) if ([[file pathExtension] isEqualToString:@"...
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis
Vigenère cipher/Cryptanalysis
Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text: MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS...
#Rust
Rust
  use std::iter::FromIterator;   const CRYPTOGRAM: &str = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG ALWQC SNWBU BYHCU HKO...
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis
Vigenère cipher/Cryptanalysis
Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text: MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS...
#Tcl
Tcl
package require Tcl 8.6   oo::class create VigenereAnalyzer { variable letterFrequencies sortedTargets constructor {{frequencies { 0.08167 0.01492 0.02782 0.04253 0.12702 0.02228 0.02015 0.06094 0.06966 0.00153 0.00772 0.04025 0.02406 0.06749 0.07507 0.01929 0.00095 0.05987 0.06327 0.09056 0.02758 0.00978 ...
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   ...
#Factor
Factor
USE: io.directories.search   "." t [ dup ".factor" tail? [ print ] [ drop ] if ] each-file
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   ...
#Forth
Forth
  require unix/filestat.fs require unix/libc.fs   : $append ( from len to -- ) 2DUP >R >R COUNT + SWAP MOVE R> R@ C@ + R> C! ;   defer ls-filter   : dots? ( name len -- ? ) drop c@ [char] . = ;   file-stat buffer: statbuf   : isdir ( addr u -- flag ) statbuf lstat ?ior statbuf st_mode w@ S_IFMT and S_IFDIR =...
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 ██ ...
#Go
Go
  package main   import "fmt"   func maxl(hm []int ) []int{ res := make([]int,len(hm)) max := 1 for i := 0; i < len(hm);i++{ if(hm[i] > max){ max = hm[i] } res[i] = max; } return res } func maxr(hm []int ) []int{ res := make([]int,len(hm)) max := 1 for i := len(hm) - 1 ; i >= 0;i--{ if(hm[i] > max){ ...
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 ...
#Forth
Forth
: .bounds ( u1 u2 -- ) ." lower bound = " . ." upper bound = " 1- . cr ; : init-bins ( n -- addr ) cells dup allocate throw tuck swap erase ; : expected ( u1 cnt -- u2 ) over 2/ + swap / ; : calc-limits ( n cnt pct -- low high ) >r expected r> over 100 */ 2dup + 1+ >r - r> ; : make-histogram ( bins xt...
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 ...
#Fortran
Fortran
subroutine distcheck(randgen, n, delta)   interface function randgen integer :: randgen end function randgen end interface   real, intent(in) :: delta integer, intent(in) :: n integer :: i, mval, lolim, hilim integer, allocatable :: buckets(:) integer, allocatable :: rnums(:) logical :: s...
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.
#Perl
Perl
use strict; use warnings; use Imager;   my %type = ( Taxicab => sub { my($px, $py, $x, $y) = @_; abs($px - $x) + abs($py - $y) }, Euclidean => sub { my($px, $py, $x, $y) = @_; ($px - $x)**2 + ($py - $y)**2 }, Minkowski => sub { my($px, $py, $x, $y) = @_; abs($px - $x)**3 + abs($py - $y)**3 ...
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribut...
#11l
11l
V a = 12 V k1_factrl = 1.0 [Float] c c.append(sqrt(2.0 * math:pi)) L(k) 1 .< a c.append(exp(a - k) * (a - k) ^ (k - 0.5) / k1_factrl) k1_factrl *= -k   F gamma_spounge(z) V accm = :c[0] L(k) 1 .< :a accm += :c[k] / (z + k) accm *= exp(-(z + :a)) * (z + :a) ^ (z + 0.5) R accm / z   F GammaInc_Q(a...
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at t...
#J
J
cyc=: | +/~@i. NB. cyclic group, order y ac=: |(+-/~@i.) NB. anticyclic group, order y a2n=: (+#)@ NB. add 2^n di=: (cyc,.cyc a2n),((ac a2n),.ac)   D=: di 5 INV=: ,I.0=D P=: {&(C.1 5 8 9 4 2 7 0;3 6)^:(i.8) i.10   verhoeff=: {{ c=. 0 for_N. |.10 #.inv y do. c=. D{~<c,P{~<(8|N_index),N end. }}   trace...
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 ...
#Ceylon
Ceylon
shared void run() {   function normalize(String text) => text.uppercased.filter(Character.letter);   function crypt(String text, String key, Character(Character, Character) transform) => String { for ([a, b] in zipPairs(normalize(text), normalize(key).cycled)) transform(a, b) };   functi...
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 ...
#F.C5.8Drmul.C3.A6
Fōrmulæ
Dim Shared As Ubyte colores(4) => {7,13,14,3,2}   Sub showTree(n As Integer, A As String) Dim As Integer i, co = 0, b = 1, col Dim As String cs = Left(A, 1)   If cs = "" Then Exit Sub   Select Case cs Case "[" co += 1 : showTree(n + 1, Right(A, Len(A) - 1)) Exit Select Case "]" ...
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. ...
#OCaml
OCaml
#load "str.cma" let contents = Array.to_list (Sys.readdir ".") in let select pat str = Str.string_match (Str.regexp pat) str 0 in List.filter (select ".*\\.jpg") contents
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. ...
#Oz
Oz
declare [Path] = {Module.link ['x-oz://system/os/Path.ozf']} [Regex] = {Module.link ['x-oz://contrib/regex']}   Files = {Filter {Path.readdir "."} Path.isFile} Pattern = ".*\\.oz$" MatchingFiles = {Filter Files fun {$ File} {Regex.search Pattern File} \= false end} in {ForAll MatchingFiles System.showInfo}
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis
Vigenère cipher/Cryptanalysis
Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text: MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS...
#Vedit_macro_language
Vedit macro language
// (1) Copy text into tmp buffer and remove non-alpha chars.   Chdir(PATH_ONLY) BOF Reg_Copy(10, ALL) // copy text to new buffer Buf_Switch(Buf_Free) Reg_Ins(10) BOF Replace ("|!|A", "", BEGIN+ALL+NOERR) // remove non-alpha chars Reg_Copy_Block(10,0,EOB_pos) // @10 = text to be analys...
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   ...
#FreeBASIC
FreeBASIC
#include "dir.bi"   Sub listFiles(Byref filespec As String, Byval attrib As Integer) Dim As Integer count = 0 Dim As String filename = Dir(filespec, attrib) Do While Len(filename) > 0 count += 1 Print filename filename = Dir() Loop Print !"\nArchives count:"; count End Sub   ...
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   ...
#Gambas
Gambas
Public Sub Main() Dim sTemp As String   For Each sTemp In RDir("/etc", "*.d") Print sTemp Next   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 ██ ...
#Groovy
Groovy
  Integer waterBetweenTowers(List<Integer> towers) { // iterate over the vertical axis. There the amount of water each row can hold is // the number of empty spots, minus the empty spots at the beginning and end return (1..towers.max()).collect { height -> // create a string representing the row, ...
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 ...
#FreeBASIC
FreeBASIC
  Randomize Timer Function dice5() As Integer Return Int(Rnd * 5) + 1 End Function   Function dice7() As Integer Dim As Integer temp Do temp = dice5() * 5 + dice5() -6 Loop Until temp < 21 Return (temp Mod 7) +1 End Function   Function distCheck(n As Ulongint, delta As Double) As Ulongint   ...
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.
#Phix
Phix
-- -- demo\rosetta\VoronoiDiagram.exw -- =============================== -- -- Can resize, double or halve the number of sites (press +/-), and toggle -- between Euclid, Manhattan, and Minkowski (press e/m/w). -- with javascript_semantics include pGUI.e Ihandle dlg, canvas, timer cdCanvas cddbuffer, cdcanvas -- Sto...
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribut...
#Ada
Ada
package Chi_Square is   type Flt is digits 18; type Bins_Type is array(Positive range <>) of Natural;   function Distance(Bins: Bins_Type) return Flt;   end Chi_Square;
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribut...
#C
C
#include <stdlib.h> #include <stdio.h> #include <math.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif   typedef double (* Ifctn)( double t); /* Numerical integration method */ double Simpson3_8( Ifctn f, double a, double b, int N) { int j; double l1; double h = (b-a)/N; double h1 = h/3.0; ...
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at t...
#jq
jq
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;   def d: [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], [2, 3, 4, 0, 1, 7, 8, 9, 5, 6], [3, 4, 0, 1, 2, 8, 9, 5, 6, 7], [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], [5, 9, 8, 7, 6, 0, 4, 3, 2, 1], [6, 5, 9, 8, 7, 1...
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at t...
#Julia
Julia
const multiplicationtable = [ 0 1 2 3 4 5 6 7 8 9; 1 2 3 4 0 6 7 8 9 5; 2 3 4 0 1 7 8 9 5 6; 3 4 0 1 2 8 9 5 6 7; 4 0 1 2 3 9 5 6 7 8; 5 9 8 7 6 0 4 3 2 1; 6 5 9 8 7 1 0 4 3 2; 7 6 5 9 8 2 1 0 4 3; 8 7 6 5 9 ...
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 ...
#Clojure
Clojure
(ns org.rosettacode.clojure.vigenere (:require [clojure.string :as string]))   ; convert letter to offset from \A (defn to-num [char] (- (int char) (int \A)))   ; convert number to letter, treating it as modulo 26 offset from \A (defn from-num [num] (char (+ (mod num 26) (int \A))))   ; Convert a string to a sequence...
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 ...
#FreeBASIC
FreeBASIC
Dim Shared As Ubyte colores(4) => {7,13,14,3,2}   Sub showTree(n As Integer, A As String) Dim As Integer i, co = 0, b = 1, col Dim As String cs = Left(A, 1)   If cs = "" Then Exit Sub   Select Case cs Case "[" co += 1 : showTree(n + 1, Right(A, Len(A) - 1)) Exit Select Case "]" ...
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. ...
#Pascal
Pascal
{$H+}   program Walk;   uses SysUtils;   var Res: TSearchRec; Pattern, Path, Name: String; FileAttr: LongInt; Attr: Integer;   begin Write('File pattern: '); ReadLn(Pattern); { For example .\*.pas }   Attr := faAnyFile; if FindFirst(Pattern, Attr, Res) = 0 then begin Path := ...
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. ...
#Perl
Perl
use 5.010; opendir my $dh, '/home/foo/bar'; say for grep { /php$/ } readdir $dh; closedir $dh;
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis
Vigenère cipher/Cryptanalysis
Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text: MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS...
#Vlang
Vlang
import strings const encoded = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" + "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" + "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" + "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" + "ALWQC SNWBU...
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis
Vigenère cipher/Cryptanalysis
Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text: MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS...
#Wren
Wren
import "/math" for Nums import "/trait" for Stepped import "/str" for Char, Str import "/fmt" for Fmt   var encoded = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" + "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" + "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS"...
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   ...
#GAP
GAP
Walk := function(name, op) local dir, file, e; dir := Directory(name); for e in SortedList(DirectoryContents(name)) do file := Filename(dir, e); if IsDirectoryPath(file) then if not (e in [".", ".."]) then Walk(file, op); fi; else op(file); fi; od; end;   # This will print filenames Walk(".", D...
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   ...
#Go
Go
package main   import ( "fmt" "os" "path/filepath" )   func VisitFile(fp string, fi os.FileInfo, err error) error { if err != nil { fmt.Println(err) // can't walk here, return nil // but continue walking elsewhere } if fi.IsDir() { return nil // not a file. ignore....
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 ██ ...
#Haskell
Haskell
import Data.Vector.Unboxed (Vector) import qualified Data.Vector.Unboxed as V   waterCollected :: Vector Int -> Int waterCollected = V.sum . -- Sum of the water depths over each of V.filter (> 0) . -- the columns that are covered by some water. (V.zipWith (-) =<< -- Where coverages are differences be...
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 ...
#Go
Go
package main   import ( "fmt" "math" "math/rand" "time" )   // "given" func dice5() int { return rand.Intn(5) + 1 }   // function specified by task "Seven-sided dice from five-sided dice" func dice7() (i int) { for { i = 5*dice5() + dice5() if i < 27 { break }...
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.
#Processing
Processing
void setup() { size(500, 500); generateVoronoiDiagram(width, height, 25); saveFrame("VoronoiDiagram.png"); }   void generateVoronoiDiagram(int w, int h, int num_cells) { int nx[] = new int[num_cells]; int ny[] = new int[num_cells]; int nr[] = new int[num_cells]; int ng[] = new int[num_cells]; int nb[] =...
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribut...
#D
D
import std.stdio, std.algorithm, std.mathspecial;   real x2Dist(T)(in T[] data) pure nothrow @safe @nogc { immutable avg = data.sum / data.length; immutable sqs = reduce!((a, b) => a + (b - avg) ^^ 2)(0.0L, data); return sqs / avg; }   real x2Prob(in real dof, in real distance) pure nothrow @safe @nogc { ...
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at t...
#Nim
Nim
import strformat   const   D = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], [2, 3, 4, 0, 1, 7, 8, 9, 5, 6], [3, 4, 0, 1, 2, 8, 9, 5, 6, 7], [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], [5, 9, 8, 7, 6, 0, 4, 3, 2, 1], [6, 5, 9, 8, 7, 1, 0, 4, 3, 2], [7, 6, 5, 9, ...
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at t...
#Perl
Perl
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Verhoeff_algorithm use warnings;   my @inv = qw(0 4 3 2 1 5 6 7 8 9);   my @d = map [ split ], split /\n/, <<END; 0 1 2 3 4 5 6 7 8 9 1 2 3 4 0 6 7 8 9 5 2 3 4 0 1 7 8 9 5 6 3 4 0 1 2 8 9 5 6 7 4 0 1 2 3 9 5 6 7 8 ...
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 ...
#CoffeeScript
CoffeeScript
# Simple helper since charCodeAt is quite long to write. code = (char) -> char.charCodeAt()   encrypt = (text, key) -> res = [] j = 0   for c in text.toUpperCase() continue if c < 'A' or c > 'Z'   res.push ((code c) + (code key[j]) - 130) % 26 + 65 j = ++j % key.length   String.fromCharCode res...   decrypt =...
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 ...
#Go
Go
package main   import ( "encoding/json" "fmt" "log" )   type Node struct { Name string Children []*Node }   func main() { tree := &Node{"root", []*Node{ &Node{"a", []*Node{ &Node{"d", nil}, &Node{"e", []*Node{ &Node{"f", nil}, }}}},...
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. ...
#Phix
Phix
puts(1,join(columnize(dir("*.txt"))[D_NAME],"\n"))
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. ...
#PHP
PHP
$pattern = 'php'; $dh = opendir('c:/foo/bar'); // Or '/home/foo/bar' for Linux while (false !== ($file = readdir($dh))) { if ($file != '.' and $file != '..') { if (preg_match("/$pattern/", $file)) { echo "$file matches $pattern\n"; } } } closedir($dh);
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis
Vigenère cipher/Cryptanalysis
Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text: MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS...
#zkl
zkl
var[const] uppercase=["A".."Z"].pump(String), english_frequences=T( // A..Z 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0....