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/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.
#C.2B.2B
C++
  #include <windows.h> #include <vector> #include <string>   using namespace std;   ////////////////////////////////////////////////////// struct Point { int x, y; };   ////////////////////////////////////////////////////// class MyBitmap { public: MyBitmap() : pen_(nullptr) {} ~MyBitmap() { DeleteObject(pen_); DeleteDC(hdc_); DeleteObject(bmp_); }   bool Create(int w, int h) { BITMAPINFO bi; ZeroMemory(&bi, sizeof(bi));   bi.bmiHeader.biSize = sizeof(bi.bmiHeader); bi.bmiHeader.biBitCount = sizeof(DWORD) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h;   void *bits_ptr = nullptr; HDC dc = GetDC(GetConsoleWindow()); bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0); if (!bmp_) return false;   hdc_ = CreateCompatibleDC(dc); SelectObject(hdc_, bmp_); ReleaseDC(GetConsoleWindow(), dc);   width_ = w; height_ = h;   return true; }   void SetPenColor(DWORD clr) { if (pen_) DeleteObject(pen_); pen_ = CreatePen(PS_SOLID, 1, clr); SelectObject(hdc_, pen_); }   bool SaveBitmap(const char* path) { HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (file == INVALID_HANDLE_VALUE) { return false; }   BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; GetObject(bmp_, sizeof(bitmap), &bitmap);   DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD)); ZeroMemory(&infoheader, sizeof(BITMAPINFO)); ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));   infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);   fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;   GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);   DWORD wb; WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr); WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr); WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr); CloseHandle(file);   delete[] dwp_bits; return true; }   HDC hdc() { return hdc_; } int width() { return width_; } int height() { return height_; }   private: HBITMAP bmp_; HDC hdc_; HPEN pen_; int width_, height_; };   static int DistanceSqrd(const Point& point, int x, int y) { int xd = x - point.x; int yd = y - point.y; return (xd * xd) + (yd * yd); }   ////////////////////////////////////////////////////// class Voronoi { public: void Make(MyBitmap* bmp, int count) { bmp_ = bmp; CreatePoints(count); CreateColors(); CreateSites(); SetSitesPoints(); }   private: void CreateSites() { int w = bmp_->width(), h = bmp_->height(), d; for (int hh = 0; hh < h; hh++) { for (int ww = 0; ww < w; ww++) { int ind = -1, dist = INT_MAX; for (size_t it = 0; it < points_.size(); it++) { const Point& p = points_[it]; d = DistanceSqrd(p, ww, hh); if (d < dist) { dist = d; ind = it; } }   if (ind > -1) SetPixel(bmp_->hdc(), ww, hh, colors_[ind]); else __asm nop // should never happen! } } }   void SetSitesPoints() { for (const auto& point : points_) { int x = point.x, y = point.y; for (int i = -1; i < 2; i++) for (int j = -1; j < 2; j++) SetPixel(bmp_->hdc(), x + i, y + j, 0); } }   void CreatePoints(int count) { const int w = bmp_->width() - 20, h = bmp_->height() - 20; for (int i = 0; i < count; i++) { points_.push_back({ rand() % w + 10, rand() % h + 10 }); } }   void CreateColors() { for (size_t i = 0; i < points_.size(); i++) { DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50); colors_.push_back(c); } }   vector<Point> points_; vector<DWORD> colors_; MyBitmap* bmp_; };   ////////////////////////////////////////////////////// int main(int argc, char* argv[]) { ShowWindow(GetConsoleWindow(), SW_MAXIMIZE); srand(GetTickCount());   MyBitmap bmp; bmp.Create(512, 512); bmp.SetPenColor(0);   Voronoi v; v.Make(&bmp, 50);   BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY); bmp.SaveBitmap("v.bmp");   system("pause");   return 0; }  
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.
#11l
11l
T Node String value Node? left Node? right   F (value, Node? left = N, Node? right = N) .value = String(value) .left = left .right = right   F tree_indent() -> [String] V tr = I .right != N {.right.tree_indent()} E [‘-- (null)’] R [‘--’(.value)] [+] (I .left != N {.left.tree_indent()} E [‘-- (null)’]).map(a -> ‘ |’a) [+] [‘ `’tr[0]] + tr[1..].map(a -> ‘ ’a)   V tree = Node(1, Node(2, Node(4, Node(7)), Node(5)), Node(3, Node(6, Node(8), Node(9)))) print(tree.tree_indent().join("\n"))
http://rosettacode.org/wiki/Vogel%27s_approximation_method
Vogel's approximation method
Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem. The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that: A will require 30 hours of work, B will require 20 hours of work, C will require 70 hours of work, D will require 30 hours of work, and E will require 60 hours of work. They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”. W has 50 hours available to commit to working, X has 60 hours available, Y has 50 hours available, and Z has 50 hours available. The cost per hour for each contractor for each task is summarized by the following table: A B C D E W 16 16 13 22 17 X 14 14 13 19 15 Y 19 19 20 23 50 Z 50 12 50 15 11 The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows: Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand) Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column. Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell). Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost. Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet. Step 6: Compute total transportation cost for the feasible allocations. For this task assume that the model is balanced. For each task and contractor (row and column above) calculating the difference between the smallest two values produces: A B C D E W X Y Z 1 2 2 0 4 4 3 1 0 1 E-Z(50) Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply). Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working. Repeat until all supply and demand is met: 2 2 2 0 3 2 3 1 0 - C-W(50) 3 5 5 7 4 35 - 1 0 - E-X(10) 4 5 5 7 4 - - 1 0 - C-X(20) 5 5 5 - 4 - - 0 0 - A-X(30) 6 - 19 - 23 - - - 4 - D-Y(30) - - - - - - - - - B-Y(20) Finally calculate the cost of your solution. In the example given it is £3100: A B C D E W 50 X 30 20 10 Y 20 30 Z 50 The optimal solution determined by GLPK is £3100: A B C D E W 50 X 10 20 20 10 Y 20 30 Z 50 Cf. Transportation problem
#Sidef
Sidef
var costs = :( W => :(A => 16, B => 16, C => 13, D => 22, E => 17), X => :(A => 14, B => 14, C => 13, D => 19, E => 15), Y => :(A => 19, B => 19, C => 20, D => 23, E => 50), Z => :(A => 50, B => 12, C => 50, D => 15, E => 11) )   var demand = :(A => 30, B => 20, C => 70, D => 30, E => 60) var supply = :(W => 50, X => 60, Y => 50, Z => 50)   var cols = demand.keys.sort   var (:res, :g) supply.each {|x| g{x} = costs{x}.keys.sort_by{|g| costs{x}{g} }} demand.each {|x| g{x} = costs .keys.sort_by{|g| costs{g}{x} }}   while (g) { var d = demand.collect {|x| [x, var z = costs{g{x}[0]}{x}, g{x}[1] ? costs{g{x}[1]}{x}-z : z] }   var s = supply.collect {|x| [x, var z = costs{x}{g{x}[0]}, g{x}[1] ? costs{x}{g{x}[1]}-z : z] }   d.grep! { .[2] == d.max_by{ .[2] }[2] }.min_by! { .[1] } s.grep! { .[2] == s.max_by{ .[2] }[2] }.min_by! { .[1] }   var (t,f) = (d[2] == s[2] ? ((s[1], d[1])) : ((d[2], s[2]))) (d,s) = (t > f ? ((d[0], g{d[0]}[0])) : ((g{s[0]}[0],s[0])))   var v = (supply{s} `min` demand{d})   res{s}{d} := 0 += v demand{d} -= v   if (demand{d} == 0) { supply.grep {|_,n| n != 0 }.each {|x| g{x}.delete(d) } g.delete(d) demand.delete(d) }   supply{s} -= v   if (supply{s} == 0) { demand.grep {|_,n| n != 0 }.each {|x| g{x}.delete(s) } g.delete(s) supply.delete(s) } }   say("\t", cols.join("\t"))   var cost = 0 costs.keys.sort.each { |g| print(g, "\t") cols.each { |n| if (defined(var y = res{g}{n})) { print(y) cost += (y * costs{g}{n}) } print("\t") } print("\n") }   say "\n\nTotal Cost = #{cost}"
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).
#F.23
F#
System.IO.Directory.GetFiles("c:\\temp", "*.xml") |> Array.iter (printfn "%s")
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).
#Factor
Factor
USING: globs io io.directories kernel regexp sequences ; IN: walk-directory-non-recursively   : print-files ( path pattern -- ) [ directory-files ] [ <glob> ] bi* [ matches? ] curry filter [ print ] each ;
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.
#AppleScript
AppleScript
--------------- WATER COLLECTED BETWEEN TOWERS -------------   -- waterCollected :: [Int] -> Int on waterCollected(xs) set leftWalls to scanl1(my max, xs) set rightWalls to scanr1(my max, xs)   set waterLevels to zipWith(my min, leftWalls, rightWalls)   -- positive :: Num a => a -> Bool script positive on |λ|(x) x > 0 end |λ| end script   -- minus :: Num a => a -> a -> a script minus on |λ|(a, b) a - b end |λ| end script   sum(filter(positive, zipWith(minus, waterLevels, xs))) end waterCollected     ---------------------------- TEST -------------------------- on run map(waterCollected, ¬ [[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]])   --> {2, 14, 35, 0, 0, 0, 0} end run     --------------------- GENERIC FUNCTIONS --------------------   -- filter :: (a -> Bool) -> [a] -> [a] on filter(f, xs) tell mReturn(f) set lst to {} set lng to length of xs repeat with i from 1 to lng set v to item i of xs if |λ|(v, i, xs) then set end of lst to v end repeat return lst end tell end filter   -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl   -- init :: [a] -> [a] on init(xs) if length of xs > 1 then items 1 thru -2 of xs else {} end if end init   -- 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   -- max :: Ord a => a -> a -> a on max(x, y) if x > y then x else y end if end max   -- min :: Ord a => a -> a -> a on min(x, y) if y < x then y else x end if end min   -- 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   -- scanl :: (b -> a -> b) -> b -> [a] -> [b] on scanl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs set lst to {startValue} repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) set end of lst to v end repeat return lst end tell end scanl   -- scanl1 :: (a -> a -> a) -> [a] -> [a] on scanl1(f, xs) if length of xs > 0 then scanl(f, item 1 of xs, items 2 thru -1 of xs) else {} end if end scanl1   -- scanr :: (b -> a -> b) -> b -> [a] -> [b] on scanr(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs set lst to {startValue} repeat with i from lng to 1 by -1 set v to |λ|(v, item i of xs, i, xs) set end of lst to v end repeat return reverse of lst end tell end scanr   -- scanr1 :: (a -> a -> a) -> [a] -> [a] on scanr1(f, xs) if length of xs > 0 then scanr(f, item -1 of xs, items 1 thru -2 of xs) else {} end if end scanr1   -- sum :: Num a => [a] -> a on sum(xs) script add on |λ|(a, b) a + b end |λ| end script   foldl(add, 0, xs) end sum   -- tail :: [a] -> [a] on tail(xs) if length of xs > 1 then items 2 thru -1 of xs else {} end if end tail   -- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] on zipWith(f, xs, ys) set lng to min(length of xs, length of ys) set lst to {} tell mReturn(f) repeat with i from 1 to lng set end of lst to |λ|(item i of xs, item i of ys) end repeat return lst end tell end zipWith
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.
#D
D
import std.random, std.algorithm, std.range, bitmap;   struct Point { uint x, y; }   enum randomPoints = (in size_t nPoints, in size_t nx, in size_t ny) => nPoints.iota .map!((int) => Point(uniform(0, nx), uniform(0, ny))) .array;   Image!RGB generateVoronoi(in Point[] pts, in size_t nx, in size_t ny) /*nothrow*/ { // Generate a random color for each centroid. immutable rndRBG = (int) => RGB(uniform!"[]"(ubyte.min, ubyte.max), uniform!"[]"(ubyte.min, ubyte.max), uniform!"[]"(ubyte.min, ubyte.max)); const colors = pts.length.iota.map!rndRBG.array;   // Generate diagram by coloring pixels with color of nearest site. auto img = new typeof(return)(nx, ny); foreach (immutable x; 0 .. nx) foreach (immutable y; 0 .. ny) { immutable dCmp = (in Point a, in Point b) pure nothrow => ((a.x - x) ^^ 2 + (a.y - y) ^^ 2) < ((b.x - x) ^^ 2 + (b.y - y) ^^ 2); // img[x, y] = colors[pts.reduce!(min!dCmp)]; img[x, y] = colors[pts.length - pts.minPos!dCmp.length]; }   // Mark each centroid with a white dot. foreach (immutable p; pts) img[p.tupleof] = RGB.white; return img; }   void main() { enum imageWidth = 640, imageHeight = 480; randomPoints(150, imageWidth, imageHeight) .generateVoronoi(imageWidth, imageHeight) .savePPM6("voronoi.ppm"); }
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.
#Ada
Ada
with Ada.Text_IO, Ada.Directories;   procedure Directory_Tree is   procedure Print_Tree(Current: String; Indention: Natural := 0) is   function Spaces(N: Natural) return String is (if N= 0 then "" else " " & Spaces(N-1));   use Ada.Directories; Search: Search_Type; Found: Directory_Entry_Type;   begin Start_Search(Search, Current, ""); while More_Entries(Search) loop Get_Next_Entry(Search, Found); declare Name: String := Simple_Name(Found); Dir: Boolean := Kind(Found) = Directory; begin if Name(Name'First) /= '.' then -- skip all files who's names start with ".", namely "." and ".." Ada.Text_IO.Put_Line(Spaces(2*Indention) & Simple_Name(Found) & (if Dir then " (dir)" else "")); if Dir then Print_Tree(Full_Name(Found), Indention + 1); end if; end if; end; end loop; end Print_Tree;   begin Print_Tree(Ada.Directories.Current_Directory); end Directory_Tree;
http://rosettacode.org/wiki/Vogel%27s_approximation_method
Vogel's approximation method
Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem. The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that: A will require 30 hours of work, B will require 20 hours of work, C will require 70 hours of work, D will require 30 hours of work, and E will require 60 hours of work. They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”. W has 50 hours available to commit to working, X has 60 hours available, Y has 50 hours available, and Z has 50 hours available. The cost per hour for each contractor for each task is summarized by the following table: A B C D E W 16 16 13 22 17 X 14 14 13 19 15 Y 19 19 20 23 50 Z 50 12 50 15 11 The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows: Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand) Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column. Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell). Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost. Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet. Step 6: Compute total transportation cost for the feasible allocations. For this task assume that the model is balanced. For each task and contractor (row and column above) calculating the difference between the smallest two values produces: A B C D E W X Y Z 1 2 2 0 4 4 3 1 0 1 E-Z(50) Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply). Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working. Repeat until all supply and demand is met: 2 2 2 0 3 2 3 1 0 - C-W(50) 3 5 5 7 4 35 - 1 0 - E-X(10) 4 5 5 7 4 - - 1 0 - C-X(20) 5 5 5 - 4 - - 0 0 - A-X(30) 6 - 19 - 23 - - - 4 - D-Y(30) - - - - - - - - - B-Y(20) Finally calculate the cost of your solution. In the example given it is £3100: A B C D E W 50 X 30 20 10 Y 20 30 Z 50 The optimal solution determined by GLPK is £3100: A B C D E W 50 X 10 20 20 10 Y 20 30 Z 50 Cf. Transportation problem
#Tcl
Tcl
package require Tcl 8.6   # A sort that works by sorting by an auxiliary key computed by a lambda term proc sortByFunction {list lambda} { lmap k [lsort -index 1 [lmap k $list { list $k [uplevel 1 [list apply $lambda $k]] }]] {lindex $k 0} }   # A simple way to pick a “best” item from a list proc minimax {list maxidx minidx} { set max -Inf; set min Inf foreach t $list { if {[set m [lindex $t $maxidx]] > $max} { set best $t set max $m set min Inf } elseif {$m == $max && [set m [lindex $t $minidx]] < $min} { set best $t set min $m } } return $best }   # The approximation engine. Note that this does not change the provided # arguments at all since they are copied on write. proc VAM {costs demand supply} { # Initialise the sorted sequence of pairs and the result dictionary foreach x [dict keys $demand] { dict set g $x [sortByFunction [dict keys $supply] {g { upvar 1 costs costs x x; dict get $costs $g $x }}] dict set row $x 0 } foreach x [dict keys $supply] { dict set g $x [sortByFunction [dict keys $demand] {g { upvar 1 costs costs x x; dict get $costs $x $g }}] dict set res $x $row }   # While there's work to do... while {[dict size $g]} { # Select "best" demand lassign [minimax [lmap x [dict keys $demand] { if {![llength [set gx [dict get $g $x]]]} continue set z [dict get $costs [lindex $gx 0] $x] if {[llength $gx] > 1} { list $x $z [expr {[dict get $costs [lindex $gx 1] $x] - $z}] } else { list $x $z $z } }] 2 1] d dVal dCost   # Select "best" supply lassign [minimax [lmap x [dict keys $supply] { if {![llength [set gx [dict get $g $x]]]} continue set z [dict get $costs $x [lindex $gx 0]] if {[llength $gx] > 1} { list $x $z [expr {[dict get $costs $x [lindex $gx 1]] - $z}] } else { list $x $z $z } }] 2 1] s sVal sCost   # Compute how much to transfer, and with which "best" if {$sCost == $dCost ? $sVal > $dVal : $sCost < $dCost} { set s [lindex [dict get $g $d] 0] } else { set d [lindex [dict get $g $s] 0] } set v [expr {min([dict get $supply $s], [dict get $demand $d])}]   # Transfer some supply to demand dict update res $s inner {dict incr inner $d $v} dict incr demand $d -$v if {[dict get $demand $d] == 0} { dict for {k n} $supply { if {$n != 0} { # Filter list in dictionary to remove element dict set g $k [lmap x [dict get $g $k] { if {$x eq $d} continue; set x }] } } dict unset g $d dict unset demand $d } dict incr supply $s -$v if {[dict get $supply $s] == 0} { dict for {k n} $demand { if {$n != 0} { dict set g $k [lmap x [dict get $g $k] { if {$x eq $s} continue; set x }] } } dict unset g $s dict unset supply $s } } return $res }
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).
#Forth
Forth
defer ls-filter ( name len -- ? ) : ls-all 2drop true ; : ls-visible drop c@ [char] . <> ;   : ls ( dir len -- ) open-dir throw ( dirid ) begin dup pad 256 rot read-dir throw while pad over ls-filter if cr pad swap type else drop then repeat drop close-dir throw ;   \ only show C language source and header files (*.c *.h) : c-file? ( str len -- ? ) dup 3 < if 2drop false exit then + 1- dup c@ dup [char] c <> swap [char] h <> and if drop false exit then 1- dup c@ [char] . <> if drop false exit then drop true ; ' c-file? is ls-filter   s" ." ls
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).
#FreeBASIC
FreeBASIC
  Sub show (pattern As String) Dim As String f = Dir$(pattern) While Len(f) Print f f = Dir$ Wend End Sub   show "*.*" Sleep  
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 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 HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK Letter frequencies for English can be found here. Specifics for this task: Take only the ciphertext as input. You can assume it's all capitalized and has no punctuation, but it might have whitespace. Assume the plaintext is written in English. Find and output the key. Use that key to decrypt and output the original plaintext. Maintaining the whitespace from the ciphertext is optional. The algorithm doesn't have to be perfect (which may not be possible) but it should work when given enough ciphertext. The example above is fairly long, and should be plenty for any algorithm.
#11l
11l
-V ascii_uppercase = Array(‘A’..‘Z’)   F vigenere_decrypt(target_freqs, input) V nchars = :ascii_uppercase.len V ordA = ‘A’.code V sorted_targets = sorted(target_freqs)   F frequency(input) V result = :ascii_uppercase.map(c -> (c, 0.0)) L(c) input result[c - @ordA][1]++ R result   F correlation(input) V result = 0.0 V freq = sorted(@frequency(input), key' a -> a[1])   L(f) freq result += f[1] * @sorted_targets[L.index] R result   V cleaned = input.uppercase().filter(c -> c.is_uppercase()).map(c -> c.code) V best_len = 0 V best_corr = -100.0   L(i) 2 .< cleaned.len I/ 20 V pieces = [[Int]()] * i L(c) cleaned pieces[L.index % i].append(c) V corr = -0.5 * i + sum(pieces.map(p -> @correlation(p)))   I corr > best_corr best_len = i best_corr = corr   I best_len == 0 R (‘Text is too short to analyze’, ‘’)   V pieces = [[Int]()] * best_len L(c) cleaned pieces[L.index % best_len].append(c)   V freqs = pieces.map(p -> @frequency(p))   V key = ‘’ L(fr_) freqs V fr = sorted(fr_, key' a -> a[1], reverse' 1B) V m = 0 V max_corr = 0.0 L(j) 0 .< nchars V corr = 0.0 V c = ordA + j L(frc) fr V d = (frc[0].code - c + nchars) % nchars corr += frc[1] * target_freqs[d]   I corr > max_corr m = j max_corr = corr   key ‘’= Char(code' m + ordA)   V r = (enumerate(cleaned).map((i, c) -> Char(code' (c - @key[i % @best_len].code + @nchars) % @nchars + @ordA))) R (key, r.join(‘’))   V 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 BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK’   V english_frequences = [ 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.00150, 0.01974, 0.00074]   V (key, decoded) = vigenere_decrypt(english_frequences, encoded) print(‘Key: ’key) print("\nText: "decoded)
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).
#11l
11l
L(filename) fs:walk_dir(‘/’) I re:‘.*\.mp3’.match(filename) print(filename)
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.
#AutoHotkey
AutoHotkey
WCBT(oTwr){ topL := Max(oTwr*), l := num := 0, barCh := lbarCh := "", oLvl := [] while (++l <= topL) for t, h in oTwr oLvl[l,t] := h ? "██" : "≈≈" , oTwr[t] := oTwr[t]>0 ? oTwr[t]-1 : 0 for l, obj in oLvl{ while (oLvl[l, A_Index] = "≈≈") oLvl[l, A_Index] := " " while (oLvl[l, obj.Count() +1 - A_Index] = "≈≈") oLvl[l, obj.Count() +1 - A_Index] := " " for t, v in obj lbarCh .= StrReplace(v, "≈≈", "≈≈", n), num += n barCh := lbarCh "`n" barCh, lbarCh := "" } return [num, barCh] }
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.
#Delphi
Delphi
  uses System.Generics.Collections;   procedure TForm1.Voronoi; const p = 3; cells = 100; size = 1000;   var aCanvas : TCanvas; px, py: array of integer; color: array of Tcolor; Img: TBitmap; lastColor:Integer; auxList: TList<TPoint>; poligonlist : TDictionary<integer,TList<TPoint>>; pointarray : array of TPoint;   n,i,x,y,k,j: Integer; d1,d2: double;   function distance(x1,x2,y1,y2 :Integer) : Double; begin result := sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); ///Euclidian // result := abs(x1 - x2) + abs(y1 - y2); // Manhattan // result := power(power(abs(x1 - x2), p) + power(abs(y1 - y2), p), (1 / p)); // Minkovski end;   begin   poligonlist := TDictionary<integer,TList<Tpoint>>.create;   n := 0; Randomize;   img := TBitmap.Create; img.Width :=1000; img.Height :=1000;   setlength(px,cells); setlength(py,cells); setlength(color,cells);   for i:= 0 to cells-1 do begin px[i] := Random(size); py[i] := Random(size);   color[i] := Random(16777215); auxList := TList<Tpoint>.Create; poligonlist.Add(i,auxList); end;   for x := 0 to size - 1 do begin lastColor:= 0; for y := 0 to size - 1 do begin n:= 0;   for i := 0 to cells - 1 do begin d1:= distance(px[i], x, py[i], y); d2:= distance(px[n], x, py[n], y);   if d1 < d2 then begin n := i; end; end; if n <> lastColor then begin poligonlist[n].Add(Point(x,y)); poligonlist[lastColor].Add(Point(x,y)); lastColor := n; end; end;   poligonlist[n].Add(Point(x,y)); poligonlist[lastColor].Add(Point(x,y)); lastColor := n; end;   for j := 0 to cells -1 do begin   SetLength(pointarray, poligonlist[j].Count); for I := 0 to poligonlist[j].Count - 1 do begin if Odd(i) then pointarray[i] := poligonlist[j].Items[i]; end; for I := 0 to poligonlist[j].Count - 1 do begin if not Odd(i) then pointarray[i] := poligonlist[j].Items[i]; end; Img.Canvas.Pen.Color := color[j]; Img.Canvas.Brush.Color := color[j]; Img.Canvas.Polygon(pointarray);   Img.Canvas.Pen.Color := clBlack; Img.Canvas.Brush.Color := clBlack; Img.Canvas.Rectangle(px[j] -2, py[j] -2, px[j] +2, py[j] +2); end; Canvas.Draw(0,0, img); 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.
#ALGOL_68
ALGOL 68
# outputs nested html tables to visualise a tree #   # mode representing nodes of the tree # MODE NODE = STRUCT( STRING value, REF NODE child, REF NODE sibling ); REF NODE nil node = NIL;   # tags etc. # STRING table = "<table border=""1"" cellspacing=""4"">" , elbat = "</table>" , tr = "<tr>" , rt = "</tr>" , td = "<td style=""text-align: center; vertical-align: top; """ , dt = "</td>" , nbsp = "&nbsp;" ; CHAR nl = REPR 10;   # returns the number of child elements of tree # OP CHILDCOUNT = ( REF NODE tree )INT: BEGIN INT result := 0; REF NODE child := child OF tree; WHILE REF NODE( child ) ISNT nil node DO result +:= 1; child := sibling OF child OD; result END # CHILDCOUNT # ;   # generates nested HTML tables from the tree # OP TOHTML = ( REF NODE tree )STRING: IF tree IS nil node THEN # no node # "" ELSE # hae at least one node # STRING result := ""; INT child count = CHILDCOUNT tree; result +:= table + nl + tr + nl + td + " colspan=""" + whole( IF child count < 1 THEN 1 ELSE child count FI, 0 ) + """>" + nbsp + value OF tree + nbsp + dt + nl + rt + nl ; IF child count > 0 THEN # the node has branches # REF NODE child := child OF tree; INT child number := 1; INT mid child = ( child count + 1 ) OVER 2; child := child OF tree; result +:= tr + nl; WHILE child ISNT nil node DO result +:= td + ">" + nl + IF CHILDCOUNT child < 1 THEN nbsp + value OF child + nbsp ELSE TOHTML child FI + dt + nl; child := sibling OF child OD; result +:= rt + nl FI; result +:= elbat + nl FI # TOHTML # ;   # test the tree visualisation #   # returns a new node with the specified value and no child or siblings # PROC new node = ( STRING value )REF NODE: HEAP NODE := NODE( value, nil node, nil node ); # appends a sibling node to the node n, returns the sibling # OP +:= = ( REF NODE n, REF NODE sibling node )REF NODE: BEGIN REF NODE sibling := n; WHILE REF NODE( sibling OF sibling ) ISNT nil node DO sibling := sibling OF sibling OD; sibling OF sibling := sibling node END # +:= # ; # appends a new sibling node to the node n, returns the sibling # OP +:= = ( REF NODE n, STRING sibling value )REF NODE: n +:= new node( sibling value ); # adds a child node to the node n, returns the child # OP /:= = ( REF NODE n, REF NODE child node )REF NODE: child OF n := child node; # adda a new child node to the node n, returns the child # OP /:= = ( REF NODE n, STRING child value )REF NODE: n /:= new node( child value );   NODE animals := new node( "animals" ); NODE fish := new node( "fish" ); NODE reptiles := new node( "reptiles" ); NODE mammals := new node( "mammals" ); NODE primates := new node( "primates" ); NODE sharks := new node( "sharks" ); sharks /:= "great-white" +:= "hammer-head"; fish /:= "cod" +:= sharks +:= "piranha"; reptiles /:= "iguana" +:= "brontosaurus"; primates /:= "gorilla" +:= "lemur"; mammals /:= "sloth" +:= "horse" +:= "bison" +:= primates; animals /:= fish +:= reptiles +:= mammals;   print( ( TOHTML animals ) )
http://rosettacode.org/wiki/Vogel%27s_approximation_method
Vogel's approximation method
Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem. The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that: A will require 30 hours of work, B will require 20 hours of work, C will require 70 hours of work, D will require 30 hours of work, and E will require 60 hours of work. They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”. W has 50 hours available to commit to working, X has 60 hours available, Y has 50 hours available, and Z has 50 hours available. The cost per hour for each contractor for each task is summarized by the following table: A B C D E W 16 16 13 22 17 X 14 14 13 19 15 Y 19 19 20 23 50 Z 50 12 50 15 11 The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows: Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand) Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column. Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell). Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost. Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet. Step 6: Compute total transportation cost for the feasible allocations. For this task assume that the model is balanced. For each task and contractor (row and column above) calculating the difference between the smallest two values produces: A B C D E W X Y Z 1 2 2 0 4 4 3 1 0 1 E-Z(50) Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply). Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working. Repeat until all supply and demand is met: 2 2 2 0 3 2 3 1 0 - C-W(50) 3 5 5 7 4 35 - 1 0 - E-X(10) 4 5 5 7 4 - - 1 0 - C-X(20) 5 5 5 - 4 - - 0 0 - A-X(30) 6 - 19 - 23 - - - 4 - D-Y(30) - - - - - - - - - B-Y(20) Finally calculate the cost of your solution. In the example given it is £3100: A B C D E W 50 X 30 20 10 Y 20 30 Z 50 The optimal solution determined by GLPK is £3100: A B C D E W 50 X 10 20 20 10 Y 20 30 Z 50 Cf. Transportation problem
#Wren
Wren
import "/math" for Int, Nums import "/fmt" for Fmt   var supply = [50, 60, 50, 50] var demand = [30, 20, 70, 30, 60]   var costs = [ [16, 16, 13, 22, 17], [14, 14, 13, 19, 15], [19, 19, 20, 23, 50], [50, 12, 50, 15, 11] ]   var nRows = supply.count var nCols = demand.count   var rowDone = List.filled(nRows, false) var colDone = List.filled(nCols, false) var results = List.filled(nRows, null) for (i in 0...nRows) results[i] = List.filled(nCols, 0)   var diff = Fn.new { |j, len, isRow| var min1 = Int.maxSafe var min2 = min1 var minP = -1 for (i in 0...len) { var done = isRow ? colDone[i] : rowDone[i] if (!done) { var c = isRow ? costs[j][i] : costs[i][j] if (c < min1) { min2 = min1 min1 = c minP = i } else if (c < min2) min2 = c } } return [min2 - min1, min1, minP] }   var maxPenalty = Fn.new { |len1, len2, isRow| var md = -Int.maxSafe var pc = -1 var pm = -1 var mc = -1 for (i in 0...len1) { var done = isRow ? rowDone[i] : colDone[i] if (!done) { var res = diff.call(i, len2, isRow) if (res[0] > md) { md = res[0] // max diff pm = i // pos of max diff mc = res[1] // min cost pc = res[2] // pos of min cost } } } return isRow ? [pm, pc, mc, md] : [pc, pm, mc, md] }   var nextCell = Fn.new { var res1 = maxPenalty.call(nRows, nCols, true) var res2 = maxPenalty.call(nCols, nRows, false) if (res1[3] == res2[3]) return (res1[2] < res2[2]) ? res1 : res2 return (res1[3] > res2[3]) ? res2 : res1 }   var supplyLeft = Nums.sum(supply) var totalCost = 0 while (supplyLeft > 0) { var cell = nextCell.call() var r = cell[0] var c = cell[1] var q = demand[c].min(supply[r]) demand[c] = demand[c] - q if (demand[c] == 0) colDone[c] = true supply[r] = supply[r] - q if (supply[r] == 0) rowDone[r] = true results[r][c] = q supplyLeft = supplyLeft - q totalCost = totalCost + q*costs[r][c] }   System.print(" A B C D E") var i = 0 for (result in results) { Fmt.write("$c", "W".bytes[0] + i) for (item in result) Fmt.write(" $2d", item) System.print() i = i + 1 } System.print("\nTotal Cost = %(totalCost)")
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).
#Frink
Frink
for f = select[files["."], {|f1| f1.getName[] =~ %r/\.frink$/}] println[f.getName[]]
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).
#Gambas
Gambas
Public Sub Main() Dim sTemp As String   For Each sTemp In Dir("/etc", "*.d") Print sTemp Next   End
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 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 HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK Letter frequencies for English can be found here. Specifics for this task: Take only the ciphertext as input. You can assume it's all capitalized and has no punctuation, but it might have whitespace. Assume the plaintext is written in English. Find and output the key. Use that key to decrypt and output the original plaintext. Maintaining the whitespace from the ciphertext is optional. The algorithm doesn't have to be perfect (which may not be possible) but it should work when given enough ciphertext. The example above is fairly long, and should be plenty for any algorithm.
#Ada
Ada
with Ada.Text_IO;   procedure Vignere_Cryptanalysis is   subtype Letter is Character range 'A' .. 'Z';   function "+"(X, Y: Letter) return Letter is begin return Character'Val( ( (Character'Pos(X)-Character'Pos('A')) + (Character'Pos(Y)-Character'Pos('A')) ) mod 26 + Character'Pos('A')); end;   function "-"(X, Y: Letter) return Letter is begin return Character'Val( ( (Character'Pos(X)-Character'Pos('A')) - (Character'Pos(Y)-Character'Pos('A')) ) mod 26 + Character'Pos('A')); end;   type Frequency_Array is array (Letter) of Float;   English: Frequency_Array := ( 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.00150, 0.01974, 0.00074 );   function Get_Frequency(S: String) return Frequency_Array is Result: Frequency_Array := (others => 0.0); Offset: Float := 1.0/Float(S'Length); begin for I in S'Range loop if S(I) in Letter then Result(S(I)) := Result(S(I)) + Offset; end if; end loop; return Result; end Get_Frequency;   function Remove_Whitespace(S: String) return String is begin if S="" then return ""; elsif S(S'First) in Letter then return S(S'First) & Remove_Whitespace(S(S'First+1 .. S'Last)); else return Remove_Whitespace(S(S'First+1 .. S'Last)); end if; end Remove_Whitespace;   function Distance(A, B: Frequency_Array; Offset: Character := 'A') return Float is Result: Float := 0.0; Diff: Float; begin for C in A'Range loop Diff := A(C+Offset) - B(C); Result := Result + (Diff * Diff); end loop; return Result; end Distance;   function Find_Key(Cryptogram: String; Key_Length: Positive) return String is   function Find_Caesar_Key(S: String) return Letter is Frequency: Frequency_Array := Get_Frequency(S); Candidate: Letter := 'A'; -- a fake candidate Candidate_Dist : Float := Distance(Frequency, English, 'A'); New_Dist: Float;   begin   for L in Letter range 'B' .. 'Z' loop New_Dist := Distance(Frequency, English, L); if New_Dist <= Candidate_Dist then Candidate_Dist := New_Dist; Candidate  := L; end if; end loop; return Candidate; end Find_Caesar_Key;   function Get_Slide(S: String; Step: Positive) return String is begin if S'Length= 0 then return ""; else return S(S'First) & Get_Slide(S(S'First+Step .. S'Last), Step); end if; end Get_Slide;   Key: String(1 .. Key_Length);   S: String renames Cryptogram;   begin for I in Key'Range loop Key(I) := Find_Caesar_Key(Get_Slide(S(S'First+I-1 .. S'Last), Key_Length)); end loop; return Key; end Find_Key;   function Key_Char(Key: String; Index: Positive) return Letter is begin if Index > Key'Last then return Key_Char(Key, Index-Key'Last); else return Key(Index); end if; end Key_Char;   Ciphertext: String := Remove_Whitespace( "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 HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" & "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" & "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" & "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" & "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" & "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" & "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" & "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" & "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" & "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" & "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" & "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" & "FWAML ZZRXJ EKAHV FASMU LVVUT TGK");   Best_Plain: String := Ciphertext; Best_Dist: Float := Distance(English, Get_Frequency(Best_Plain)); Best_Key: String := Ciphertext; Best_Key_L: Natural := 0;   begin -- Vignere_Cryptanalysis for I in 1 .. Ciphertext'Length/10 loop declare Key: String(1 .. I) := Find_Key(Ciphertext, I); Plaintext: String(Ciphertext'Range); begin for I in Ciphertext'Range loop Plaintext(I) := Ciphertext(I) - Key_Char(Key, I); end loop; if Distance(English, Get_Frequency(Plaintext)) < Best_Dist then Best_Plain := Plaintext; Best_Dist  := Distance(English, Get_Frequency(Plaintext)); Best_Key(1 .. I) := Key; Best_Key_L := I; if Best_dist < 0.01 then declare use Ada.Text_IO; begin Put_Line("Key =" & Best_Key(1 .. Best_Key_L)); Put_Line("Distance = " & Float'Image(Best_Dist)); New_Line; Put_Line("Plaintext ="); Put_Line(Best_Plain); New_Line; New_Line; end; end if; end if; end; end loop; end Vignere_Cryptanalysis;
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).
#8th
8th
  "*.c" f:rglob \ top of stack now has list of all "*.c" files, recursively  
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).
#Ada
Ada
with Ada.Directories; use Ada.Directories; with Ada.Text_IO;   procedure Test_Directory_Walk is procedure Walk (Name : String; Pattern : String) is procedure Print (Item : Directory_Entry_Type) is begin Ada.Text_IO.Put_Line (Full_Name (Item)); end Print; procedure Walk (Item : Directory_Entry_Type) is begin if Simple_Name (Item) /= "." and then Simple_Name (Item) /= ".." then Walk (Full_Name (Item), Pattern); end if; exception when Name_Error => null; end Walk; begin Search (Name, Pattern, (others => True), Print'Access); Search (Name, "", (Directory => True, others => False), Walk'Access); end Walk; begin Walk (".", "*.adb"); end Test_Directory_Walk;
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.
#AWK
AWK
  # syntax: GAWK -f WATER_COLLECTED_BETWEEN_TOWERS.AWK [-v debug={0|1}] BEGIN { wcbt("1,5,3,7,2") wcbt("5,3,7,2,6,4,5,9,1,2") wcbt("2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1") wcbt("5,5,5,5") wcbt("5,6,7,8") wcbt("8,7,7,6") wcbt("6,7,10,7,6") exit(0) } function wcbt(str, ans,hl,hr,i,n,tower) { n = split(str,tower,",") for (i=n; i>=0; i--) { # scan right to left hr[i] = max(tower[i],(i<n)?hr[i+1]:0) } for (i=0; i<=n; i++) { # scan left to right hl[i] = max(tower[i],(i!=0)?hl[i-1]:0) ans += min(hl[i],hr[i]) - tower[i] } printf("%4d : %s\n",ans,str) if (debug == 1) { for (i=1; i<=n; i++) { printf("%-4s",tower[i]) } ; print("tower") for (i=1; i<=n; i++) { printf("%-4s",hl[i]) } ; print("l-r") for (i=1; i<=n; i++) { printf("%-4s",hr[i]) } ; print("r-l") for (i=1; i<=n; i++) { printf("%-4s",min(hl[i],hr[i])) } ; print("min") for (i=1; i<=n; i++) { printf("%-4s",min(hl[i],hr[i])-tower[i]) } ; print("sum\n") } } function max(x,y) { return((x > y) ? x : y) } function min(x,y) { return((x < y) ? x : y) }  
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.
#FreeBASIC
FreeBASIC
Dim Shared As Integer ancho = 500, alto = 500 Screenres ancho, alto, 8 Cls Randomize Timer   Function hypot(a As Integer, b As Integer) As Double Return Sqr(a^2 + b^2) End Function   Sub Generar_Diagrama_Voronoi(ancho As Integer, alto As Integer, num_celdas As Integer) Dim As Integer nx(num_celdas), ny(num_celdas), nr(num_celdas), ng(num_celdas), nb(num_celdas) Dim As Integer x, i, y, j, dmin, d   For i = 1 To num_celdas nx(i) = (Rnd * ancho) ny(i) = (Rnd * alto) nr(i) = (Rnd * 256) ng(i) = (Rnd * 256) nb(i) = (Rnd * 256) Next i For y = 1 To alto For x = 1 To ancho dmin = hypot(ancho-1, alto-1) j = -1 For i = 1 To num_celdas d = hypot(nx(i)-x, ny(i)-y) If d < dmin Then dmin = d : j = i Next i Pset (x, y), Rgb(nr(j), ng(j), ng(j)) Next x Next y End Sub   Generar_Diagrama_Voronoi(ancho, alto, 25) Bsave "Voronoi_diadram.bmp",0 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.
#AppleScript
AppleScript
-- Vertically centered textual tree using UTF8 monospaced -- box-drawing characters, with options for compacting -- and pruning.   -- ┌── Gamma -- ┌─ Beta ┼── Delta -- │ └ Epsilon -- Alpha ┼─ Zeta ───── Eta -- │ ┌─── Iota -- └ Theta ┼── Kappa -- └─ Lambda   -- TESTS -------------------------------------------------- on run set tree to Node(1, ¬ {Node(2, ¬ {Node(4, {Node(7, {})}), ¬ Node(5, {})}), ¬ Node(3, ¬ {Node(6, ¬ {Node(8, {}), Node(9, {})})})})   set tree2 to Node("Alpha", ¬ {Node("Beta", ¬ {Node("Gamma", {}), ¬ Node("Delta", {}), ¬ Node("Epsilon", {})}), ¬ Node("Zeta", {Node("Eta", {})}), ¬ Node("Theta", ¬ {Node("Iota", {}), Node("Kappa", {}), ¬ Node("Lambda", {})})})   set strTrees to unlines({"(NB – view in mono-spaced font)\n\n", ¬ "Compacted (not all parents vertically centered):\n", ¬ drawTree2(true, false, tree), ¬ "\nFully expanded and vertically centered:\n", ¬ drawTree2(false, false, tree2), ¬ "\nVertically centered, with nodeless lines pruned out:\n", ¬ drawTree2(false, true, tree2)}) set the clipboard to strTrees strTrees end run     -- drawTree2 :: Bool -> Bool -> Tree String -> String on drawTree2(blnCompressed, blnPruned, tree) -- Tree design and algorithm inspired by the Haskell snippet at: -- https://doisinkidney.com/snippets/drawing-trees.html script measured on |λ|(t) script go on |λ|(x) set s to " " & x & " " Tuple(length of s, s) end |λ| end script fmapTree(go, t) end |λ| end script set measuredTree to |λ|(tree) of measured   script levelMax on |λ|(a, level) a & maximum(map(my fst, level)) end |λ| end script set levelWidths to foldl(levelMax, {}, ¬ init(levels(measuredTree)))   -- Lefts, Mid, Rights script lmrFromStrings on |λ|(xs) set {ls, rs} to items 2 thru -2 of ¬ (splitAt((length of xs) div 2, xs) as list) Tuple3(ls, item 1 of rs, rest of rs) end |λ| end script   script stringsFromLMR on |λ|(lmr) script add on |λ|(a, x) a & x end |λ| end script foldl(add, {}, items 2 thru -2 of (lmr as list)) end |λ| end script   script fghOverLMR on |λ|(f, g, h) script property mg : mReturn(g) on |λ|(lmr) set {ls, m, rs} to items 2 thru -2 of (lmr as list) Tuple3(map(f, ls), |λ|(m) of mg, map(h, rs)) end |λ| end script end |λ| end script   script lmrBuild on leftPad(n) script on |λ|(s) replicateString(n, space) & s end |λ| end script end leftPad   -- lmrBuild main on |λ|(w, f) script property mf : mReturn(f) on |λ|(wsTree) set xs to nest of wsTree set lng to length of xs set {nChars, x} to items 2 thru -2 of ¬ ((root of wsTree) as list) set _x to replicateString(w - nChars, "─") & x   -- LEAF NODE ------------------------------------ if 0 = lng then Tuple3({}, _x, {})   else if 1 = lng then -- NODE WITH SINGLE CHILD --------------------- set indented to leftPad(1 + w) script lineLinked on |λ|(z) _x & "─" & z end |λ| end script |λ|(|λ|(item 1 of xs) of mf) of ¬ (|λ|(indented, lineLinked, indented) of ¬ fghOverLMR) else -- NODE WITH CHILDREN ------------------------- script treeFix on cFix(x) script on |λ|(xs) x & xs end |λ| end script end cFix   on |λ|(l, m, r) compose(stringsFromLMR, ¬ |λ|(cFix(l), cFix(m), cFix(r)) of ¬ fghOverLMR) end |λ| end script   script linked on |λ|(s) set c to text 1 of s set t to tail(s) if "┌" = c then _x & "┬" & t else if "│" = c then _x & "┤" & t else if "├" = c then _x & "┼" & t else _x & "┴" & t end if end |λ| end script   set indented to leftPad(w) set lmrs to map(f, xs) if blnCompressed then set sep to {} else set sep to {"│"} end if   tell lmrFromStrings set tupleLMR to |λ|(intercalate(sep, ¬ {|λ|(item 1 of lmrs) of ¬ (|λ|(" ", "┌", "│") of treeFix)} & ¬ map(|λ|("│", "├", "│") of treeFix, ¬ init(tail(lmrs))) & ¬ {|λ|(item -1 of lmrs) of ¬ (|λ|("│", "└", " ") of treeFix)})) end tell   |λ|(tupleLMR) of ¬ (|λ|(indented, linked, indented) of fghOverLMR) end if end |λ| end script end |λ| end script   set treeLines to |λ|(|λ|(measuredTree) of ¬ foldr(lmrBuild, 0, levelWidths)) of stringsFromLMR if blnPruned then script notEmpty on |λ|(s) script isData on |λ|(c) "│ " does not contain c end |λ| end script any(isData, characters of s) end |λ| end script set xs to filter(notEmpty, treeLines) else set xs to treeLines end if unlines(xs) end drawTree2     -- GENERIC ------------------------------------------------   -- Node :: a -> [Tree a] -> Tree a on Node(v, xs) {type:"Node", root:v, nest:xs} end Node   -- Tuple (,) :: a -> b -> (a, b) on Tuple(a, b) -- Constructor for a pair of values, possibly of two different types. {type:"Tuple", |1|:a, |2|:b, length:2} end Tuple   -- Tuple3 (,,) :: a -> b -> c -> (a, b, c) on Tuple3(x, y, z) {type:"Tuple3", |1|:x, |2|:y, |3|:z, length:3} end Tuple3   -- Applied to a predicate and a list, -- |any| returns true if at least one element of the -- list satisfies the predicate. -- any :: (a -> Bool) -> [a] -> Bool on any(f, xs) tell mReturn(f) set lng to length of xs repeat with i from 1 to lng if |λ|(item i of xs) then return true end repeat false end tell end any   -- compose (<<<) :: (b -> c) -> (a -> b) -> a -> c on compose(f, g) script property mf : mReturn(f) property mg : mReturn(g) on |λ|(x) |λ|(|λ|(x) of mg) of mf end |λ| end script end compose   -- concat :: [[a]] -> [a] -- concat :: [String] -> String on concat(xs) set lng to length of xs if 0 < lng and string is class of (item 1 of xs) then set acc to "" else set acc to {} end if repeat with i from 1 to lng set acc to acc & item i of xs end repeat acc end concat   -- concatMap :: (a -> [b]) -> [a] -> [b] on concatMap(f, xs) set lng to length of xs set acc to {} tell mReturn(f) repeat with i from 1 to lng set acc to acc & (|λ|(item i of xs, i, xs)) end repeat end tell return acc end concatMap   -- filter :: (a -> Bool) -> [a] -> [a] on filter(f, xs) tell mReturn(f) set lst to {} set lng to length of xs repeat with i from 1 to lng set v to item i of xs if |λ|(v, i, xs) then set end of lst to v end repeat return lst end tell end filter   -- fmapTree :: (a -> b) -> Tree a -> Tree b on fmapTree(f, tree) script go property g : |λ| of mReturn(f) on |λ|(x) set xs to nest of x if xs ≠ {} then set ys to map(go, xs) else set ys to xs end if Node(g(root of x), ys) end |λ| end script |λ|(tree) of go end fmapTree   -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl   -- foldr :: (a -> b -> b) -> b -> [a] -> b on foldr(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from lng to 1 by -1 set v to |λ|(item i of xs, v, i, xs) end repeat return v end tell end foldr   -- fst :: (a, b) -> a on fst(tpl) if class of tpl is record then |1| of tpl else item 1 of tpl end if end fst   -- identity :: a -> a on identity(x) -- The argument unchanged. x end identity   -- init :: [a] -> [a] -- init :: [String] -> [String] on init(xs) set blnString to class of xs = string set lng to length of xs   if lng > 1 then if blnString then text 1 thru -2 of xs else items 1 thru -2 of xs end if else if lng > 0 then if blnString then "" else {} end if else missing value end if end init   -- intercalate :: [a] -> [[a]] -> [a] -- intercalate :: String -> [String] -> String on intercalate(sep, xs) concat(intersperse(sep, xs)) end intercalate   -- intersperse(0, [1,2,3]) -> [1, 0, 2, 0, 3] -- intersperse :: a -> [a] -> [a] -- intersperse :: Char -> String -> String on intersperse(sep, xs) set lng to length of xs if lng > 1 then set acc to {item 1 of xs} repeat with i from 2 to lng set acc to acc & {sep, item i of xs} end repeat if class of xs is string then concat(acc) else acc end if else xs end if end intersperse   -- isNull :: [a] -> Bool -- isNull :: String -> Bool on isNull(xs) if class of xs is string then "" = xs else {} = xs end if end isNull   -- iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a] on iterateUntil(p, f, x) script property mp : mReturn(p)'s |λ| property mf : mReturn(f)'s |λ| property lst : {x} on |λ|(v) repeat until mp(v) set v to mf(v) set end of lst to v end repeat return lst end |λ| end script |λ|(x) of result end iterateUntil   -- levels :: Tree a -> [[a]] on levels(tree) script nextLayer on |λ|(xs) script on |λ|(x) nest of x end |λ| end script concatMap(result, xs) end |λ| end script   script roots on |λ|(xs) script on |λ|(x) root of x end |λ| end script map(result, xs) end |λ| end script   map(roots, iterateUntil(my isNull, nextLayer, {tree})) end levels   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) -- The list obtained by applying f -- to each element of 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   -- maximum :: Ord a => [a] -> a on maximum(xs) script on |λ|(a, b) if a is missing value or b > a then b else a end if end |λ| end script foldl(result, missing value, xs) end maximum   -- mReturn :: First-class m => (a -> b) -> m (a -> b) on mReturn(f) -- 2nd class handler function lifted into 1st class script wrapper. if script is class of f then f else script property |λ| : f end script end if end mReturn   -- replicateString :: Int -> String -> String on replicateString(n, s) set out to "" if n < 1 then return out set dbl to s   repeat while (n > 1) if (n mod 2) > 0 then set out to out & dbl set n to (n div 2) set dbl to (dbl & dbl) end repeat return out & dbl end replicateString   -- snd :: (a, b) -> b on snd(tpl) if class of tpl is record then |2| of tpl else item 2 of tpl end if end snd   -- splitAt :: Int -> [a] -> ([a], [a]) on splitAt(n, xs) if n > 0 and n < length of xs then if class of xs is text then Tuple(items 1 thru n of xs as text, items (n + 1) thru -1 of xs as text) else Tuple(items 1 thru n of xs, items (n + 1) thru -1 of xs) end if else if n < 1 then Tuple({}, xs) else Tuple(xs, {}) end if end if end splitAt   -- tail :: [a] -> [a] on tail(xs) set blnText to text is class of xs if blnText then set unit to "" else set unit to {} end if set lng to length of xs if 1 > lng then missing value else if 2 > lng then unit else if blnText then text 2 thru -1 of xs else rest of xs end if end if end tail   -- unlines :: [String] -> String on unlines(xs) -- A single string formed by the intercalation -- of a list of strings with the newline character. set {dlm, my text item delimiters} to ¬ {my text item delimiters, linefeed} set str to xs as text set my text item delimiters to dlm str end unlines
http://rosettacode.org/wiki/Vogel%27s_approximation_method
Vogel's approximation method
Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem. The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that: A will require 30 hours of work, B will require 20 hours of work, C will require 70 hours of work, D will require 30 hours of work, and E will require 60 hours of work. They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”. W has 50 hours available to commit to working, X has 60 hours available, Y has 50 hours available, and Z has 50 hours available. The cost per hour for each contractor for each task is summarized by the following table: A B C D E W 16 16 13 22 17 X 14 14 13 19 15 Y 19 19 20 23 50 Z 50 12 50 15 11 The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows: Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand) Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column. Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell). Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost. Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet. Step 6: Compute total transportation cost for the feasible allocations. For this task assume that the model is balanced. For each task and contractor (row and column above) calculating the difference between the smallest two values produces: A B C D E W X Y Z 1 2 2 0 4 4 3 1 0 1 E-Z(50) Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply). Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working. Repeat until all supply and demand is met: 2 2 2 0 3 2 3 1 0 - C-W(50) 3 5 5 7 4 35 - 1 0 - E-X(10) 4 5 5 7 4 - - 1 0 - C-X(20) 5 5 5 - 4 - - 0 0 - A-X(30) 6 - 19 - 23 - - - 4 - D-Y(30) - - - - - - - - - B-Y(20) Finally calculate the cost of your solution. In the example given it is £3100: A B C D E W 50 X 30 20 10 Y 20 30 Z 50 The optimal solution determined by GLPK is £3100: A B C D E W 50 X 10 20 20 10 Y 20 30 Z 50 Cf. Transportation problem
#Yabasic
Yabasic
  N_ROWS = 4 : N_COLS = 5   dim supply(N_ROWS) dim demand(N_COLS)   restore sup for n = 0 to N_ROWS - 1 read supply(n) next n   restore dem for n = 0 to N_COLS - 1 read demand(n) next n   label sup data 50, 60, 50, 50   label dem data 30, 20, 70, 30, 60   dim costs(N_ROWS, N_COLS)   label cost data 16, 16, 13, 22, 17 data 14, 14, 13, 19, 15 data 19, 19, 20, 23, 50 data 50, 12, 50, 15, 11   restore cost for i = 0 to N_ROWS - 1 for j = 0 to N_COLS - 1 read costs(i, j) next j next i   dim row_done(N_ROWS) dim col_done(N_COLS)   sub diff(j, leng, is_row, res()) local i, c, min1, min2, min_p, test   min1 = 10e300 : min2 = min1 : min_p = -1   for i = 0 to leng - 1 if is_row then test = col_done(i) else test = row_done(i) end if if test continue if is_row then c = costs(j, i) else c = costs(i, j) end if if c < min1 then min2 = min1 min1 = c min_p = i elseif c < min2 then min2 = c end if next i res(0) = min2 - min1 res(1) = min1 res(2) = min_p end sub   sub max_penalty(len1, len2, is_row, res()) local i, pc, pm, mc, md, res2(3), test   pc = -1 : pm = -1 : mc = -1 : md = -10e300   for i = 0 to len1 - 1 if is_row then test = row_done(i) else test = col_done(i) end if if test continue diff(i, len2, is_row, res2()) if res2(0) > md then md = res2(0) //* max diff */ pm = i //* pos of max diff */ mc = res2(1) //* min cost */ pc = res2(2) //* pos of min cost */ end if next i   if is_row then res(0) = pm : res(1) = pc else res(0) = pc : res(1) = pm end if res(2) = mc : res(3) = md end sub   sub next_cell(res()) local i, res1(4), res2(4)   max_penalty(N_ROWS, N_COLS, TRUE, res1()) max_penalty(N_COLS, N_ROWS, FALSE, res2())   if res1(3) = res2(3) then if res1(2) < res2(2) then for i = 0 to 3 : res(i) = res1(i) : next i else for i = 0 to 3 : res(i) = res2(i) : next i end if return end if if res1(3) > res2(3) then for i = 0 to 3 : res(i) = res2(i) : next i else for i = 0 to 3 : res(i) = res1(i) : next i end if end sub   supply_left = 0 : total_cost = 0 : dim cell(4)   dim results(N_ROWS, N_COLS)   for i = 0 to N_ROWS - 1 : supply_left = supply_left + supply(i) : next i   while(supply_left > 0) next_cell(cell()) r = cell(0) c = cell(1) q = min(demand(c), supply(r)) demand(c) = demand(c) - q if not demand(c) col_done(c) = TRUE supply(r) = supply(r) - q if not supply(r) row_done(r) = TRUE results(r, c) = q supply_left = supply_left - q total_cost = total_cost + q * costs(r, c) wend   print " A B C D E\n" for i = 0 to N_ROWS - 1 print chr$(asc("W") + i), " "; for j = 0 to N_COLS - 1 print results(i, j) using "###"; next j print next i print "\nTotal cost = ", total_cost
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).
#Go
Go
package main   import ( "fmt" "path/filepath" )   func main() { fmt.Println(filepath.Glob("*.go")) }
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).
#Groovy
Groovy
// *** print *.txt files in current directory new File('.').eachFileMatch(~/.*\.txt/) { println it }   // *** print *.txt files in /foo/bar new File('/foo/bar').eachFileMatch(~/.*\.txt/) { println it }
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 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 HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK Letter frequencies for English can be found here. Specifics for this task: Take only the ciphertext as input. You can assume it's all capitalized and has no punctuation, but it might have whitespace. Assume the plaintext is written in English. Find and output the key. Use that key to decrypt and output the original plaintext. Maintaining the whitespace from the ciphertext is optional. The algorithm doesn't have to be perfect (which may not be possible) but it should work when given enough ciphertext. The example above is fairly long, and should be plenty for any algorithm.
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h>   const char *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 BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" "FWAML ZZRXJ EKAHV FASMU LVVUT TGK";   const double freq[] = { 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.00150, 0.01974, 0.00074 };   int best_match(const double *a, const double *b) { double sum = 0, fit, d, best_fit = 1e100; int i, rotate, best_rotate = 0; for (i = 0; i < 26; i++) sum += a[i]; for (rotate = 0; rotate < 26; rotate++) { fit = 0; for (i = 0; i < 26; i++) { d = a[(i + rotate) % 26] / sum - b[i]; fit += d * d / b[i]; }   if (fit < best_fit) { best_fit = fit; best_rotate = rotate; } }   return best_rotate; }   double freq_every_nth(const int *msg, int len, int interval, char *key) { double sum, d, ret; double out[26], accu[26] = {0}; int i, j, rot;   for (j = 0; j < interval; j++) { for (i = 0; i < 26; i++) out[i] = 0; for (i = j; i < len; i += interval) out[msg[i]]++; key[j] = rot = best_match(out, freq); key[j] += 'A'; for (i = 0; i < 26; i++) accu[i] += out[(i + rot) % 26]; }   for (i = 0, sum = 0; i < 26; i++) sum += accu[i];   for (i = 0, ret = 0; i < 26; i++) { d = accu[i] / sum - freq[i]; ret += d * d / freq[i]; }   key[interval] = '\0'; return ret; }   int main() { int txt[strlen(encoded)]; int len = 0, j; char key[100]; double fit, best_fit = 1e100;   for (j = 0; encoded[j] != '\0'; j++) if (isupper(encoded[j])) txt[len++] = encoded[j] - 'A';   for (j = 1; j < 30; j++) { fit = freq_every_nth(txt, len, j, key); printf("%f, key length: %2d, %s", fit, j, key); if (fit < best_fit) { best_fit = fit; printf(" <--- best so far"); } printf("\n"); }   return 0; }
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).
#ALGOL_68
ALGOL 68
INT match=0, no match=1, out of memory error=2, other error=3;   STRING slash = "/", pwd=".", parent="..";   PROC walk tree = (STRING path, PROC (STRING)VOID call back)VOID: ( []STRING files = get directory(path); FOR file index TO UPB files DO STRING file = files[file index]; STRING path file = path+slash+file; IF file is directory(path file) THEN IF file NE pwd AND file NE parent THEN walk tree(path file, call back) FI ELSE call back(path file) FI OD );   STRING re sort a68 = "[Ss]ort[^/]*[.]a68$";   PROC match sort a68 and print = (STRING path file)VOID: IF grep in string(re sort a68, path file, NIL, NIL) = match THEN print((path file, new line)) FI;   walk tree(".", match sort a68 and print)
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.
#BASIC
BASIC
10 DEFINT A-Z: DIM T(20): K=0 20 K=K+1: READ N: IF N=0 THEN END 30 FOR I=0 TO N-1: READ T(I): NEXT 40 W=0 50 FOR R=N-1 TO 0 STEP -1: IF T(R)=0 THEN NEXT ELSE IF R=0 THEN 110 60 B=0 70 FOR C=0 TO R 80 IF T(C)>0 THEN T(C)=T(C)-1: B=B+1 ELSE IF B>0 THEN W=W+1 90 NEXT 100 IF B>1 THEN 50 110 PRINT "Block";K;"holds";W;"water units." 120 GOTO 20 130 DATA 5, 1,5,3,7,2 140 DATA 10, 5,3,7,2,6,4,5,9,1,2 150 DATA 16, 2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1 160 DATA 4, 5,5,5,5 170 DATA 4, 5,6,7,8 180 DATA 4, 8,7,7,6 190 DATA 5, 6,7,10,7,6 200 DATA 0
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.
#Go
Go
package main   import ( "fmt" "image" "image/color" "image/draw" "image/png" "math/rand" "os" "time" )   const ( imageWidth = 300 imageHeight = 200 nSites = 10 )   func main() { writePngFile(generateVoronoi(randomSites())) }   func generateVoronoi(sx, sy []int) image.Image { // generate a random color for each site sc := make([]color.NRGBA, nSites) for i := range sx { sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)), uint8(rand.Intn(256)), 255} }   // generate diagram by coloring each pixel with color of nearest site img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight)) for x := 0; x < imageWidth; x++ { for y := 0; y < imageHeight; y++ { dMin := dot(imageWidth, imageHeight) var sMin int for s := 0; s < nSites; s++ { if d := dot(sx[s]-x, sy[s]-y); d < dMin { sMin = s dMin = d } } img.SetNRGBA(x, y, sc[sMin]) } } // mark each site with a black box black := image.NewUniform(color.Black) for s := 0; s < nSites; s++ { draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2), black, image.ZP, draw.Src) } return img }   func dot(x, y int) int { return x*x + y*y }   func randomSites() (sx, sy []int) { rand.Seed(time.Now().Unix()) sx = make([]int, nSites) sy = make([]int, nSites) for i := range sx { sx[i] = rand.Intn(imageWidth) sy[i] = rand.Intn(imageHeight) } return }   func writePngFile(img image.Image) { f, err := os.Create("voronoi.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, img); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
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.
#Batch_File
Batch File
@tree %cd%
http://rosettacode.org/wiki/Vogel%27s_approximation_method
Vogel's approximation method
Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem. The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that: A will require 30 hours of work, B will require 20 hours of work, C will require 70 hours of work, D will require 30 hours of work, and E will require 60 hours of work. They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”. W has 50 hours available to commit to working, X has 60 hours available, Y has 50 hours available, and Z has 50 hours available. The cost per hour for each contractor for each task is summarized by the following table: A B C D E W 16 16 13 22 17 X 14 14 13 19 15 Y 19 19 20 23 50 Z 50 12 50 15 11 The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows: Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand) Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column. Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell). Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost. Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet. Step 6: Compute total transportation cost for the feasible allocations. For this task assume that the model is balanced. For each task and contractor (row and column above) calculating the difference between the smallest two values produces: A B C D E W X Y Z 1 2 2 0 4 4 3 1 0 1 E-Z(50) Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply). Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working. Repeat until all supply and demand is met: 2 2 2 0 3 2 3 1 0 - C-W(50) 3 5 5 7 4 35 - 1 0 - E-X(10) 4 5 5 7 4 - - 1 0 - C-X(20) 5 5 5 - 4 - - 0 0 - A-X(30) 6 - 19 - 23 - - - 4 - D-Y(30) - - - - - - - - - B-Y(20) Finally calculate the cost of your solution. In the example given it is £3100: A B C D E W 50 X 30 20 10 Y 20 30 Z 50 The optimal solution determined by GLPK is £3100: A B C D E W 50 X 10 20 20 10 Y 20 30 Z 50 Cf. Transportation problem
#zkl
zkl
costs:=Dictionary( "W",Dictionary("A",16, "B",16, "C",13, "D",22, "E",17), "X",Dictionary("A",14, "B",14, "C",13, "D",19, "E",15), "Y",Dictionary("A",19, "B",19, "C",20, "D",23, "E",50), "Z",Dictionary("A",50, "B",12, "C",50, "D",15, "E",11)).makeReadOnly(); demand:=Dictionary("A",30, "B",20, "C",70, "D",30, "E",60); // gonna be modified supply:=Dictionary("W",50, "X",60, "Y",50, "Z",50); // gonna be modified
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).
#Hare
Hare
use fmt; use glob;   export fn main() void = { ls("/etc/*.conf"); };   fn ls(pattern: str) void = { let gen = glob::glob(pattern, glob::flags::NONE); defer glob::finish(&gen); for (true) match (glob::next(&gen)) { case void => break; case glob::failure => continue; case let s: str => fmt::printfln("{}", s)!; }; };
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).
#Haskell
Haskell
import System.Directory import Text.Regex import Data.Maybe   walk :: FilePath -> String -> IO () walk dir pattern = do filenames <- getDirectoryContents dir mapM_ putStrLn $ filter (isJust.(matchRegex $ mkRegex pattern)) filenames   main = walk "." ".\\.hs$"
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 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 HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK Letter frequencies for English can be found here. Specifics for this task: Take only the ciphertext as input. You can assume it's all capitalized and has no punctuation, but it might have whitespace. Assume the plaintext is written in English. Find and output the key. Use that key to decrypt and output the original plaintext. Maintaining the whitespace from the ciphertext is optional. The algorithm doesn't have to be perfect (which may not be possible) but it should work when given enough ciphertext. The example above is fairly long, and should be plenty for any algorithm.
#C.2B.2B
C++
#include <iostream> #include <string> #include <vector> #include <map> #include <algorithm> #include <array> using namespace std;   typedef array<pair<char, double>, 26> FreqArray;   class VigenereAnalyser { private: array<double, 26> targets; array<double, 26> sortedTargets; FreqArray freq;   // Update the freqs array FreqArray& frequency(const string& input) { for (char c = 'A'; c <= 'Z'; ++c) freq[c - 'A'] = make_pair(c, 0);   for (size_t i = 0; i < input.size(); ++i) freq[input[i] - 'A'].second++;   return freq; }   double correlation(const string& input) { double result = 0.0; frequency(input);   sort(freq.begin(), freq.end(), [](pair<char, double> u, pair<char, double> v)->bool { return u.second < v.second; });   for (size_t i = 0; i < 26; ++i) result += freq[i].second * sortedTargets[i];   return result; }   public: VigenereAnalyser(const array<double, 26>& targetFreqs) { targets = targetFreqs; sortedTargets = targets; sort(sortedTargets.begin(), sortedTargets.end()); }   pair<string, string> analyze(string input) { string cleaned; for (size_t i = 0; i < input.size(); ++i) { if (input[i] >= 'A' && input[i] <= 'Z') cleaned += input[i]; else if (input[i] >= 'a' && input[i] <= 'z') cleaned += input[i] + 'A' - 'a'; }   size_t bestLength = 0; double bestCorr = -100.0;   // Assume that if there are less than 20 characters // per column, the key's too long to guess for (size_t i = 2; i < cleaned.size() / 20; ++i) { vector<string> pieces(i); for (size_t j = 0; j < cleaned.size(); ++j) pieces[j % i] += cleaned[j];   // The correlation increases artificially for smaller // pieces/longer keys, so weigh against them a little double corr = -0.5*i; for (size_t j = 0; j < i; ++j) corr += correlation(pieces[j]);   if (corr > bestCorr) { bestLength = i; bestCorr = corr; } }   if (bestLength == 0) return make_pair("Text is too short to analyze", "");   vector<string> pieces(bestLength); for (size_t i = 0; i < cleaned.size(); ++i) pieces[i % bestLength] += cleaned[i];   vector<FreqArray> freqs; for (size_t i = 0; i < bestLength; ++i) freqs.push_back(frequency(pieces[i]));   string key = ""; for (size_t i = 0; i < bestLength; ++i) { sort(freqs[i].begin(), freqs[i].end(), [](pair<char, double> u, pair<char, double> v)->bool { return u.second > v.second; });   size_t m = 0; double mCorr = 0.0; for (size_t j = 0; j < 26; ++j) { double corr = 0.0; char c = 'A' + j; for (size_t k = 0; k < 26; ++k) { int d = (freqs[i][k].first - c + 26) % 26; corr += freqs[i][k].second * targets[d]; }   if (corr > mCorr) { m = j; mCorr = corr; } }   key += m + 'A'; }   string result = ""; for (size_t i = 0; i < cleaned.size(); ++i) result += (cleaned[i] - key[i % key.length()] + 26) % 26 + 'A';   return make_pair(result, key); } };   int main() { string input = "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 HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" "FWAML ZZRXJ EKAHV FASMU LVVUT TGK";   array<double, 26> english = { 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.00150, 0.01974, 0.00074};   VigenereAnalyser va(english); pair<string, string> output = va.analyze(input);   cout << "Key: " << output.second << endl << endl; cout << "Text: " << output.first << endl; }
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).
#Arturo
Arturo
; list all files at current path print list.recursive "."   ; get all files at given path ; and select only the ones we want   ; just select the files with .md extension select list.recursive "some/path" => [".md" = extract.extension]   ; just select the files that contain "test" select list.recursive "some/path" => [in? "test"]
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).
#AutoHotkey
AutoHotkey
Loop, %A_Temp%\*.tmp,,1 out .= A_LoopFileName "`n" MsgBox,% out
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.
#C
C
  #include<stdlib.h> #include<stdio.h>   int getWater(int* arr,int start,int end,int cutoff){ int i, sum = 0;   for(i=start;i<=end;i++) sum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);   return sum; }   int netWater(int* arr,int size){ int i, j, ref1, ref2, marker, markerSet = 0,sum = 0;   if(size<3) return 0;   for(i=0;i<size-1;i++){ start:if(i!=size-2 && arr[i]>arr[i+1]){ ref1 = i;   for(j=ref1+1;j<size;j++){ if(arr[j]>=arr[ref1]){ ref2 = j;   sum += getWater(arr,ref1+1,ref2-1,ref1);   i = ref2;   goto start; }   else if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){ marker = j+1; markerSet = 1; } }   if(markerSet==1){ sum += getWater(arr,ref1+1,marker-1,marker);   i = marker;   markerSet = 0;   goto start; } } }   return sum; }   int main(int argC,char* argV[]) { int *arr,i;   if(argC==1) printf("Usage : %s <followed by space separated series of integers>"); else{ arr = (int*)malloc((argC-1)*sizeof(int));   for(i=1;i<argC;i++) arr[i-1] = atoi(argV[i]);   printf("Water collected : %d",netWater(arr,argC-1)); }   return 0; }  
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.
#Haskell
Haskell
  -- Compile with: ghc -O2 -fllvm -fforce-recomp -threaded --make {-# LANGUAGE BangPatterns #-} module Main where   import System.Random   import Data.Word import Data.Array.Repa as Repa import Data.Array.Repa.IO.BMP   {-# INLINE sqDistance #-} sqDistance :: Word32 -> Word32 -> Word32 -> Word32 -> Word32 sqDistance !x1 !y1 !x2 !y2 = ((x1-x2)^2) + ((y1-y2)^2)   centers :: Int -> Int -> Array U DIM2 Word32 centers nCenters nCells = fromListUnboxed (Z :. nCenters :. 2) $ take (2*nCenters) $ randomRs (0, fromIntegral nCells) (mkStdGen 1)   applyReduce2 arr f = traverse arr (\(i :. j) -> i) $ \lookup (Z:.i) -> f (lookup (Z:.i:.0)) (lookup (Z:.i:.1))   minimize1D arr = foldS f h t where indexed arr = traverse arr id (\src idx@(Z :. i) -> (src idx, (fromIntegral i))) (Z :. n) = extent arr iarr = indexed arr h = iarr ! (Z :. 0) t = extract (Z :. 1) (Z :. (n-1)) iarr   f min@(!valMin, !iMin ) x@(!val, !i) | val < valMin = x | otherwise = min   voronoi :: Int -> Int -> Array D DIM2 Word32 voronoi nCenters nCells = let {-# INLINE cellReducer #-} cellReducer = applyReduce2 (centers nCenters nCells) {-# INLINE nearestCenterIndex #-} nearestCenterIndex = snd . (Repa.! Z) . minimize1D in Repa.fromFunction (Z :. nCells :. nCells :: DIM2) $ \ (Z:.i:.j) -> nearestCenterIndex $ cellReducer (sqDistance (fromIntegral i) (fromIntegral j))   genColorTable :: Int -> Array U DIM1 (Word8, Word8, Word8) genColorTable n = fromListUnboxed (Z :. n) $ zip3 l1 l2 l3 where randoms = randomRs (0,255) (mkStdGen 1) (l1, rest1) = splitAt n randoms (l2, rest2) = splitAt n rest1 l3 = take n rest2   colorize :: Array U DIM1 (Word8, Word8, Word8) -> Array D DIM2 Word32 -> Array D DIM2 (Word8, Word8, Word8) colorize ctable = Repa.map $ \x -> ctable Repa.! (Z:. fromIntegral x)   main = do let nsites = 150 let ctable = genColorTable nsites voro <- computeP $ colorize ctable (voronoi nsites 512) :: IO (Array U DIM2 (Word8, Word8, Word8)) writeImageToBMP "out.bmp" voro    
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
#11l
11l
F encrypt(key, text) V out = ‘’ V j = 0 L(c) text I !c.is_alpha() L.continue out ‘’= Char(code' (c.uppercase().code + key[j].code - 2 * ‘A’.code) % 26 + ‘A’.code) j = (j + 1) % key.len R out   F decrypt(key, text) V out = ‘’ V j = 0 L(c) text I !c.is_alpha() L.continue out ‘’= Char(code' (c.code - key[j].code + 26) % 26 + ‘A’.code) j = (j + 1) % key.len R out   V key = ‘VIGENERECIPHER’ V original = ‘Beware the Jabberwock, my son! The jaws that bite, the claws that catch!’ V encrypted = encrypt(key, original) V decrypted = decrypt(key, encrypted)   print(original) print(‘Encrypted: ’encrypted) print(‘Decrypted: ’decrypted)
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.
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"WINLIB5" ON ERROR SYS "MessageBox", @hwnd%, REPORT$, 0, 0 : QUIT   REM!WC Windows constants: TVI_SORT = -65533 TVIF_TEXT = 1 TVM_INSERTITEM = 4352 TVS_HASBUTTONS = 1 TVS_HASLINES = 2 TVS_LINESATROOT = 4   REM. TV_INSERTSTRUCT DIM tvi{hParent%, \ \ hInsertAfter%, \ \ mask%, \ \ hItem%, \ \ state%, \ \ stateMask%, \ \ pszText%, \ \ cchTextMax%, \ \ iImage%, \ \ iSelectedImage%,\ \ cChildren%, \ \ lParam% \ \ }   SYS "InitCommonControls" hTree% = FN_createwindow("SysTreeView32", "", 0, 0, @vdu.tr%, @vdu.tb%, 0, \ \ TVS_HASLINES OR TVS_HASBUTTONS OR TVS_LINESATROOT, 0) hroot% = FNinsertnode(0, "Root") hchild1% = FNinsertnode(hroot%, "Child 1") hchild2% = FNinsertnode(hroot%, "Child 2") hchild11% = FNinsertnode(hchild1%, "Grandchild 1") hchild12% = FNinsertnode(hchild1%, "Grandchild 2") hchild21% = FNinsertnode(hchild2%, "Grandchild 3") hchild22% = FNinsertnode(hchild2%, "Grandchild 4")   REPEAT WAIT 1 UNTIL FALSE END   DEF FNinsertnode(hparent%, text$) LOCAL hnode% text$ += CHR$0   tvi.hParent% = hparent% tvi.hInsertAfter% = TVI_SORT tvi.mask% = TVIF_TEXT tvi.pszText% = !^text$   SYS "SendMessage", hTree%, TVM_INSERTITEM, 0, tvi{} TO hnode% IF hnode% = 0 ERROR 100, "TVM_INSERTITEM failed" SYS "InvalidateRect", hTree%, 0, 0 = hnode%
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).
#HicEst
HicEst
CHARACTER dirtxt='dir.txt', filename*80   SYSTEM(DIR='*.*', FIle=dirtxt) ! "file names", length, attrib, Created, LastWrite, LastAccess OPEN(FIle=dirtxt, Format='"",', LENgth=files) ! parses column 1 ("file names")   DO nr = 1, files filename = dirtxt(nr,1) ! reads dirtxt row = nr, column = 1 to filename ! write file names with extensions "txt", or "hic", or "jpg" (case insensitive) using RegEx option =128: IF( INDEX(filename, "\.txt|\.hic|\.jpg", 128) ) WRITE() filename ENDDO
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).
#Icon_and_Unicon
Icon and Unicon
procedure main() every write(getdirs(".","icn")) # writes out all directories from the current directory down end   procedure getdirs(s,pat) #: return a list of directories beneath the directory 's' local d,f   if ( stat(s).mode ? ="d" ) & ( d := open(s) ) then { while f := read(d) do if find(pat,f) then suspend f close(d) } end
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 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 HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK Letter frequencies for English can be found here. Specifics for this task: Take only the ciphertext as input. You can assume it's all capitalized and has no punctuation, but it might have whitespace. Assume the plaintext is written in English. Find and output the key. Use that key to decrypt and output the original plaintext. Maintaining the whitespace from the ciphertext is optional. The algorithm doesn't have to be perfect (which may not be possible) but it should work when given enough ciphertext. The example above is fairly long, and should be plenty for any algorithm.
#D
D
import std.stdio, std.algorithm, std.typecons, std.string, std.array, std.numeric, std.ascii;   string[2] vigenereDecrypt(in double[] targetFreqs, in string input) { enum nAlpha = std.ascii.uppercase.length;   static double correlation(in string txt, in double[] sTargets) pure nothrow /*@safe*/ @nogc { uint[nAlpha] charCounts = 0; foreach (immutable c; txt) charCounts[c - 'A']++; return charCounts[].sort().release.dotProduct(sTargets); }   static frequency(in string txt) pure nothrow @safe { auto freqs = new Tuple!(char,"c", uint,"d")[nAlpha]; foreach (immutable i, immutable c; std.ascii.uppercase) freqs[i] = tuple(c, 0); foreach (immutable c; txt) freqs[c - 'A'].d++; return freqs; }   static string[2] decode(in string cleaned, in string key) pure nothrow @safe { assert(!key.empty); string decoded; foreach (immutable i, immutable c; cleaned) decoded ~= (c - key[i % $] + nAlpha) % nAlpha + 'A'; return [key, decoded]; }   static size_t findBestLength(in string cleaned, in double[] sTargets) pure nothrow /*@safe*/ { size_t bestLength; double bestCorr = -100.0;   // Assume that if there are less than 20 characters // per column, the key's too long to guess foreach (immutable i; 2 .. cleaned.length / 20) { auto pieces = new Appender!string[i]; foreach (immutable j, immutable c; cleaned) pieces[j % i] ~= c;   // The correlation seems to increase for smaller // pieces/longer keys, so weigh against them a little double corr = -0.5 * i; foreach (const p; pieces) corr += correlation(p.data, sTargets);   if (corr > bestCorr) { bestLength = i; bestCorr = corr; } }   return bestLength; }   static string findKey(in string cleaned, in size_t bestLength, in double[] targetFreqs) pure nothrow @safe { auto pieces = new string[bestLength]; foreach (immutable i, immutable c; cleaned) pieces[i % bestLength] ~= c;   string key; foreach (fr; pieces.map!frequency) { fr.sort!q{ a.d > b.d };   size_t m; double maxCorr = 0.0; foreach (immutable j, immutable c; uppercase) { double corr = 0.0; foreach (immutable frc; fr) { immutable di = (frc.c - c + nAlpha) % nAlpha; corr += frc.d * targetFreqs[di]; }   if (corr > maxCorr) { m = j; maxCorr = corr; } }   key ~= m + 'A'; }   return key; }   immutable cleaned = input.toUpper.removechars("^A-Z");   //immutable sortedTargets = targetFreqs.sorted; immutable sortedTargets = targetFreqs.dup.sort().release.idup;   immutable bestLength = findBestLength(cleaned, sortedTargets); if (bestLength == 0) throw new Exception("Text is too short to analyze.");   immutable string key = findKey(cleaned, bestLength, targetFreqs); return decode(cleaned, key); }     void main() { immutable 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 BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK";   immutable englishFrequences = [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.00150, 0.01974, 0.00074];   immutable key_dec = vigenereDecrypt(englishFrequences, encoded); writefln("Key: %s\n\nText: %s", key_dec[0], key_dec[1]); }
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).
#BaCon
BaCon
PRINT WALK$(".", 1, ".+", TRUE, NL$)
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).
#Batch_File
Batch File
dir /s /b "%windir%\System32\*.exe"
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.
#C.23
C#
class Program { static void Main(string[] args) { int[][] wta = { new int[] {1, 5, 3, 7, 2}, new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 }, new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 }, new int[] { 5, 5, 5, 5 }, new int[] { 5, 6, 7, 8 }, new int[] { 8, 7, 7, 6 }, new int[] { 6, 7, 10, 7, 6 }}; string blk, lf = "\n", tb = "██", wr = "≈≈", mt = " "; for (int i = 0; i < wta.Length; i++) { int bpf; blk = ""; do { string floor = ""; bpf = 0; for (int j = 0; j < wta[i].Length; j++) { if (wta[i][j] > 0) { floor += tb; wta[i][j] -= 1; bpf += 1; } else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt); } if (bpf > 0) blk = floor + lf + blk; } while (bpf > 0); while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt); while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt); if (args.Length > 0) System.Console.Write("\n{0}", blk); System.Console.WriteLine("Block {0} retains {1,2} water units.", i + 1, (blk.Length - blk.Replace(wr, "").Length) / 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.
#Icon_and_Unicon
Icon and Unicon
link graphics,printf,strings   record site(x,y,colour) # site data position and colour invocable all # needed for string metrics   procedure main(A) # voronoi   &window := open("Voronoi","g","bg=black") | stop("Unable to open window")   WAttrib("canvas=hidden") # figure out maximal size width & height WAttrib(sprintf("size=%d,%d",WAttrib("displaywidth"),WAttrib("displayheight"))) WAttrib("canvas=maximal") height := WAttrib("height") width := WAttrib("width")   metrics := ["hypot","taxi","taxi3"] # different metrics   while case a := get(A) of { # command line arguments "--sites" | "-s" : sites := 0 < integer(a := get(A)) | runerr(205,a) "--height" | "-h" : height := 0 < (height >= integer(a := get(A))) | runerr(205,a) "--width" | "-w" : width := 0 < (width >= integer(a := get(A))) | runerr(205,a) "--metric" | "-m" : metric := ((a := get(A)) == !metrics) | runerr(205,a) "--help" | "-?" : write("Usage:\n voronoi [[--sites|-s] n] ", "[[--height|-h] pixels] [[--width|-w] pixels]", "[[--metric|-m] metric_procedure]", "[--help|-?]\n\n") }   /metric := metrics[1] # default to normal /sites := ?(r := integer(.1*width)) + r # sites = random .1 to .2 of width if not given   WAttrib(sprintf("label=Voronoi %dx%d %d %s",width,height,sites,metric)) WAttrib(sprintf("size=%d,%d",width,height))   x := "0123456789abcdef" # hex for random sites (colour) siteL := [] every 1 to sites do # random sites put(siteL, site(?width,?height,cat("#",?x,?x,?x,?x,?x,?x)))   VoronoiDiagram(width,height,siteL,metric) # Voronoi-ize it WDone() end   procedure hypot(x,y,site) # normal metric return sqrt((x-site.x)^2 + (y-site.y)^2) end   procedure taxi(x,y,site) # "taxi" metric return abs(x-site.x)+abs(y-site.y) end   procedure taxi3(x,y,site) # copied from a commented out version (TCL) return (abs(x-site.x)^3+abs(y-site.y)^3)^(.3) end   procedure VoronoiDiagram(width,height,siteL,metric) /metric := hypot every y := 1 to height & x := 1 to width do { dist := width+height # anything larger than diagonal every site := !siteL do { if dist < (dt := metric(x,y,site)) then next # skip else if dist >:= dt then Fg(site.colour) # site else Fg("#000000") # unowned DrawPoint(x,y) } }   Fg("Black") every site := !siteL do # mark sites DrawCircle(site.x,site.y,1) end
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
#Action.21
Action!
PROC Fix(CHAR ARRAY in,fixed) INT i CHAR c   fixed(0)=0 FOR i=1 TO in(0) DO c=in(i) IF c>='a AND c<='z THEN c==-('a-'A) FI IF c>='A AND c<='Z THEN fixed(0)==+1 fixed(fixed(0))=c FI OD RETURN   PROC Process(CHAR ARRAY in,key,out INT dir) CHAR ARRAY inFixed(256),keyFixed(256) INT keyI,tmp,i CHAR c   out(0)=0 Fix(in,inFixed) Fix(key,keyFixed) IF inFixed(0)=0 OR keyFixed(0)=0 THEN RETURN FI   keyI=1 FOR i=1 TO inFixed(0) DO c=inFixed(i) tmp=c-'A+dir*(keyFixed(keyI)-'A) IF tmp<0 THEN tmp==+26 FI out(0)==+1 out(out(0))='A+tmp MOD 26 keyI==+1 IF keyI>keyFixed(0) THEN keyI=1 FI OD RETURN   PROC Encrypt(CHAR ARRAY in,key,out) Process(in,key,out,1) RETURN   PROC Decrypt(CHAR ARRAY in,key,out) Process(in,key,out,-1) RETURN   PROC Test(CHAR ARRAY in,key) CHAR ARRAY enc(256),dec(256)   PrintE("Original:") PrintE(in) Encrypt(in,key,enc) PrintF("Encrypted key=%S:%E",key) PrintE(enc) Decrypt(enc,key,dec) PrintF("Decrypted key=%S:%E",key) PrintE(dec) PutE() RETURN   PROC Main() Test("Attack at dawn!","LEMONLEMONLE")   Test("Crypto is short for cryptography.","ABCDABCDABCDABCDABCDABCDABCD") RETURN
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.
#C
C
#include <stdio.h> #include <stdlib.h>   typedef struct stem_t *stem; struct stem_t { const char *str; stem next; };   void tree(int root, stem head) { static const char *sdown = " |", *slast = " `", *snone = " "; struct stem_t col = {0, 0}, *tail;   for (tail = head; tail; tail = tail->next) { printf("%s", tail->str); if (!tail->next) break; }   printf("--%d\n", root);   if (root <= 1) return;   if (tail && tail->str == slast) tail->str = snone;   if (!tail) tail = head = &col; else tail->next = &col;   while (root) { // make a tree by doing something random int r = 1 + (rand() % root); root -= r; col.str = root ? sdown : slast;   tree(r, head); }   tail->next = 0; }   int main(int c, char**v) { int n; if (c < 2 || (n = atoi(v[1])) < 0) n = 8;   tree(n, 0); return 0; }
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).
#IDL
IDL
f = file_search('*.txt', count=cc) if cc gt 0 then print,f
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).
#J
J
require 'dir' 0 dir '*.png' 0 dir '/mydir/*.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 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 HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK Letter frequencies for English can be found here. Specifics for this task: Take only the ciphertext as input. You can assume it's all capitalized and has no punctuation, but it might have whitespace. Assume the plaintext is written in English. Find and output the key. Use that key to decrypt and output the original plaintext. Maintaining the whitespace from the ciphertext is optional. The algorithm doesn't have to be perfect (which may not be possible) but it should work when given enough ciphertext. The example above is fairly long, and should be plenty for any algorithm.
#Go
Go
package main   import ( "fmt" "strings" )   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" + "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" + "ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" + "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" + "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" + "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" + "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" + "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" + "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" + "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" + "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" + "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" + "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" + "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" + "FWAML ZZRXJ EKAHV FASMU LVVUT TGK"   var freq = [26]float64{ 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.00150, 0.01974, 0.00074, }   func sum(a []float64) (sum float64) { for _, f := range a { sum += f } return }   func bestMatch(a []float64) int { sum := sum(a) bestFit, bestRotate := 1e100, 0 for rotate := 0; rotate < 26; rotate++ { fit := 0.0 for i := 0; i < 26; i++ { d := a[(i+rotate)%26]/sum - freq[i] fit += d * d / freq[i] } if fit < bestFit { bestFit, bestRotate = fit, rotate } } return bestRotate }   func freqEveryNth(msg []int, key []byte) float64 { l := len(msg) interval := len(key) out := make([]float64, 26) accu := make([]float64, 26) for j := 0; j < interval; j++ { for k := 0; k < 26; k++ { out[k] = 0.0 } for i := j; i < l; i += interval { out[msg[i]]++ } rot := bestMatch(out) key[j] = byte(rot + 65) for i := 0; i < 26; i++ { accu[i] += out[(i+rot)%26] } } sum := sum(accu) ret := 0.0 for i := 0; i < 26; i++ { d := accu[i]/sum - freq[i] ret += d * d / freq[i] } return ret }   func decrypt(text, key string) string { var sb strings.Builder ki := 0 for _, c := range text { if c < 'A' || c > 'Z' { continue } ci := (c - rune(key[ki]) + 26) % 26 sb.WriteRune(ci + 65) ki = (ki + 1) % len(key) } return sb.String() }   func main() { enc := strings.Replace(encoded, " ", "", -1) txt := make([]int, len(enc)) for i := 0; i < len(txt); i++ { txt[i] = int(enc[i] - 'A') } bestFit, bestKey := 1e100, "" fmt.Println(" Fit Length Key") for j := 1; j <= 26; j++ { key := make([]byte, j) fit := freqEveryNth(txt, key) sKey := string(key) fmt.Printf("%f  %2d  %s", fit, j, sKey) if fit < bestFit { bestFit, bestKey = fit, sKey fmt.Print(" <--- best so far") } fmt.Println() } fmt.Println("\nBest key :", bestKey) fmt.Printf("\nDecrypted text:\n%s\n", decrypt(enc, bestKey)) }
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).
#BBC_BASIC
BBC BASIC
directory$ = "C:\Windows\" pattern$ = "*.chm" PROClisttree(directory$, pattern$) END   DEF PROClisttree(dir$, filter$) LOCAL dir%, sh%, res% DIM dir% LOCAL 317 IF RIGHT$(dir$) <> "\" IF RIGHT$(dir$) <> "/" dir$ += "\" SYS "FindFirstFile", dir$ + filter$, dir% TO sh% IF sh% <> -1 THEN REPEAT IF (!dir% AND 16) = 0 PRINT dir$ + $$(dir%+44) SYS "FindNextFile", sh%, dir% TO res% UNTIL res% = 0 SYS "FindClose", sh% ENDIF SYS "FindFirstFile", dir$ + "*", dir% TO sh% IF sh% <> -1 THEN REPEAT IF (!dir% AND 16) IF dir%?44 <> &2E THEN PROClisttree(dir$ + $$(dir%+44) + "\", filter$) ENDIF SYS "FindNextFile", sh%, dir% TO res% UNTIL res% = 0 SYS "FindClose", sh% ENDIF ENDPROC
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).
#C
C
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <regex.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <err.h>   enum { WALK_OK = 0, WALK_BADPATTERN, WALK_NAMETOOLONG, WALK_BADIO, };   #define WS_NONE 0 #define WS_RECURSIVE (1 << 0) #define WS_DEFAULT WS_RECURSIVE #define WS_FOLLOWLINK (1 << 1) /* follow symlinks */ #define WS_DOTFILES (1 << 2) /* per unix convention, .file is hidden */ #define WS_MATCHDIRS (1 << 3) /* if pattern is used on dir names too */   int walk_recur(char *dname, regex_t *reg, int spec) { struct dirent *dent; DIR *dir; struct stat st; char fn[FILENAME_MAX]; int res = WALK_OK; int len = strlen(dname); if (len >= FILENAME_MAX - 1) return WALK_NAMETOOLONG;   strcpy(fn, dname); fn[len++] = '/';   if (!(dir = opendir(dname))) { warn("can't open %s", dname); return WALK_BADIO; }   errno = 0; while ((dent = readdir(dir))) { if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.') continue; if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue;   strncpy(fn + len, dent->d_name, FILENAME_MAX - len); if (lstat(fn, &st) == -1) { warn("Can't stat %s", fn); res = WALK_BADIO; continue; }   /* don't follow symlink unless told so */ if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK)) continue;   /* will be false for symlinked dirs */ if (S_ISDIR(st.st_mode)) { /* recursively follow dirs */ if ((spec & WS_RECURSIVE)) walk_recur(fn, reg, spec);   if (!(spec & WS_MATCHDIRS)) continue; }   /* pattern match */ if (!regexec(reg, fn, 0, 0, 0)) puts(fn); }   if (dir) closedir(dir); return res ? res : errno ? WALK_BADIO : WALK_OK; }   int walk_dir(char *dname, char *pattern, int spec) { regex_t r; int res; if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB)) return WALK_BADPATTERN; res = walk_recur(dname, &r, spec); regfree(&r);   return res; }   int main() { int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS); switch(r) { case WALK_OK: break; case WALK_BADIO: err(1, "IO error"); case WALK_BADPATTERN: err(1, "Bad pattern"); case WALK_NAMETOOLONG: err(1, "Filename too long"); default: err(1, "Unknown error?"); } return 0; }
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.
#C.2B.2B
C++
  #include <iostream> #include <vector> #include <algorithm>   enum { EMPTY, WALL, WATER };   auto fill(const std::vector<int> b) { auto water = 0; const auto rows = *std::max_element(std::begin(b), std::end(b)); const auto cols = std::size(b); std::vector<std::vector<int>> g(rows); for (auto& r : g) { for (auto i = 0; i < cols; ++i) { r.push_back(EMPTY); } } for (auto c = 0; c < cols; ++c) { for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) { g[r][c] = WALL; } } for (auto c = 0; c < cols - 1; ++c) { auto start_row = rows - b[c]; while (start_row < rows) { if (g[start_row][c] == EMPTY) break; auto c2 = c + 1; bool hitWall = false; while (c2 < cols) { if (g[start_row][c2] == WALL) { hitWall = true; break; } ++c2; } if (hitWall) { for (auto i = c + 1; i < c2; ++i) { g[start_row][i] = WATER; ++water; } } ++start_row; } } return water; }   int main() { std::vector<std::vector<int>> b = { { 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 (const auto v : b) { auto water = fill(v); std::cout << water << " water drops." << std::endl; } std::cin.ignore(); std::cin.get(); return 0; }
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.
#J
J
NB. (number of points) voronoi (shape) NB. Generates an array of indices of the nearest point voronoi =: 4 :0 p =. (x,2) ?@$ y (i.<./)@:(+/@:*:@:-"1&p)"1 ,"0/&i./ y )   load'viewmat' viewmat 25 voronoi 500 500
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
#Ada
Ada
WITH Ada.Text_IO, Ada.Characters.Handling; USE Ada.Text_IO, Ada.Characters.Handling;   PROCEDURE Main IS SUBTYPE Alpha IS Character RANGE 'A' .. 'Z'; TYPE Ring IS MOD (Alpha'Range_length); TYPE Seq IS ARRAY (Integer RANGE <>) OF Ring;   FUNCTION "+" (S, Key : Seq) RETURN Seq IS R : Seq (S'Range); BEGIN FOR I IN R'Range LOOP R (I) := S (I) + Key (Key'First + (I - R'First) MOD Key'Length); END LOOP; RETURN R; END "+";   FUNCTION "-" (S : Seq) RETURN Seq IS R : Seq (S'Range); BEGIN FOR I IN R'Range LOOP R (I) := - S (I); END LOOP; RETURN R; END "-";   FUNCTION To_Seq (S : String) RETURN Seq IS R  : Seq (S'Range); I  : Integer := R'First; BEGIN FOR C OF To_Upper (S) LOOP IF C IN Alpha THEN R (I) := Ring'Mod (Alpha'Pos (C) - Alpha'Pos (Alpha'First)); I := I + 1; END IF; END LOOP; RETURN R (R'First .. I - 1); END To_Seq;   FUNCTION To_String (S : Seq ) RETURN String IS R : String (S'Range); BEGIN FOR I IN R'Range LOOP R (I) := Alpha'Val ( Integer (S (I)) + Alpha'Pos (Alpha'First)); END LOOP; RETURN R; END To_String;   Input : Seq := To_Seq (Get_Line); Key : Seq := To_Seq (Get_Line); Crypt : Seq := Input + Key; BEGIN Put_Line ("Encrypted: " & To_String (Crypt)); Put_Line ("Decrypted: " & To_String (Crypt + (-Key))); END Main;    
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.
#C.2B.2B
C++
#include <functional> #include <iostream> #include <random>   class BinarySearchTree { private: struct Node { int key; Node *left, *right;   Node(int k) : key(k), left(nullptr), right(nullptr) { //empty } } *root;   public: BinarySearchTree() : root(nullptr) { // empty }   bool insert(int key) { if (root == nullptr) { root = new Node(key); } else { auto n = root; Node *parent; while (true) { if (n->key == key) { return false; }   parent = n;   bool goLeft = key < n->key; n = goLeft ? n->left : n->right;   if (n == nullptr) { if (goLeft) { parent->left = new Node(key); } else { parent->right = new Node(key); } break; } } } return true; }   friend std::ostream &operator<<(std::ostream &, const BinarySearchTree &); };   template<typename T> void display(std::ostream &os, const T *n) { if (n != nullptr) { os << "Node(";   display(os, n->left);   os << ',' << n->key << ',';   display(os, n->right);   os << ")"; } else { os << '-'; } }   std::ostream &operator<<(std::ostream &os, const BinarySearchTree &bst) { display(os, bst.root); return os; }   int main() { std::default_random_engine generator; std::uniform_int_distribution<int> distribution(0, 200); auto rng = std::bind(distribution, generator);   BinarySearchTree tree;   tree.insert(100); for (size_t i = 0; i < 20; i++) { tree.insert(rng()); } std::cout << tree << '\n';   return 0; }
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).
#Java
Java
File dir = new File("/foo/bar");   String[] contents = dir.list(); for (String file : contents) if (file.endsWith(".mp3")) System.out.println(file);
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).
#JavaScript
JavaScript
var fso = new ActiveXObject("Scripting.FileSystemObject"); var dir = fso.GetFolder('test_folder');   function walkDirectory(dir, re_pattern) { WScript.Echo("Files in " + dir.name + " matching '" + re_pattern +"':"); walkDirectoryFilter(dir.Files, re_pattern);   WScript.Echo("Folders in " + dir.name + " matching '" + re_pattern +"':"); walkDirectoryFilter(dir.Subfolders, re_pattern); }   function walkDirectoryFilter(items, re_pattern) { var e = new Enumerator(items); while (! e.atEnd()) { var item = e.item(); if (item.name.match(re_pattern)) WScript.Echo(item.name); e.moveNext(); } }   walkDirectory(dir, '\\.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 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 HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK Letter frequencies for English can be found here. Specifics for this task: Take only the ciphertext as input. You can assume it's all capitalized and has no punctuation, but it might have whitespace. Assume the plaintext is written in English. Find and output the key. Use that key to decrypt and output the original plaintext. Maintaining the whitespace from the ciphertext is optional. The algorithm doesn't have to be perfect (which may not be possible) but it should work when given enough ciphertext. The example above is fairly long, and should be plenty for any algorithm.
#Haskell
Haskell
{-# LANGUAGE TupleSections #-} import Data.List(transpose, nub, sort, maximumBy) import Data.Ord (comparing) import Data.Char (ord) import Data.Map (Map, fromListWith, toList, findWithDefault)   average :: Fractional a => [a] -> a average as = sum as / fromIntegral (length as)   -- Create a map from each entry in list to the number of occurrences of -- that entry in the list. countEntries :: Ord a => [a] -> Map a Int countEntries = fromListWith (+) . fmap (,1)   -- Break a string up into substrings of n chars. breakup :: Int -> [a] -> [[a]] breakup _ [] = [] breakup n as = let (h, r) = splitAt n as in h:breakup n r   -- Dole out elements of a string over a n element distribution. distribute :: [a] -> Int -> [[a]] distribute as n = transpose $ breakup n as   -- The probability that members of a pair of characters taken randomly -- from a given string are equal. coincidence :: (Ord a, Fractional b) => [a] -> b coincidence str = let charCounts = snd <$> toList (countEntries str) strln = length str d = fromIntegral $ strln * (strln - 1) n = fromIntegral $ sum $ fmap (\cc -> cc * (cc-1)) charCounts in n / d   -- Use the average probablity of coincidence for all the members of -- a distribution to rate the distribution - the higher the better. -- The correlation increases artificially for smaller -- pieces/longer keys, so weigh against them a little rate :: (Ord a, Fractional b) => [[a]] -> b rate d = average (fmap coincidence d) - fromIntegral (length d) / 3000.0   -- Multiply elements of lists together and add up the results. dot :: Num a => [a] -> [a] -> a dot v0 v1 = sum $ zipWith (*) v0 v1   -- Given two lists of floats, rotate one of them by the number of -- characters indicated by letter and then 'dot' them together. rotateAndDot :: Num a => [a] -> [a] -> Char -> a rotateAndDot v0 v1 letter = dot v0 (drop (ord letter - ord 'A') (cycle v1))   -- Find decoding offset that results in best match -- between actual char frequencies and expected frequencies. getKeyChar :: RealFrac a => [a] -> String -> Char getKeyChar expected sample = let charCounts = countEntries sample countInSample c = findWithDefault 0 c charCounts actual = fmap (fromIntegral . countInSample) ['A'..'Z'] in maximumBy (comparing $ rotateAndDot expected actual) ['A'..'Z']   main = do let cr = filter (/=' ') crypt -- Assume that if there are less than 20 characters -- per column, the key's too long to guess distributions = fmap (distribute cr) [1..length cr `div` 20] bestDistribution = maximumBy (comparing rate) distributions key = fmap (getKeyChar englishFrequencies) bestDistribution alphaSum a b = ['A'..'Z'] !! ((ord b - ord a) `mod` 26) mapM_ putStrLn ["Key: " ++ key, "Decrypted Text: " ++ zipWith alphaSum (cycle key) cr]   englishFrequencies = [ 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.00150, 0.01974, 0.00074 ]   crypt = "\ \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 HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\ \ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\ \JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\ \LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\ \MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\ \QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\ \RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\ \TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\ \SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\ \ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\ \BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\ \BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\ \FWAML ZZRXJ EKAHV FASMU LVVUT TGK\ \"
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).
#C.23
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq;   namespace RosettaRecursiveDirectory { class Program { static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern) { var directoryStack = new Stack<DirectoryInfo>(); directoryStack.Push(new DirectoryInfo(rootPath)); while (directoryStack.Count > 0) { var dir = directoryStack.Pop(); try { foreach (var i in dir.GetDirectories()) directoryStack.Push(i); } catch (UnauthorizedAccessException) { continue; // We don't have access to this directory, so skip it } foreach (var f in dir.GetFiles().Where(Pattern)) // "Pattern" is a function yield return f; } } static void Main(string[] args) { // Print the full path of all .wmv files that are somewhere in the C:\Windows directory or its subdirectories foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv")) Console.WriteLine(file.FullName); Console.WriteLine("Done."); } } }  
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.
#Clojure
Clojure
  (defn trapped-water [towers] (let [maxes #(reductions max %) ; the seq of increasing max values found in the input seq maxl (maxes towers) ; the seq of max heights to the left of each tower maxr (reverse (maxes (reverse towers))) ; the seq of max heights to the right of each tower mins (map min maxl maxr)] ; minimum highest surrounding tower per position (reduce + (map - mins towers)))) ; sum up the trapped water per position  
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
#11l
11l
F dice5() R random:(1..5)   F distcheck(func, repeats, delta) V bin = DefaultDict[Int, Int]() L 1..repeats bin[func()]++ V target = repeats I/ bin.len V deltacount = Int(delta / 100.0 * target) assert(all(bin.values().map(count -> abs(@target - count) < @deltacount)), ‘Bin distribution skewed from #. +/- #.: #.’.format(target, deltacount, sorted(bin.items()).map((key, count) -> (key, @target - count)))) print(bin)   distcheck(dice5, 1000000, 1)
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.
#Java
Java
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random;   import javax.imageio.ImageIO; import javax.swing.JFrame;   public class Voronoi extends JFrame { static double p = 3; static BufferedImage I; static int px[], py[], color[], cells = 100, size = 1000;   public Voronoi() { super("Voronoi Diagram"); setBounds(0, 0, size, size); setDefaultCloseOperation(EXIT_ON_CLOSE); int n = 0; Random rand = new Random(); I = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); px = new int[cells]; py = new int[cells]; color = new int[cells]; for (int i = 0; i < cells; i++) { px[i] = rand.nextInt(size); py[i] = rand.nextInt(size); color[i] = rand.nextInt(16777215);   } for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { n = 0; for (byte i = 0; i < cells; i++) { if (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) { n = i;   } } I.setRGB(x, y, color[n]);   } }   Graphics2D g = I.createGraphics(); g.setColor(Color.BLACK); for (int i = 0; i < cells; i++) { g.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5)); }   try { ImageIO.write(I, "png", new File("voronoi.png")); } catch (IOException e) {   }   }   public void paint(Graphics g) { g.drawImage(I, 0, 0, this); }   static double distance(int x1, int x2, int y1, int y2) { double d; d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); // Euclidian // d = Math.abs(x1 - x2) + Math.abs(y1 - y2); // Manhattan // d = Math.pow(Math.pow(Math.abs(x1 - x2), p) + Math.pow(Math.abs(y1 - y2), p), (1 / p)); // Minkovski return d; }   public static void main(String[] args) { new Voronoi().setVisible(true); } }  
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
#ALGOL_68
ALGOL 68
STRING key := "";   PROC vigenere cipher = (REF STRING key)VOID: ( FOR i FROM LWB key TO UPB key DO IF key[i] >= "A" AND key[i] <= "Z" THEN key +:= key[i] FI; IF key[i] >= "a" AND key[i] <= "z" THEN key +:= REPR(ABS key[i] + ABS"A" - ABS"a") FI OD );   PROC encrypt = (STRING text)STRING: ( STRING out := "";   INT j := LWB text; FOR i FROM LWB text TO UPB text DO CHAR c := text[i];   IF c >= "a" AND c <= "z" THEN c := REPR(ABS c + (ABS"A" - ABS"a")) FI; IF c >= "A" AND c <= "Z" THEN out +:= REPR((ABS c + ABS key[j] - 2*ABS"A") MOD 26 + ABS"A"); j := j MOD UPB key + 1 FI OD;   out );   PROC decrypt = (STRING text)STRING: ( STRING out;   INT j := LWB text; FOR i FROM LWB text TO UPB text DO CHAR c := text[i];   IF c >= "a" AND c <= "z" THEN c := REPR(ABS c + (ABS"A" - ABS"a")) FI; IF c >= "A" AND c <= "Z" THEN out +:= REPR((ABS c - ABS key[j] + 26) MOD 26 + ABS"A"); j := j MOD UPB key + 1 FI OD;   out );   main: ( vigenere cipher(key:="VIGENERECIPHER");   STRING original := "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; STRING encrypted := encrypt(original); STRING decrypted := decrypt(encrypted);   print((original, new line)); print(("Encrypted: ", encrypted, new line)); print(("Decrypted: ", decrypted, new line)) )
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.
#C.23
C#
using System;   public static class VisualizeTree { public static void Main() { "A".t( "B0".t( "C1", "C2".t( "D".t("E1", "E2", "E3")), "C3".t( "F1", "F2", "F3".t("G"), "F4".t("H1", "H2"))), "B1".t( "K1", "K2".t( "L1".t("M"), "L2", "L3"), "K3") ).Print(); }   private static Tree t(this string value, params Tree[] children) => new Tree(value, children);   private static void Print(this Tree tree) => tree.Print(true, "");   private static void Print(this Tree tree, bool last, string prefix) { (string current, string next) = last ? (prefix + "└─" + tree.Value, prefix + " ") : (prefix + "├─" + tree.Value, prefix + "| "); Console.WriteLine(current[2..]); for (int c = 0; c < tree.Children.Length; c++) { tree.Children[c].Print(c == tree.Children.Length - 1, next); } }   class Tree { public Tree(string value, params Tree[] children) => (Value, Children) = (value, children); public static implicit operator Tree(string value) => new Tree(value); public string Value { get; } public Tree[] Children { get; } }   }
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).
#Julia
Julia
for filename in readdir("/foo/bar") if endswith(filename, ".mp3") print(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. Note: Please be careful when running any code presented here. Related task   Walk Directory Tree   (read entire directory tree).
#Kotlin
Kotlin
// version 1.1.2   import java.io.File   fun walkDirectory(dirPath: String, pattern: Regex): List<String> { val d = File(dirPath) require(d.exists() && d.isDirectory()) return d.list().filter { it.matches(pattern) } }   fun main(args: Array<String>) { val r = Regex("""^a.*\.h$""") // get all C header files beginning with 'a' val files = walkDirectory("/usr/include", r) for (file in files) println(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 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 HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK Letter frequencies for English can be found here. Specifics for this task: Take only the ciphertext as input. You can assume it's all capitalized and has no punctuation, but it might have whitespace. Assume the plaintext is written in English. Find and output the key. Use that key to decrypt and output the original plaintext. Maintaining the whitespace from the ciphertext is optional. The algorithm doesn't have to be perfect (which may not be possible) but it should work when given enough ciphertext. The example above is fairly long, and should be plenty for any algorithm.
#Java
Java
public class Vig{ static String encodedMessage = "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 HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK";   final static double freq[] = { 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.00150, 0.01974, 0.00074 };     public static void main(String[] args) { int lenghtOfEncodedMessage = encodedMessage.length(); char[] encoded = new char [lenghtOfEncodedMessage] ; char[] key = new char [lenghtOfEncodedMessage] ;   encodedMessage.getChars(0, lenghtOfEncodedMessage, encoded, 0); int txt[] = new int[lenghtOfEncodedMessage]; int len = 0, j;   double fit, best_fit = 1e100;   for (j = 0; j < lenghtOfEncodedMessage; j++) if (Character.isUpperCase(encoded[j])) txt[len++] = encoded[j] - 'A';   for (j = 1; j < 30; j++) { fit = freq_every_nth(txt, len, j, key); System.out.printf("%f, key length: %2d ", fit, j); System.out.print(key); if (fit < best_fit) { best_fit = fit; System.out.print(" <--- best so far"); } System.out.print("\n");   } }     static String decrypt(String text, final String key) { String res = ""; text = text.toUpperCase(); for (int i = 0, j = 0; i < text.length(); i++) { char c = text.charAt(i); if (c < 'A' || c > 'Z') continue; res += (char)((c - key.charAt(j) + 26) % 26 + 'A'); j = ++j % key.length(); } return res; }   static int best_match(final double []a, final double []b) { double sum = 0, fit, d, best_fit = 1e100; int i, rotate, best_rotate = 0; for (i = 0; i < 26; i++) sum += a[i]; for (rotate = 0; rotate < 26; rotate++) { fit = 0; for (i = 0; i < 26; i++) { d = a[(i + rotate) % 26] / sum - b[i]; fit += d * d / b[i]; }   if (fit < best_fit) { best_fit = fit; best_rotate = rotate; } }   return best_rotate; }   static double freq_every_nth(final int []msg, int len, int interval, char[] key) { double sum, d, ret; double [] accu = new double [26]; double [] out = new double [26]; int i, j, rot;   for (j = 0; j < interval; j++) { for (i = 0; i < 26; i++) out[i] = 0; for (i = j; i < len; i += interval) out[msg[i]]++; rot = best_match(out, freq); try{ key[j] = (char)(rot + 'A'); } catch (Exception e) { System.out.print(e.getMessage()); } for (i = 0; i < 26; i++) accu[i] += out[(i + rot) % 26]; }   for (i = 0, sum = 0; i < 26; i++) sum += accu[i];   for (i = 0, ret = 0; i < 26; i++) { d = accu[i] / sum - freq[i]; ret += d * d / freq[i]; }   key[interval] = '\0'; return ret; }   }  
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).
#C.2B.2B
C++
#include "boost/filesystem.hpp" #include "boost/regex.hpp" #include <iostream>   using namespace boost::filesystem;   int main() { path current_dir("."); // boost::regex pattern("a.*"); // list all files starting with a for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) { std::string name = iter->path().filename().string(); if (regex_match(name, pattern)) std::cout << iter->path() << "\n"; } }
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).
#Cach.C3.A9_ObjectScript
Caché ObjectScript
  Class Utils.File [ Abstract ] {   ClassMethod WalkTree(pDir As %String = "", pMask As %String = "*.*") As %Status { // do some validation If pDir="" Quit $$$ERROR($$$GeneralError, "No directory specified.")   // search input directory for files matching wildcard Set fs=##class(%ResultSet).%New("%File.FileSet") Set sc=fs.Execute(pDir, pMask) While (fs.Next()) { Write !, fs.Name // sub-directory If fs.Type="D" Set sc=..WalkTree(fs.Name, pMask) }   // finished Quit $$$OK }   }  
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.
#CLU
CLU
max = proc [T: type] (a,b: T) returns (T) where T has lt: proctype (T,T) returns (bool) if a<b then return(b) else return(a) end end max   % based on: https://stackoverflow.com/a/42821623 water = proc (towers: sequence[int]) returns (int) si = sequence[int]   w: int := 0 left: int := 1 right: int := si$size(towers) max_left: int := si$bottom(towers) max_right: int := si$top(towers)   while left <= right do if towers[left] <= towers[right] then max_left := max[int](towers[left], max_left) w := w + max[int](max_left - towers[left], 0) left := left + 1 else max_right := max[int](towers[right], max_right) w := w + max[int](max_right - towers[right], 0) right := right - 1 end end return(w) end water   start_up = proc () si = sequence[int] ssi = sequence[si]   po: stream := stream$primary_output()   tests: ssi := ssi$[ si$[1, 5, 3, 7, 2], si$[5, 3, 7, 2, 6, 4, 5, 9, 1, 2], si$[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], si$[5, 5, 5, 5], si$[5, 6, 7, 8], si$[8, 7, 7, 6], si$[6, 7, 10, 7, 6] ]   for test: si in ssi$elements(tests) do stream$puts(po, int$unparse(water(test)) || " ") end end start_up
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
#Ada
Ada
with Ada.Numerics.Discrete_Random, Ada.Text_IO;   procedure Naive_Random is   type M_1000 is mod 1000; package Rand is new Ada.Numerics.Discrete_Random(M_1000); Gen: Rand.Generator;   procedure Perform(Modulus: Positive; Expected, Margin: Natural; Passed: out boolean) is Low: Natural  := (100-Margin) * Expected/100; High: Natural  := (100+Margin) * Expected/100; Buckets: array(0 .. Modulus-1) of Natural := (others => 0); Index: Natural; begin for I in 1 .. Expected * Modulus loop Index := Integer(Rand.Random(Gen)) mod Modulus; Buckets(Index) := Buckets(Index) + 1; end loop; Passed := True; for I in Buckets'Range loop Ada.Text_IO.Put("Bucket" & Integer'Image(I+1) & ":" & Integer'Image(Buckets(I))); if Buckets(I) < Low or else Buckets(I) > High then Ada.Text_IO.Put_Line(" (failed)"); Passed := False; else Ada.Text_IO.Put_Line(" (passed)"); end if; end loop; Ada.Text_IO.New_Line; end Perform;   Number_Of_Buckets: Positive := Natural'Value(Ada.Text_IO.Get_Line); Expected_Per_Bucket: Natural := Natural'Value(Ada.Text_IO.Get_Line); Margin_In_Percent: Natural := Natural'Value(Ada.Text_IO.Get_Line); OK: Boolean;   begin Ada.Text_IO.Put_Line( "Buckets:" & Integer'Image(Number_Of_Buckets) & ", Expected:" & Integer'Image(Expected_Per_Bucket) & ", Margin:" & Integer'Image(Margin_In_Percent)); Rand.Reset(Gen);   Perform(Modulus => Number_Of_Buckets, Expected => Expected_Per_Bucket, Margin => Margin_In_Percent, Passed => OK);   Ada.Text_IO.Put_Line("Test Passed? (" & Boolean'Image(OK) & ")"); end Naive_Random;
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.
#JavaScript
JavaScript
<!-- VoronoiD.html --> <html> <head><title>Voronoi diagram</title> <script> // HF#1 Like in PARI/GP: return random number 0..max-1 function randgp(max) {return Math.floor(Math.random()*max)} // HF#2 Random hex color function randhclr() { return "#"+ ("00"+randgp(256).toString(16)).slice(-2)+ ("00"+randgp(256).toString(16)).slice(-2)+ ("00"+randgp(256).toString(16)).slice(-2) } // HF#3 Metrics: Euclidean, Manhattan and Minkovski 3/20/17 function Metric(x,y,mt) { if(mt==1) {return Math.sqrt(x*x + y*y)} if(mt==2) {return Math.abs(x) + Math.abs(y)} if(mt==3) {return(Math.pow(Math.pow(Math.abs(x),3) + Math.pow(Math.abs(y),3),0.33333))} } // Plotting Voronoi diagram. aev 3/10/17 function pVoronoiD() { var cvs=document.getElementById("cvsId"); var ctx=cvs.getContext("2d"); var w=cvs.width, h=cvs.height; var x=y=d=dm=j=0, w1=w-2, h1=h-2; var n=document.getElementById("sites").value; var mt=document.getElementById("mt").value; var X=new Array(n), Y=new Array(n), C=new Array(n); ctx.fillStyle="white"; ctx.fillRect(0,0,w,h); for(var i=0; i<n; i++) { X[i]=randgp(w1); Y[i]=randgp(h1); C[i]=randhclr(); } for(y=0; y<h1; y++) { for(x=0; x<w1; x++) { dm=Metric(h1,w1,mt); j=-1; for(var i=0; i<n; i++) { d=Metric(X[i]-x,Y[i]-y,mt) if(d<dm) {dm=d; j=i;} }//fend i ctx.fillStyle=C[j]; ctx.fillRect(x,y,1,1); }//fend x }//fend y ctx.fillStyle="black"; for(var i=0; i<n; i++) { ctx.fillRect(X[i],Y[i],3,3); } } </script></head> <body style="font-family: arial, helvatica, sans-serif;"> <b>Please input number of sites: </b> <input id="sites" value=100 type="number" min="10" max="150" size="3">&nbsp;&nbsp; <b>Metric: </b> <select id="mt"> <option value=1 selected>Euclidean</option> <option value=2>Manhattan</option> <option value=3>Minkovski</option> </select>&nbsp; <input type="button" value="Plot it!" onclick="pVoronoiD();">&nbsp;&nbsp; <h3>Voronoi diagram</h3> <canvas id="cvsId" width="640" height="640" style="border: 2px inset;"></canvas> </body> </html>  
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
#Applesoft_BASIC
Applesoft BASIC
  100 : 110 REM VIGENERE CIPHER 120 : 200 REM SET-UP 210 K$ = "LEMON": PRINT "KEY: "; K$ 220 PT$ = "ATTACK AT DAWN": PRINT "PLAIN TEXT: ";PT$ 230 DEF FN MOD(A) = A - INT (A / 26) * 26 300 REM ENCODING 310 K = 1 320 FOR I = 1 TO LEN (PT$) 330 IF ASC ( MID$ (PT$,I,1)) < 65 OR ASC ( MID$ (PT$,I,1)) > 90 THEN NEXT I 340 TV = ASC ( MID$ (PT$,I,1)) - 65 350 KV = ASC ( MID$ (K$,K,1)) - 65 360 CT$ = CT$ + CHR$ ( FN MOD(TV + KV) + 65) 370 K = K + 1: IF K > LEN (K$) THEN K = 1 380 NEXT I 390 PRINT "CIPHER TEXT: ";CT$ 400 REM DECODING 410 K = 1 420 FOR I = 1 TO LEN (CT$) 430 TV = ASC ( MID$ (CT$,I,1)) - 65 440 KV = ASC ( MID$ (K$,K,1)) - 65 450 T = TV - KV: IF T < 0 THEN T = T + 26 460 DT$ = DT$ + CHR$ (T + 65) 470 K = K + 1: IF K > LEN (K$) THEN K = 1 480 NEXT I 490 PRINT "DECRYPTED TEXT: ";DT$
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
#Arturo
Arturo
Letters: append `A`..`Z` `a`..`z` encrypt: function [msg, key][ pos: 0 result: new "" loop msg 'c -> if in? c Letters [ 'result ++ to :char (((to :integer key\[pos]) + to :integer upper c) % 26) + to :integer `A` pos: (pos + 1) % size key ] return result ]   decrypt: function [msg, key][ pos: 0 result: new "" loop msg 'c [ 'result ++ to :char ((26 + (to :integer c) - to :integer key\[pos]) % 26) + to :integer `A` pos: (pos + 1) % size key ] return result ]   text: "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!" key: "VIGENERECIPHER"   encr: encrypt text key decr: decrypt encr key   print text print encr print 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.
#Clojure
Clojure
(use 'vijual)   (draw-tree [[:A] [:B] [:C [:D [:E] [:F]] [:G]]])  
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).
#Lasso
Lasso
local(matchingfilenames = array)   dir('.') -> foreach => {#1 >> 'string' ? #matchingfilenames -> insert(#1)}   #matchingfilenames
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).
#Lingo
Lingo
-- Usage: printFiles("C:\scripts", ".ls") on printFiles (dir, fileType) i = 1 sub = fileType.length -1 repeat while TRUE fn = getNthFileNameInFolder(dir, i) if fn = EMPTY then exit repeat i = i+1 if fn.length<fileType.length then next repeat if fn.char[fn.length-sub..fn.length]=fileType then put fn end repeat end
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 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 HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK Letter frequencies for English can be found here. Specifics for this task: Take only the ciphertext as input. You can assume it's all capitalized and has no punctuation, but it might have whitespace. Assume the plaintext is written in English. Find and output the key. Use that key to decrypt and output the original plaintext. Maintaining the whitespace from the ciphertext is optional. The algorithm doesn't have to be perfect (which may not be possible) but it should work when given enough ciphertext. The example above is fairly long, and should be plenty for any algorithm.
#Julia
Julia
# ciphertext block {{{1 const ciphertext = filter(isalpha, """ 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 HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK """) # }}}   # character frequencies {{{1 const letters = Dict{Char, Float32}( 'E' => 12.702, 'T' => 9.056, 'A' => 8.167, 'O' => 7.507, 'I' => 6.966, 'N' => 6.749, 'S' => 6.327, 'H' => 6.094, 'R' => 5.987, 'D' => 4.253, 'L' => 4.025, 'C' => 2.782, 'U' => 2.758, 'M' => 2.406, 'W' => 2.361, 'F' => 2.228, 'G' => 2.015, 'Y' => 1.974, 'P' => 1.929, 'B' => 1.492, 'V' => 0.978, 'K' => 0.772, 'J' => 0.153, 'X' => 0.150, 'Q' => 0.095, 'Z' => 0.074) const digraphs = Dict{AbstractString, Float32}( "TH" => 15.2, "HE" => 12.8, "IN" => 9.4, "ER" => 9.4, "AN" => 8.2, "RE" => 6.8, "ND" => 6.3, "AT" => 5.9, "ON" => 5.7, "NT" => 5.6, "HA" => 5.6, "ES" => 5.6, "ST" => 5.5, "EN" => 5.5, "ED" => 5.3, "TO" => 5.2, "IT" => 5.0, "OU" => 5.0, "EA" => 4.7, "HI" => 4.6, "IS" => 4.6, "OR" => 4.3, "TI" => 3.4, "AS" => 3.3, "TE" => 2.7, "ET" => 1.9, "NG" => 1.8, "OF" => 1.6, "AL" => 0.9, "DE" => 0.9, "SE" => 0.8, "LE" => 0.8, "SA" => 0.6, "SI" => 0.5, "AR" => 0.4, "VE" => 0.4, "RA" => 0.4, "LD" => 0.2, "UR" => 0.2) const trigraphs = Dict{AbstractString, Float32}( "THE" => 18.1, "AND" => 7.3, "ING" => 7.2, "ION" => 4.2, "ENT" => 4.2, "HER" => 3.6, "FOR" => 3.4, "THA" => 3.3, "NTH" => 3.3, "INT" => 3.2, "TIO" => 3.1, "ERE" => 3.1, "TER" => 3.0, "EST" => 2.8, "ERS" => 2.8, "HAT" => 2.6, "ATI" => 2.6, "ATE" => 2.5, "ALL" => 2.5, "VER" => 2.4, "HIS" => 2.4, "HES" => 2.4, "ETH" => 2.4, "OFT" => 2.2, "STH" => 2.1, "RES" => 2.1, "OTH" => 2.1, "ITH" => 2.1, "FTH" => 2.1, "ONT" => 2.0) # 1}}}   function decrypt(enc::ASCIIString, key::ASCIIString) const enclen = length(enc) const keylen = length(key)   if keylen < enclen key = (key^(div(enclen - keylen, keylen) + 2))[1:enclen] end   msg = Array(Char, enclen)   for i=1:enclen msg[i] = Char((Int(enc[i]) - Int(key[i]) + 26) % 26 + 65) end   msg::Array{Char, 1} end   function cryptanalyze(enc::ASCIIString; maxkeylen::Integer = 20) const enclen = length(enc) maxkey = "" maxdec = "" maxscore = 0.0   for keylen=1:maxkeylen key = Array(Char, keylen) idx = filter(x -> x % keylen == 0, 1:enclen) - keylen + 1   for i=1:keylen maxsubscore = 0.0   for j='A':'Z' subscore = 0.0   for k in decrypt(enc[idx], ascii(string(j))) subscore += get(letters, k, 0.0) end   if subscore > maxsubscore maxsubscore = subscore key[i] = j end end   idx += 1 end   key = join(key) const dec = decrypt(enc, key) score = 0.0   for i in dec score += get(letters, i, 0.0) end   for i=1:enclen - 2 const digraph = string(dec[i], dec[i + 1]) const trigraph = string(dec[i], dec[i + 1], dec[i + 2])   if haskey(digraphs, digraph) score += 2 * get(digraphs, digraph, 0.0) end   if haskey(trigraphs, trigraph) score += 3 * get(trigraphs, trigraph, 0.0) end end   if score > maxscore maxscore = score maxkey = key maxdec = dec end end   (maxkey, join(maxdec))::Tuple{ASCIIString, ASCIIString} end   key, dec = cryptanalyze(ciphertext) println("key: ", key, "\n\n", dec)   # post-compilation profiling run gc() t = @elapsed cryptanalyze(ciphertext) println("\nelapsed time: ", t, " seconds")
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 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 HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK Letter frequencies for English can be found here. Specifics for this task: Take only the ciphertext as input. You can assume it's all capitalized and has no punctuation, but it might have whitespace. Assume the plaintext is written in English. Find and output the key. Use that key to decrypt and output the original plaintext. Maintaining the whitespace from the ciphertext is optional. The algorithm doesn't have to be perfect (which may not be possible) but it should work when given enough ciphertext. The example above is fairly long, and should be plenty for any algorithm.
#Kotlin
Kotlin
// version 1.1.3   val 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 BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" + "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" + "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" + "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" + "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" + "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" + "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" + "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" + "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" + "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" + "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" + "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" + "FWAML ZZRXJ EKAHV FASMU LVVUT TGK"   val freq = doubleArrayOf( 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.00150, 0.01974, 0.00074 )   fun bestMatch(a: DoubleArray): Int { val sum = a.sum() var bestFit = 1e100 var bestRotate = 0 for (rotate in 0..25) { var fit = 0.0 for (i in 0..25) { val d = a[(i + rotate) % 26] / sum - freq[i] fit += d * d / freq[i] } if (fit < bestFit) { bestFit = fit bestRotate = rotate } } return bestRotate }   fun freqEveryNth(msg: IntArray, key: CharArray): Double { val len = msg.size val interval = key.size val out = DoubleArray(26) val accu = DoubleArray(26) for (j in 0 until interval) { out.fill(0.0) for (i in j until len step interval) out[msg[i]]++ val rot = bestMatch(out) key[j] = (rot + 65).toChar() for (i in 0..25) accu[i] += out[(i + rot) % 26] } val sum = accu.sum() var ret = 0.0 for (i in 0..25) { val d = accu[i] / sum - freq[i] ret += d * d / freq[i] } return ret }   fun decrypt(text: String, key: String): String { val sb = StringBuilder() var ki = 0 for (c in text) { if (c !in 'A'..'Z') continue val ci = (c.toInt() - key[ki].toInt() + 26) % 26 sb.append((ci + 65).toChar()) ki = (ki + 1) % key.length } return sb.toString() }   fun main(args: Array<String>) { val enc = encoded.replace(" ", "") val txt = IntArray(enc.length) { enc[it] - 'A' } var bestFit = 1e100 var bestKey = "" val f = "%f  %2d  %s" println(" Fit Length Key") for (j in 1..26) { val key = CharArray(j) val fit = freqEveryNth(txt, key) val sKey = key.joinToString("") print(f.format(fit, j, sKey)) if (fit < bestFit) { bestFit = fit bestKey = sKey print(" <--- best so far") } println() } println() println("Best key : $bestKey") println("\nDecrypted text:\n${decrypt(enc, bestKey)}") }
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).
#Clojure
Clojure
(use '[clojure.java.io])   (defn walk [dirpath pattern] (doall (filter #(re-matches pattern (.getName %)) (file-seq (file dirpath)))))   (map #(println (.getPath %)) (walk "src" #".*\.clj"))  
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).
#CoffeeScript
CoffeeScript
fs = require 'fs'   walk = (dir, f_match, f_visit) -> _walk = (dir) -> fns = fs.readdirSync dir for fn in fns fn = dir + '/' + fn if f_match fn f_visit fn if fs.statSync(fn).isDirectory() _walk fn _walk(dir)   dir = '..' matcher = (fn) -> fn.match /\.coffee/ action = console.log walk dir, matcher, action
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.
#Cowgol
Cowgol
include "cowgol.coh"; include "argv.coh";   # Count the amount of water in a given array sub water(towers: [uint8], length: intptr): (units: uint8) is units := 0; loop var right := towers + length; loop right := @prev right; if right < towers or [right] != 0 then break; end if; end loop; if right < towers then break; end if;   var blocks: uint8 := 0; var col := towers; while col <= right loop if [col] != 0 then [col] := [col] - 1; blocks := blocks + 1; elseif blocks != 0 then units := units + 1; end if; col := @next col; end loop; if blocks < 2 then break; end if; end loop; end sub;   # Read list from the command line and print the answer ArgvInit(); var towers: uint8[256]; var count: @indexof towers := 0; var n32: int32; loop var argmt := ArgvNext(); if argmt == 0 as [uint8] then break; end if; (n32, argmt) := AToI(argmt); towers[count] := n32 as uint8; count := count + 1; end loop;   if count == 0 then print("enter towers on command line\n"); ExitWithError(); end if;   print_i8(water(&towers[0], count as intptr)); print_nl();
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive
Verify distribution uniformity/Naive
This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) producing random integers. The number of times 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
#AutoHotkey
AutoHotkey
MsgBox, % DistCheck("dice7",10000,3)   DistCheck(function, repetitions, delta) { Loop, % 7 ; initialize array { bucket%A_Index% := 0 }   Loop, % repetitions ; populate buckets { v := %function%() bucket%v% += 1 }   lbnd := round((repetitions/7)*(100-delta)/100) ubnd := round((repetitions/7)*(100+delta)/100) text := "Distribution check:`n`nTotal elements = " repetitions . "`n`nMargin = " delta "% --> Lbound = " lbnd ", Ubound = " ubnd "`n" Loop, % 7 { text := text "`nBucket " A_Index " contains " bucket%A_Index% " elements." If bucket%A_Index% not between %lbnd% and %ubnd% text := text " Skewed." } Return, text }
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
#BBC_BASIC
BBC BASIC
MAXRND = 7 FOR r% = 2 TO 5 check% = FNdistcheck(FNdice5, 10^r%, 0.05) PRINT "Over "; 10^r% " runs dice5 "; IF check% THEN PRINT "failed distribution check with "; check% " bin(s) out of range" ELSE PRINT "passed distribution check" ENDIF NEXT END   DEF FNdistcheck(RETURN func%, repet%, delta) LOCAL i%, m%, r%, s%, bins%() DIM bins%(MAXRND) FOR i% = 1 TO repet% r% = FN(^func%) bins%(r%) += 1 IF r%>m% m% = r% NEXT FOR i% = 1 TO m% IF bins%(i%)/(repet%/m%) > 1+delta s% += 1 IF bins%(i%)/(repet%/m%) < 1-delta s% += 1 NEXT = s%   DEF FNdice5 = RND(5)
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.
#Julia
Julia
  using Images function voronoi(w, h, n_centroids) dist = (point,vector) -> sqrt.((point[1].-vector[:,1]).^2 .+ (point[2].-vector[:,2]).^2) dots = [rand(1:h, n_centroids) rand(1:w, n_centroids) rand(RGB{N0f8}, n_centroids)] img = zeros(RGB{N0f8}, h, w) for x in 1:h, y in 1:w distances = dist([x,y],dots) # distance nn = findmin(distances)[2] img[x,y] = dots[nn,:][3] end return img end img = voronoi(800, 600, 200)  
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.
#Kotlin
Kotlin
// version 1.1.3   import java.awt.Color import java.awt.Graphics import java.awt.Graphics2D import java.awt.geom.Ellipse2D import java.awt.image.BufferedImage import java.util.Random import javax.swing.JFrame   fun distSq(x1: Int, x2: Int, y1: Int, y2: Int): Int { val x = x1 - x2 val y = y1 - y2 return x * x + y * y }   class Voronoi(val cells: Int, val size: Int) : JFrame("Voronoi Diagram") { val bi: BufferedImage   init { setBounds(0, 0, size, size) defaultCloseOperation = EXIT_ON_CLOSE val r = Random() bi = BufferedImage(size, size, BufferedImage.TYPE_INT_RGB) val px = IntArray(cells) { r.nextInt(size) } val py = IntArray(cells) { r.nextInt(size) } val cl = IntArray(cells) { r.nextInt(16777215) } for (x in 0 until size) { for (y in 0 until size) { var n = 0 for (i in 0 until cells) { if (distSq(px[i], x, py[i], y) < distSq(px[n], x, py[n], y)) n = i } bi.setRGB(x, y, cl[n]) } } val g = bi.createGraphics() g.color = Color.BLACK for (i in 0 until cells) { g.fill(Ellipse2D.Double(px[i] - 2.5, py[i] - 2.5, 5.0, 5.0)) } }   override fun paint(g: Graphics) { g.drawImage(bi, 0, 0, this) } }   fun main(args: Array<String>) { Voronoi(70, 700).isVisible = true }
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
#AutoHotkey
AutoHotkey
Key = VIGENERECIPHER Text= Beware the Jabberwock, my son! The jaws that bite, the claws that catch!   out := "Input =" text "`nkey =" key "`nCiphertext =" (c := VigenereCipher(Text, Key)) "`nDecrypted =" VigenereDecipher(c, key) MsgBox % clipboard := out   VigenereCipher(Text, Key){ StringUpper, Text, Text Text := RegExReplace(Text, "[^A-Z]") Loop Parse, Text { a := Asc(A_LoopField) - Asc("A") b := Asc(SubStr(Key, 1+Mod(A_Index-1, StrLen(Key)), 1)) - Asc("A") out .= Chr(Mod(a+b,26)+Asc("A")) } return out }   VigenereDecipher(Text, key){ Loop Parse, key decoderKey .= Chr(26-(Asc(A_LoopField)-65)+65) return VigenereCipher(Text, decoderKey) }
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.
#Common_Lisp
Common Lisp
(defun visualize (tree) (labels ((rprint (list) (mapc #'princ (reverse list))) (vis-h (tree branches) (let ((len (length tree))) (loop for item in tree for idx from 1 to len do (cond ((listp item) (rprint (cdr branches)) (princ "+---+") (let ((next (cons "| " (if (= idx len) (cons " " (cdr branches)) branches)))) (terpri) (rprint (if (null item) (cdr next) next)) (terpri) (vis-h item next))) (t (rprint (cdr branches)) (princ item) (terpri) (rprint (if (= idx len) (cdr branches) branches)) (terpri))))))) (vis-h 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).
#LiveCode
LiveCode
set the defaultFolder to the documents folder -- the documents folder is a "specialFolderPath" put the files into docfiles filter docfiles with "*.txt" put docfiles
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).
#Lua
Lua
require "lfs" directorypath = "." -- current working directory for filename in lfs.dir(directorypath) do if filename:match("%.lua$") then -- "%." is an escaped ".", "$" is end of string print(filename) end end
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 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 HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK Letter frequencies for English can be found here. Specifics for this task: Take only the ciphertext as input. You can assume it's all capitalized and has no punctuation, but it might have whitespace. Assume the plaintext is written in English. Find and output the key. Use that key to decrypt and output the original plaintext. Maintaining the whitespace from the ciphertext is optional. The algorithm doesn't have to be perfect (which may not be possible) but it should work when given enough ciphertext. The example above is fairly long, and should be plenty for any algorithm.
#Nim
Nim
import sequtils, strutils, sugar, tables, times   const   CipherText = """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 HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK""".splitWhitespace.join()   FreqLetters = {'E': 12.702, 'T': 9.056, 'A': 8.167, 'O': 7.507, 'I': 6.966, 'N': 6.749, 'S': 6.327, 'H': 6.094, 'R': 5.987, 'D': 4.253, 'L': 4.025, 'C': 2.782, 'U': 2.758, 'M': 2.406, 'W': 2.361, 'F': 2.228, 'G': 2.015, 'Y': 1.974, 'P': 1.929, 'B': 1.492, 'V': 0.978, 'K': 0.772, 'J': 0.153, 'X': 0.150, 'Q': 0.095, 'Z': 0.074}.toTable   FreqDigraphs = {"TH": 15.2, "HE": 12.8, "IN": 9.4, "ER": 9.4, "AN": 8.2, "RE": 6.8, "ND": 6.3, "AT": 5.9, "ON": 5.7, "NT": 5.6, "HA": 5.6, "ES": 5.6, "ST": 5.5, "EN": 5.5, "ED": 5.3, "TO": 5.2, "IT": 5.0, "OU": 5.0, "EA": 4.7, "HI": 4.6, "IS": 4.6, "OR": 4.3, "TI": 3.4, "AS": 3.3, "TE": 2.7, "ET": 1.9, "NG": 1.8, "OF": 1.6, "AL": 0.9, "DE": 0.9, "SE": 0.8, "LE": 0.8, "SA": 0.6, "SI": 0.5, "AR": 0.4, "VE": 0.4, "RA": 0.4, "LD": 0.2, "UR": 0.2}.toTable   FreqTrigraphs = {"THE": 18.1, "AND": 7.3, "ING": 7.2, "ION": 4.2, "ENT": 4.2, "HER": 3.6, "FOR": 3.4, "THA": 3.3, "NTH": 3.3, "INT": 3.2, "TIO": 3.1, "ERE": 3.1, "TER": 3.0, "EST": 2.8, "ERS": 2.8, "HAT": 2.6, "ATI": 2.6, "ATE": 2.5, "ALL": 2.5, "VER": 2.4, "HIS": 2.4, "HES": 2.4, "ETH": 2.4, "OFT": 2.2, "STH": 2.1, "RES": 2.1, "OTH": 2.1, "ITH": 2.1, "FTH": 2.1, "ONT": 2.0}.toTable   func decrypt(enc, key: string): string = let encLen = enc.len let keyLen = key.len result.setLen(encLen) var k = 0 for i in 0..<encLen: result[i] = chr((ord(enc[i]) - ord(key[k]) + 26) mod 26 + ord('A')) k = (k + 1) mod keyLen   func cryptanalyze(enc: string; maxKeyLen = 20): tuple[maxKey, maxDec: string] = let encLen = enc.len var maxScore = 0.0   for keyLen in 1..maxKeyLen: var key = newString(keyLen) var idx = collect(newSeq): for i in 1..encLen: if i mod keyLen == 0: i - keyLen   for i in 0..<keyLen: var maxSubscore = 0.0 for j in 'A'..'Z': var subscore = 0.0 let encidx = idx.mapIt(enc[it]).join() for k in decrypt(encidx, $j): subscore += FreqLetters[k] if subscore > maxSubscore: maxSubscore = subscore key[i] = j for item in idx.mitems: inc item   let dec = decrypt(enc, key) var score = 0.0 for i in dec: score += FreqLetters[i]   for i in 0..(encLen - 3): let digraph = dec[i..(i+1)] let trigraph = dec[i..(i+2)] score += 2 * FreqDigraphs.getOrDefault(digraph) score += 3 * FreqTrigraphs.getOrDefault(trigraph)   if score > maxScore: maxScore = score result.maxKey = key result.maxDec = dec   let t0 = cpuTime() let (key, dec) = CipherText.cryptanalyze() echo "key: ", key, '\n' echo dec, '\n' echo "Elapsed time: ", (cpuTime() - t0).formatFloat(ffDecimal, precision = 3), " s"
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 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 HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK Letter frequencies for English can be found here. Specifics for this task: Take only the ciphertext as input. You can assume it's all capitalized and has no punctuation, but it might have whitespace. Assume the plaintext is written in English. Find and output the key. Use that key to decrypt and output the original plaintext. Maintaining the whitespace from the ciphertext is optional. The algorithm doesn't have to be perfect (which may not be possible) but it should work when given enough ciphertext. The example above is fairly long, and should be plenty for any algorithm.
#OCaml
OCaml
  (* Task : Vigenere cipher/Cryptanalysis *)   (* Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. Uses correlation factors similar to other solutions. (originally tried Friedman test, didn't produce good result)   Coded in a way that allows non-english (by passing frequencies). *)   (*** Helpers ***)   (* Implementation of Float.round to avoid v4.08 *) let round (x : float) : float = let rem = mod_float x 1. in if rem >= 0.5 then ceil x else floor x   (* A function that updates array element at a position *) let array_update (arr : 'a array) (idx : int) (update : 'a -> 'a) : unit = let curr = Array.get arr idx in Array.set arr idx (update curr)   (*** Actual task at hand ***)   (* the n'th element of array is how often the n'th letter was found *) let observe_coincidences ?(step : int = 1) ?(offset : int = 0) (text : string) : int array = let arr = Array.make 26 0 in let a_code = Char.code 'A' in String.iteri (fun idx c -> if idx mod step = offset then array_update arr (Char.code c - a_code) succ) text; arr   (* Obtain correlation factor for the observed coincidences *) let correlation_factor ?(sort : bool = true) (coincidences : int array) (freqs : float list) : float = let clist = Array.to_list coincidences in let clist = (if sort then List.sort compare clist else clist) in List.fold_left2 (fun acc c f -> acc +. (float_of_int c *. f)) 0. clist freqs   (* Translation of the test used in other Rosetta Code solutions *) let shifted_coincidences_test (freqs : float list) (text : string) : int = let sorted_freqs = List.sort compare freqs in let bestCorr = -100. in let max_keylen = String.length text / 20 in let rec helper idx (cur_len, cur_corr) (best_len, best_corr) = if cur_len = max_keylen then (* Finished testing everything *) best_len else if idx = cur_len then (* Finished testing this key length *) let (best_len, best_corr) = if cur_corr > best_corr then (cur_len, cur_corr) else (best_len, best_corr) in helper 0 (cur_len + 1, ~-.0.5 *. float_of_int (cur_len + 1)) (best_len, best_corr) else let coincidences = observe_coincidences ~step:cur_len ~offset:idx text in let factor = correlation_factor coincidences sorted_freqs in helper (succ idx) (cur_len, cur_corr +. factor) (best_len, best_corr) in helper 0 (2, ~-.1.) (1, ~-.100.)   (* Returns the most likely shift value for this set *) let break_caesar ?(step : int = 1) ?(offset : int = 0) (text : string) (freqs : float list) : int = let c_arr = observe_coincidences ~step ~offset text in let rec helper l curShift (maxShift, maxCorr) = if curShift = 26 then maxShift else let corr = correlation_factor ~sort:false c_arr l in let l' = List.tl l @ [List.hd l] in if corr > maxCorr then helper l' (curShift + 1) (curShift, corr) else helper l' (curShift + 1) (maxShift, maxCorr) in helper freqs 0 (-1, -100.)   let break (keylen : int) (text : string) (freqs : float list) : key = let rec getCaesars idx acc = if idx >= keylen then acc else let shift = break_caesar ~step:keylen ~offset:idx text freqs in let new_code = if shift = 0 then Char.code 'A' else Char.code 'Z' + 1 - shift in getCaesars (succ idx) (acc ^ Char.(new_code |> chr |> escaped)) in getCaesars 0 ""   let cryptanalyze (freqs : float list) (text : string) : key * string = let text = ascii_upper_letters_only text in let keylen = shifted_coincidences_test freqs text in let key = break keylen text freqs in let pt = decrypt key text in (key, pt)   (*** Output ***)   let _ = let long_text = "\ 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 HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ \ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS \ JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT \ LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST \ MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH \ QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV \ RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW \ TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO \ SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR \ ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX \ BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB \ BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA \ FWAML ZZRXJ EKAHV FASMU LVVUT TGK" in let english_freqs = [ 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.00150; 0.01974; 0.00074 ] in let (key, pt) = cryptanalyze english_freqs long_text in Printf.printf "Key:  %s\n\nText: %s" key pt ;;  
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).
#Common_Lisp
Common Lisp
(ql:quickload :cl-fad) (defun mapc-directory-tree (fn directory &key (depth-first-p t)) (dolist (entry (cl-fad:list-directory directory)) (unless depth-first-p (funcall fn entry)) (when (cl-fad:directory-pathname-p entry) (mapc-directory-tree fn entry)) (when depth-first-p (funcall fn entry))))  
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).
#D
D
void main() { import std.stdio, std.file;   // Recursive breadth-first scan (use SpanMode.depth for // a depth-first scan): dirEntries("", "*.d", SpanMode.breadth).writeln; }