task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Water_collected_between_towers
Water collected between towers
Task In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, completely filling all convex enclosures in the chart with water. 9 ██ 9 ██ 8 ██ 8 ██ 7 ██ ██ 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.
#D
D
import std.stdio;   void main() { int i = 1; int[][] tba = [ [ 1, 5, 3, 7, 2 ], [ 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 ], [ 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 ], [ 5, 5, 5, 5 ], [ 5, 6, 7, 8 ], [ 8, 7, 7, 6 ], [ 6, 7, 10, 7, 6 ] ];   foreach (tea; tba) { int rht, wu, bof; do { for (rht = tea.length - 1; rht >= 0; rht--) { if (tea[rht] > 0) { break; } }   if (rht < 0) { break; }   bof = 0; for (int col = 0; col <= rht; col++) { if (tea[col] > 0) { tea[col] -= 1; bof += 1; } else if (bof > 0) { wu++; } } if (bof < 2) { break; } } while (true);   write("Block ", i++); if (wu == 0) { write(" does not hold any"); } else { write(" holds ", wu); } writeln(" water units."); } }
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
#C
C
#include <stdlib.h> #include <stdio.h> #include <math.h>   inline int rand5() { int r, rand_max = RAND_MAX - (RAND_MAX % 5); while ((r = rand()) >= rand_max); return r / (rand_max / 5) + 1; }   inline int rand5_7() { int r; while ((r = rand5() * 5 + rand5()) >= 27); return r / 3 - 1; }   /* assumes gen() returns a value from 1 to n */ int check(int (*gen)(), int n, int cnt, double delta) /* delta is relative */ { int i = cnt, *bins = calloc(sizeof(int), n); double ratio; while (i--) bins[gen() - 1]++; for (i = 0; i < n; i++) { ratio = bins[i] * n / (double)cnt - 1; if (ratio > -delta && ratio < delta) continue;   printf("bin %d out of range: %d (%g%% vs %g%%), ", i + 1, bins[i], ratio * 100, delta * 100); break; } free(bins); return i == n; }   int main() { int cnt = 1; while ((cnt *= 10) <= 1000000) { printf("Count = %d: ", cnt); printf(check(rand5_7, 7, cnt, 0.03) ? "flat\n" : "NOT flat\n"); }   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.
#Liberty_BASIC
Liberty BASIC
  WindowWidth =600 WindowHeight =600   sites = 100 xEdge = 400 yEdge = 400 graphicbox #w.gb1, 10, 10, xEdge, yEdge   open "Voronoi neighbourhoods" for window as #w   #w "trapclose quit" #w.gb1 "down ; fill black ; size 4" #w.gb1 "font courier_new 12"   dim townX( sites), townY( sites), col$( sites)   for i =1 to sites townX( i) =int( xEdge *rnd( 1)) townY( i) =int( yEdge *rnd( 1)) col$( i) = int( 256 *rnd( 1)); " "; int( 256 *rnd( 1)); " "; int( 256 *rnd( 1)) #w.gb1 "color "; col$( i) #w.gb1 "set "; townX( i); " "; townY( i) next i   #w.gb1 "size 1"   dim nearestIndex(xEdge, yEdge) dim dist(xEdge, yEdge)   start = time$("ms")   'fill distance table with distances from the first site for x = 0 to xEdge - 1 for y = 0 to yEdge - 1 dist(x, y) = (townX(1) - x) ^ 2 + (townY(1) - y) ^ 2 nearestIndex(x, y) = 1 next y next x   #w.gb1 "color darkblue" 'for other towns for i = 2 to sites 'display some progress #w.gb1 "place 0 20" #w.gb1 "\computing: "; using("###.#", i / sites * 100); "%" 'look left for x = townX(i) to 0 step -1 if not(checkRow(i, x,0, yEdge - 1)) then exit for next x 'look right for x = townX(i) + 1 to xEdge - 1 if not(checkRow(i, x, 0, yEdge - 1)) then exit for next x scan next i   for x = 0 to xEdge - 1 for y =0 to yEdge - 1 #w.gb1 "color "; col$(nearestIndex(x, y)) startY = y nearest = nearestIndex(x, y) for y = y + 1 to yEdge if nearestIndex(x, y) <> nearest then y = y - 1 : exit for next y #w.gb1 "line "; x; " "; startY; " "; x; " "; y + 1 next y next x   #w.gb1 "color black; size 4" for i =1 to sites #w.gb1 "set "; townX( i); " "; townY( i) next i print time$("ms") - start wait   sub quit w$ close #w$ end end sub   function checkRow(site, x, startY, endY) dxSquared = (townX(site) - x) ^ 2 for y = startY to endY dSquared = (townY(site) - y) ^ 2 + dxSquared if dSquared <= dist(x, y) then dist(x, y) = dSquared nearestIndex(x, y) = site checkRow = 1 end if next y end function  
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
#BASIC256
BASIC256
  function Filtrar(cadorigen) filtrado = "" for i = 1 to length(cadorigen) letra = upper(mid(cadorigen, i, 1)) if instr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", letra) then filtrado += letra next i return filtrado end function   function Encriptar(texto, llave) texto = Filtrar(texto) cifrado = "" j = 1 for i = 1 to length(texto) mSS = mid(texto, i, 1) m = asc(mSS) - asc("A") kSS = mid(llave, j, 1) k = asc(kSS) - asc("A") j = (j mod length(llave)) + 1 c = (m + k) mod 26 letra = chr(asc("A") + c) cifrado += letra next i return cifrado end function   function DesEncriptar(texto, llave) descifrado = "" j = 1 for i = 1 to length(texto) mSS = mid(texto, i, 1) m = asc(mSS) - asc("A") kSS = mid(llave, j, 1) k = asc(kSS) - asc("A") j = (j mod length(llave)) + 1 c = (m - k + 26) mod 26 letra = chr(asc("A")+c) descifrado += letra next i return descifrado end function   llave = Filtrar("vigenerecipher") cadorigen = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!" print cadorigen print llave   cadcifrada = Encriptar(cadorigen, llave) print " Cifrado: "; cadcifrada print "Descifrado: "; DesEncriptar(cadcifrada, llave) 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.
#D
D
import std.stdio, std.conv, std.algorithm, std.array;   struct Node(T) { T value; Node* left, right; }   string[] treeIndent(T)(in Node!T* t) pure nothrow @safe { if (!t) return ["-- (null)"]; const tr = t.right.treeIndent; return "--" ~ t.value.text ~ t.left.treeIndent.map!q{" |" ~ a}.array ~ (" `" ~ tr[0]) ~ tr[1 .. $].map!q{" " ~ a}.array; }   void main () { static N(T)(T v, Node!T* l=null, Node!T* r=null) { return new Node!T(v, l, r); }   const tree = N(1, N(2, N(4, N(7)), N(5)), N(3, N(6, N(8), N(9)))); writefln("%-(%s\n%)", tree.treeIndent); }
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).
#M2000_Interpreter
M2000 Interpreter
  Module Show_Files_Standard { \\ we get more (include hidden too) Module InnerWay (folder_path$, pattern$){ olddir$=dir$ dir folder_path$ \\ clear menu list Menu \\ + place export to menu, without showing \\ ! sort to name files ! + pattern$ If MenuItems>0 then { For i=1 to MenuItems { Print Menu$(i)+".exe" } } dir olddir$ } InnerWay "C:\Windows","*.exe" } Show_Files_Standard  
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).
#MACRO-10
MACRO-10
  TITLE DIRWLK - Directory Walker SUBTTL PDP-10 Assembly Language (MACRO-10 @ TOPS-20). KJX 2022.   SEARCH MONSYM,MACSYM  ;Get system-call names. .REQUIRE SYS:MACREL  ;Macros: TMSG, EJSHLT, etc.   STDAC.  ;Define standard register names.   JFN: BLOCK 1  ;Space for JFN (file-handle) FSPEC: BLOCK 20  ;Space for file specification. FSPECL= <.-FSPEC>*5  ;Length in chars of file-spec.   GO:: RESET%  ;Initialize process. TMSG <Please enter filespec, wildcards are allowed: > HRROI T1,FSPEC  ;Read into FSPEC. MOVEI T2,FSPECL  ;Maximum allowed characters. SETZ T3,  ;No Ctrl-R prompting. RDTTY%  ;Read string from terminal. EJSHLT  ; Print error-msg on errors.   MOVX T1,GJ%OLD!GJ%IFG!GJ%FLG!GJ%SHT  ;Various flags. HRROI T2,FSPEC  ;File specification from above. GTJFN%  ;Get JFN for first matching file. EJSHLT  ; Print error-msg on errors. MOVEM T1,JFN  ;Save JFN.   DO. MOVEI T1,.PRIOU  ;Write to standard-output. HRRZ T2,JFN  ;JFN from above to decode. SETZ T3,  ;No flags. JFNS%  ;Decode filename and print it. EJSHLT  ; Print error-msg on errors. TMSG < >  ;Print newline. MOVE T1,JFN  ;Get JFN into T1. GNJFN%  ;Get next matching file. JRST [ HALTF%  ; Halt program on failure. JRST GO ] LOOP.  ;No error: Do it again. ENDDO.   END GO  
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.
#Perl
Perl
use strict; use warnings; use feature 'say';   # from Wikipedia my %English_letter_freq = ( E => 12.70, L => 4.03, Y => 1.97, P => 1.93, T => 9.06, A => 8.17, O => 7.51, I => 6.97, N => 6.75, S => 6.33, H => 6.09, R => 5.99, D => 4.25, C => 2.78, U => 2.76, M => 2.41, W => 2.36, F => 2.23, G => 2.02, B => 1.29, V => 0.98, K => 0.77, J => 0.15, X => 0.15, Q => 0.10, Z => 0.07 ); my @alphabet = sort keys %English_letter_freq; my $max_key_lengths = 5; # number of keylengths to try   sub myguess { my ($text) = (@_); my ($seqtext, @spacing, @factors, @sortedfactors, $pos, %freq, %Keys);   # Kasiski examination $seqtext = $text; while ($seqtext =~ /(...).*\1/) { $seqtext = substr($seqtext, 1+index($seqtext, $1)); push @spacing, 1 + index($seqtext, $1); }   for my $j (@spacing) { push @factors, grep { $j % $_ == 0 } 2..$j; } $freq{$_}++ for @factors; @sortedfactors = grep { $_ >= 4 } sort { $freq{$b} <=> $freq{$a} } keys %freq; # discard very short keys   for my $keylen ( @sortedfactors[0..$max_key_lengths-1] ) { my $keyguess = ''; for (my $i = 0; $i < $keylen; $i++) { my($mykey, %chi_values, $bestguess); for (my $j = 0; $j < length($text); $j += $keylen) { $mykey .= substr($text, ($j+$i) % length($text), 1); }   for my $subkey (@alphabet) { my $decrypted = mycrypt($mykey, $subkey); my $length = length($decrypted); for my $char (@alphabet) { my $expected = $English_letter_freq{$char} * $length / 100; my $observed; ++$observed while $decrypted =~ /$char/g; $chi_values{$subkey} += ($observed - $expected)**2 / $expected if $observed; } }   $Keys{$keylen}{score} = $chi_values{'A'}; for my $sk (sort keys %chi_values) { if ($chi_values{$sk} <= $Keys{$keylen}{score}) { $bestguess = $sk; $Keys{$keylen}{score} = $chi_values{$sk}; } } $keyguess .= $bestguess; } $Keys{$keylen}{key} = $keyguess; } map { $Keys{$_}{key} } sort { $Keys{$a}{score} <=> $Keys{$b}{score}} keys %Keys; }   sub mycrypt { my ($text, $key) = @_; my ($new_text, %values_numbers);   my $keylen = length($key); @values_numbers{@alphabet} = 0..25; my %values_letters = reverse %values_numbers;   for (my $i = 0; $i < length($text); $i++) { my $val = -1 * $values_numbers{substr( $key, $i%$keylen, 1)} # negative shift for decode + $values_numbers{substr($text, $i, 1)}; $new_text .= $values_letters{ $val % 26 }; } return $new_text; }   my $cipher_text = <<~'EOD'; 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 EOD   my $text = uc($cipher_text) =~ s/[^@{[join '', @alphabet]}]//gr;   for my $key ( myguess($text) ) { say "Key $key\n" . "Key length " . length($key) . "\n" . "Plaintext " . substr(mycrypt($text, $key), 0, 80) . "...\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).
#Delphi
Delphi
  program Walk_a_directory;   {$APPTYPE CONSOLE} {$R *.res}   uses System.IOUtils;   var Files: TArray<string>; FileName, Directory: string;   begin Directory := TDirectory.GetCurrentDirectory; // dir = '.', work to Files := TDirectory.GetFiles(Directory, '*.*', TSearchOption.soAllDirectories);   for FileName in Files do begin Writeln(FileName); end;   Readln; end.    
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   (read a single directory).
#E
E
def walkTree(directory, pattern) { for name => file in directory { if (name =~ rx`.*$pattern.*`) { println(file.getPath()) } if (file.isDirectory()) { walkTree(file, pattern) } } }
http://rosettacode.org/wiki/Water_collected_between_towers
Water collected between towers
Task In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, completely filling all convex enclosures in the chart with water. 9 ██ 9 ██ 8 ██ 8 ██ 7 ██ ██ 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.
#Erlang
Erlang
  -module(watertowers). -export([towers/1, demo/0]).   towers(List) -> element(2, tower(List, 0)).   tower([], _) -> {0,0}; tower([H|T], MaxLPrev) -> MaxL = max(MaxLPrev, H), {MaxR, WaterAcc} = tower(T, MaxL), {max(MaxR,H), WaterAcc+max(0, min(MaxR,MaxL)-H)}.   demo() -> Cases = [[1, 5, 3, 7, 2], [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]], [io:format("~p -> ~p~n", [Case, towers(Case)]) || Case <- Cases], ok.  
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
#C.2B.2B
C++
#include <map> #include <iostream> #include <cmath>   template<typename F> bool test_distribution(F f, int calls, double delta) { typedef std::map<int, int> distmap; distmap dist;   for (int i = 0; i < calls; ++i) ++dist[f()];   double mean = 1.0/dist.size();   bool good = true;   for (distmap::iterator i = dist.begin(); i != dist.end(); ++i) { if (std::abs((1.0 * i->second)/calls - mean) > delta) { std::cout << "Relative frequency " << i->second/(1.0*calls) << " of result " << i->first << " deviates by more than " << delta << " from the expected value " << mean << "\n"; good = false; } }   return good; }
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
#Clojure
Clojure
(defn verify [rand n & [delta]] (let [rands (frequencies (repeatedly n rand)) avg (/ (reduce + (map val rands)) (count rands)) max-delta (* avg (or delta 1/10)) acceptable? #(<= (- avg max-delta) % (+ avg max-delta))] (for [[num count] (sort rands)] [num count (acceptable? count)])))   (doseq [n [100 1000 10000] [num count okay?] (verify #(rand-int 7) n)] (println "Saw" num count "times:" (if okay? "that's" " not") "acceptable"))
http://rosettacode.org/wiki/Voronoi_diagram
Voronoi diagram
A Voronoi diagram is a diagram consisting of a number of sites. Each Voronoi site s also has a Voronoi cell consisting of all points closest to s. Task Demonstrate how to generate and display a Voroni diagram. See algo K-means++ clustering.
#Lua
Lua
  function love.load( ) love.math.setRandomSeed( os.time( ) ) --set the random seed keys = { } --an empty table where we will store key presses number_cells = 50 --the number of cells we want in our diagram --draw the voronoi diagram to a canvas voronoiDiagram = generateVoronoi( love.graphics.getWidth( ), love.graphics.getHeight( ), number_cells ) end   function hypot( x, y ) return math.sqrt( x*x + y*y ) end   function generateVoronoi( width, height, num_cells ) canvas = love.graphics.newCanvas( width, height ) local imgx = canvas:getWidth( ) local imgy = canvas:getHeight( ) local nx = { } local ny = { } local nr = { } local ng = { } local nb = { } for a = 1, num_cells do table.insert( nx, love.math.random( 0, imgx ) ) table.insert( ny, love.math.random( 0, imgy ) ) table.insert( nr, love.math.random( 0, 1 ) ) table.insert( ng, love.math.random( 0, 1 ) ) table.insert( nb, love.math.random( 0, 1 ) ) end love.graphics.setColor( { 1, 1, 1 } ) love.graphics.setCanvas( canvas ) for y = 1, imgy do for x = 1, imgx do dmin = hypot( imgx-1, imgy-1 ) j = -1 for i = 1, num_cells do d = hypot( nx[i]-x, ny[i]-y ) if d < dmin then dmin = d j = i end end love.graphics.setColor( { nr[j], ng[j], nb[j] } ) love.graphics.points( x, y ) end end --reset color love.graphics.setColor( { 1, 1, 1 } ) --draw points for b = 1, num_cells do love.graphics.points( nx[b], ny[b] ) end love.graphics.setCanvas( ) return canvas end   --RENDER function love.draw( ) --reset color love.graphics.setColor( { 1, 1, 1 } ) --draw diagram love.graphics.draw( voronoiDiagram ) --draw drop shadow text love.graphics.setColor( { 0, 0, 0 } ) love.graphics.print( "space: regenerate\nesc: quit", 1, 1 ) --draw text love.graphics.setColor( { 0.7, 0.7, 0 } ) love.graphics.print( "space: regenerate\nesc: quit" ) end   --CONTROL function love.keyreleased( key ) if key == 'space' then voronoiDiagram = generateVoronoi( love.graphics.getWidth( ), love.graphics.getHeight( ), number_cells ) elseif key == 'escape' then love.event.quit( ) end end  
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at the time thought impossible with such a code. As the workings of the algorithm are clearly described in the linked Wikipedia article they will not be repeated here. Task Write routines, methods, procedures etc. in your language to generate a Verhoeff checksum digit for non-negative integers of any length and to validate the result. A combined routine is also acceptable. The more mathematically minded may prefer to generate the 3 tables required from the description provided rather than to hard-code them. Write your routines in such a way that they can optionally display digit by digit calculations as in the Wikipedia example. Use your routines to calculate check digits for the integers: 236, 12345 and 123456789012 and then validate them. Also attempt to validate the same integers if the check digits in all cases were 9 rather than what they actually are. Display digit by digit calculations for the first two integers but not for the third. Related task   Damm algorithm
#11l
11l
V MULTIPLICATION_TABLE = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], [2, 3, 4, 0, 1, 7, 8, 9, 5, 6], [3, 4, 0, 1, 2, 8, 9, 5, 6, 7], [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], [5, 9, 8, 7, 6, 0, 4, 3, 2, 1], [6, 5, 9, 8, 7, 1, 0, 4, 3, 2], [7, 6, 5, 9, 8, 2, 1, 0, 4, 3], [8, 7, 6, 5, 9, 3, 2, 1, 0, 4], [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]]   V INV = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9]   V PERMUTATION_TABLE = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 5, 7, 6, 2, 8, 3, 0, 9, 4], [5, 8, 0, 3, 7, 9, 6, 1, 4, 2], [8, 9, 1, 6, 0, 4, 3, 5, 2, 7], [9, 4, 5, 3, 1, 2, 6, 8, 7, 0], [4, 2, 8, 6, 5, 7, 3, 9, 0, 1], [2, 7, 9, 3, 8, 0, 6, 4, 1, 5], [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]]   F verhoeffchecksum(n, validate = 1B, terse = 1B, verbose = 0B) ‘ Calculate the Verhoeff checksum over `n`. Terse mode or with single argument: return True if valid (last digit is a correct check digit). If checksum mode, return the expected correct checksum digit. If validation mode, return True if last digit checks correctly. ’ I verbose print(("\n"(I validate {‘Validation’} E ‘Check digit’))‘ ’(‘calculations for ’n":\n\n i ni p[i,ni] c\n------------------")) V (c, dig) = (0, Array(String(I validate {n} E 10 * n))) L(ni) reversed(dig) V i = L.index V p = :PERMUTATION_TABLE[i % 8][Int(ni)] c = :MULTIPLICATION_TABLE[c][p] I verbose print(f:‘{i:2} {ni} {p} {c}’)   I verbose & !validate print("\ninv("c‘) = ’:INV[c]) I !terse print(I validate {"\nThe validation for '"n‘' is ’(I c == 0 {‘correct’} E ‘incorrect’)‘.’} E "\nThe check digit for '"n‘' is ’:INV[c]‘.’) R I validate {c == 0} E :INV[c]   L(n, va, t, ve) [(Int64(236), 0B, 0B, 1B), (Int64(2363), 1B, 0B, 1B), (Int64(2369), 1B, 0B, 1B), (Int64(12345), 0B, 0B, 1B), (Int64(123451), 1B, 0B, 1B), (Int64(123459), 1B, 0B, 1B), (Int64(123456789012), 0B, 0B, 0B), (Int64(1234567890120), 1B, 0B, 0B), (Int64(1234567890129), 1B, 0B, 0B)] verhoeffchecksum(n, va, t, ve)
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
#BBC_BASIC
BBC BASIC
key$ = "LEMON" plaintext$ = "ATTACK AT DAWN" ciphertext$ = FNencrypt(plaintext$, key$) PRINT "Key = """ key$ """" PRINT "Plaintext = """ plaintext$ """" PRINT "Ciphertext = """ ciphertext$ """" PRINT "Decrypted = """ FNdecrypt(ciphertext$, key$) """" END   DEF FNencrypt(plain$, key$) LOCAL i%, k%, n%, o$ plain$ = FNupper(plain$) key$ = FNupper(key$) FOR i% = 1 TO LEN(plain$) n% = ASCMID$(plain$, i%) IF n% >= 65 IF n% <= 90 THEN o$ += CHR$(65 + (n% + ASCMID$(key$, k%+1)) MOD 26) k% = (k% + 1) MOD LEN(key$) ENDIF NEXT = o$   DEF FNdecrypt(cipher$, key$) LOCAL i%, k%, n%, o$ cipher$ = FNupper(cipher$) key$ = FNupper(key$) FOR i% = 1 TO LEN(cipher$) n% = ASCMID$(cipher$, i%) o$ += CHR$(65 + (n% + 26 - ASCMID$(key$, k%+1)) MOD 26) k% = (k% + 1) MOD LEN(key$) NEXT = o$   DEF FNupper(A$) LOCAL A%,C% FOR A% = 1 TO LEN(A$) C% = ASCMID$(A$,A%) IF C% >= 97 IF C% <= 122 MID$(A$,A%,1) = CHR$(C%-32) NEXT = A$
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
#Befunge
Befunge
"VIGENERECIPHER">>>>1\:!v>"A"-\:00p0v >>!#:0#-0#1g#,*#<+:v:-1$_^#!:\+1g00p< \"{"\v>9+2*%"A"+^>$>~>:48*\`#@_::"`"` *84*`<^4+"4"+g0\_^#!+`*55\`\0::-"A"-*
http://rosettacode.org/wiki/Visualize_a_tree
Visualize a tree
A tree structure   (i.e. a rooted, connected acyclic graph)   is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as:   indented text   (à la unix tree command)   nested HTML tables   hierarchical GUI widgets   2D   or   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.
#Delphi
Delphi
  program Visualize_a_tree;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type TNode = record _label: string; children: TArray<Integer>; end;   TTree = TArray<TNode>;   TTreeHelper = record helper for TTree procedure AddNode(lb: string; chl: TArray<Integer> = []); end;   procedure Vis(t: TTree);   procedure f(n: Integer; pre: string); begin var ch := t[n].children; if Length(ch) = 0 then begin Writeln('-', t[n]._label); exit; end;   writeln('+', t[n]._label); var last := Length(ch) - 1; for var c in copy(ch, 0, last) do begin write(pre, '+-'); f(c, pre + '¦ '); end; write(pre, '+-'); f(ch[last], pre + ' '); end;   begin if Length(t) = 0 then begin writeln('<empty>'); exit; end;   f(0, ''); end;   { TTreeHelper }   procedure TTreeHelper.AddNode(lb: string; chl: TArray<Integer> = []); begin SetLength(self, Length(self) + 1); with self[High(self)] do begin _label := lb; if Length(chl) > 0 then children := copy(chl, 0, length(chl)); end; end;   var Tree: TTree;   begin Tree.AddNode('root', [1, 2, 3]); Tree.AddNode('ei', [4, 5]); Tree.AddNode('bee'); Tree.AddNode('si'); Tree.AddNode('dee'); Tree.AddNode('y', [6]); Tree.AddNode('eff');   Vis(Tree);   {$IFNDEF UNIX} readln; {$ENDIF} 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).
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
FileNames["*"] FileNames["*.png", $RootDirectory]
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. Note: Please be careful when running any code presented here. Related task   Walk Directory Tree   (read entire directory tree).
#MAXScript
MAXScript
getFiles "C:\\*.txt"
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis
Vigenère cipher/Cryptanalysis
Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text: MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS 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.
#Phix
Phix
-- -- demo\rosetta\Cryptanalysis.exw -- with javascript_semantics atom t0 = time() constant ciphertext = substitute_all(""" MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS FGRPH JOOFW 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""",{" ","\n"},{"",""}) constant letters = new_dict( {{'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}}) constant digraphs = new_dict( {{"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}}) constant trigraphs = new_dict( {{"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}}) function decrypt(string enc, string key) integer keylen = length(key), k = 1 string msg = repeat(' ', length(enc)) for i=1 to length(enc) do msg[i] = mod(enc[i]-key[k]+26,26)+'A' k = mod(k,keylen)+1 end for return msg end function function cryptanalyze(string enc, integer maxkeylen=20) integer enclen = length(enc) string maxkey = "", maxdec = "", k1 = " " atom maxscore = 0.0 for keylen=1 to maxkeylen do string key = repeat(' ',keylen) sequence idx = {} for i=1 to enclen do if mod(i,keylen)=0 then idx &= i-keylen+1 end if end for for i=1 to keylen do atom maxsubscore = 0.0 for j='A' to 'Z' do atom subscore = 0.0 k1[1] = j string encidx = "" for ii=1 to length(idx) do encidx &= enc[idx[ii]] end for string dec = decrypt(encidx,k1) for di=1 to length(dec) do subscore += getd(dec[di],letters) end for if subscore > maxsubscore then maxsubscore = subscore key[i] = j end if end for idx = sq_add(idx,1) end for string dec = decrypt(enc, key) atom score = 0.0 for i=1 to length(dec) do score += getd(dec[i],letters) end for for i=1 to enclen - 2 do string digraph = dec[i..i+1] string trigraph = dec[i..i + 2] score += 2 * getd(digraph,digraphs) score += 3 * getd(trigraph,trigraphs) end for if score > maxscore then maxscore = score maxkey = key maxdec = dec end if end for return {maxkey,maxdec} end function function fold(string s, integer w) for i=w to length(s) by w do s[i..i-1] = "\n" end for return s end function string {key, dec} = cryptanalyze(ciphertext) printf(1,"key: %s\n\n%s\n\n", {key, fold(dec,80)}) printf(1,"elapsed time: %3.2f seconds",{time()-t0}) {} = wait_key()
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).
#Elixir
Elixir
defmodule Walk_directory do def recursive(dir \\ ".") do Enum.each(File.ls!(dir), fn file -> IO.puts fname = "#{dir}/#{file}" if File.dir?(fname), do: recursive(fname) end) end end   Walk_directory.recursive
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   (read a single directory).
#Emacs_Lisp
Emacs Lisp
ELISP> (directory-files-recursively "/tmp/el" "\\.el$") ("/tmp/el/1/c.el" "/tmp/el/a.el" "/tmp/el/b.el")
http://rosettacode.org/wiki/Water_collected_between_towers
Water collected between towers
Task In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, completely filling all convex enclosures in the chart with water. 9 ██ 9 ██ 8 ██ 8 ██ 7 ██ ██ 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.
#F.23
F#
  (* A solution I'd show to Euclid !!!!. Nigel Galloway May 4th., 2017 *) let solve n = let (n,_)::(i,e)::g = n|>List.sortBy(fun n->(-(snd n))) let rec fn i g e l = match e with | (n,e)::t when n < i -> fn n g t (l+(i-n-1)*e) | (n,e)::t when n > g -> fn i n t (l+(n-g-1)*e) | (n,t)::e -> fn i g e (l-t) | _ -> l fn (min n i) (max n i) g (e*(abs(n-i)-1))  
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive
Verify distribution uniformity/Naive
This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) producing random integers. The number of times 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
#Common_Lisp
Common Lisp
(defun check-distribution (function n &optional (delta 1.0)) (let ((bins (make-hash-table))) (loop repeat n do (incf (gethash (funcall function) bins 0))) (loop with target = (/ n (hash-table-count bins)) for key being each hash-key of bins using (hash-value value) when (> (abs (- value target)) (* 0.01 delta n)) do (format t "~&Distribution potentially skewed for ~w:~ expected around ~w got ~w." key target value) finally (return bins))))
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
#D
D
import std.stdio, std.string, std.math, std.algorithm, std.traits;   /** Bin the answers to fn() and check bin counts are within +/- delta % of repeats/bincount. */ void distCheck(TF)(in TF func, in int nRepeats, in double delta) /*@safe*/ if (isCallable!TF) { int[int] counts; foreach (immutable i; 0 .. nRepeats) counts[func()]++; immutable double target = nRepeats / double(counts.length); immutable int deltaCount = cast(int)(delta / 100.0 * target);   foreach (immutable k, const count; counts) if (abs(target - count) >= deltaCount) throw new Exception(format( "distribution potentially skewed for '%s': '%d'\n", k, count));   foreach (immutable k; counts.keys.sort()) writeln(k, " ", counts[k]); writeln; }   version (verify_distribution_uniformity_naive_main) { void main() { import std.random; distCheck(() => uniform(1, 6), 1_000_000, 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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Needs["ComputationalGeometry`"] DiagramPlot[{{4.4, 14}, {6.7, 15.25}, {6.9, 12.8}, {2.1, 11.1}, {9.5, 14.9}, {13.2, 11.9}, {10.3, 12.3}, {6.8, 9.5}, {3.3, 7.7}, {0.6, 5.1}, {5.3, 2.4}, {8.45, 4.7}, {11.5, 9.6}, {13.8, 7.3}, {12.9, 3.1}, {11, 1.1}}]
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at the time thought impossible with such a code. As the workings of the algorithm are clearly described in the linked Wikipedia article they will not be repeated here. Task Write routines, methods, procedures etc. in your language to generate a Verhoeff checksum digit for non-negative integers of any length and to validate the result. A combined routine is also acceptable. The more mathematically minded may prefer to generate the 3 tables required from the description provided rather than to hard-code them. Write your routines in such a way that they can optionally display digit by digit calculations as in the Wikipedia example. Use your routines to calculate check digits for the integers: 236, 12345 and 123456789012 and then validate them. Also attempt to validate the same integers if the check digits in all cases were 9 rather than what they actually are. Display digit by digit calculations for the first two integers but not for the third. Related task   Damm algorithm
#C
C
#include <assert.h> #include <stdbool.h> #include <stdio.h> #include <string.h>   static const int d[][10] = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, 1, 0, 4, 3}, {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, };   static const int inv[] = {0, 4, 3, 2, 1, 5, 6, 7, 8, 9};   static const int p[][10] = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8}, };   int verhoeff(const char* s, bool validate, bool verbose) { if (verbose) { const char* t = validate ? "Validation" : "Check digit"; printf("%s calculations for '%s':\n\n", t, s); puts(u8" i n\xE1\xB5\xA2 p[i,n\xE1\xB5\xA2] c"); puts("------------------"); } int len = strlen(s); if (validate) --len; int c = 0; for (int i = len; i >= 0; --i) { int ni = (i == len && !validate) ? 0 : s[i] - '0'; assert(ni >= 0 && ni < 10); int pi = p[(len - i) % 8][ni]; c = d[c][pi]; if (verbose) printf("%2d  %d  %d  %d\n", len - i, ni, pi, c); } if (verbose && !validate) printf("\ninv[%d] = %d\n", c, inv[c]); return validate ? c == 0 : inv[c]; }   int main() { const char* ss[3] = {"236", "12345", "123456789012"}; for (int i = 0; i < 3; ++i) { const char* s = ss[i]; bool verbose = i < 2; int c = verhoeff(s, false, verbose); printf("\nThe check digit for '%s' is '%d'.\n", s, c); int len = strlen(s); char sc[len + 2]; strncpy(sc, s, len + 2); for (int j = 0; j < 2; ++j) { sc[len] = (j == 0) ? c + '0' : '9'; int v = verhoeff(sc, true, verbose); printf("\nThe validation for '%s' is %s.\n", sc, v ? "correct" : "incorrect"); } } return 0; }
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
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <ctype.h> #include <getopt.h>   #define NUMLETTERS 26 #define BUFSIZE 4096   char *get_input(void);   int main(int argc, char *argv[]) { char const usage[] = "Usage: vinigere [-d] key"; char sign = 1; char const plainmsg[] = "Plain text: "; char const cryptmsg[] = "Cipher text: "; bool encrypt = true; int opt;   while ((opt = getopt(argc, argv, "d")) != -1) { switch (opt) { case 'd': sign = -1; encrypt = false; break; default: fprintf(stderr, "Unrecogized command line argument:'-%i'\n", opt); fprintf(stderr, "\n%s\n", usage); return 1; } }   if (argc - optind != 1) { fprintf(stderr, "%s requires one argument and one only\n", argv[0]); fprintf(stderr, "\n%s\n", usage); return 1; }     // Convert argument into array of shifts char const *const restrict key = argv[optind]; size_t const keylen = strlen(key); char shifts[keylen];   char const *restrict plaintext = NULL; for (size_t i = 0; i < keylen; i++) { if (!(isalpha(key[i]))) { fprintf(stderr, "Invalid key\n"); return 2; } char const charcase = (isupper(key[i])) ? 'A' : 'a'; // If decrypting, shifts will be negative. // This line would turn "bacon" into {1, 0, 2, 14, 13} shifts[i] = (key[i] - charcase) * sign; }   do { fflush(stdout); // Print "Plain text: " if encrypting and "Cipher text: " if // decrypting printf("%s", (encrypt) ? plainmsg : cryptmsg); plaintext = get_input(); if (plaintext == NULL) { fprintf(stderr, "Error getting input\n"); return 4; } } while (strcmp(plaintext, "") == 0); // Reprompt if entry is empty   size_t const plainlen = strlen(plaintext);   char* const restrict ciphertext = calloc(plainlen + 1, sizeof *ciphertext); if (ciphertext == NULL) { fprintf(stderr, "Memory error\n"); return 5; }   for (size_t i = 0, j = 0; i < plainlen; i++) { // Skip non-alphabetical characters if (!(isalpha(plaintext[i]))) { ciphertext[i] = plaintext[i]; continue; } // Check case char const charcase = (isupper(plaintext[i])) ? 'A' : 'a'; // Wrapping conversion algorithm ciphertext[i] = ((plaintext[i] + shifts[j] - charcase + NUMLETTERS) % NUMLETTERS) + charcase; j = (j+1) % keylen; } ciphertext[plainlen] = '\0'; printf("%s%s\n", (encrypt) ? cryptmsg : plainmsg, ciphertext);   free(ciphertext); // Silence warnings about const not being maintained in cast to void* free((char*) plaintext); return 0; } char *get_input(void) {   char *const restrict buf = malloc(BUFSIZE * sizeof (char)); if (buf == NULL) { return NULL; }   fgets(buf, BUFSIZE, stdin);   // Get rid of newline size_t const len = strlen(buf); if (buf[len - 1] == '\n') buf[len - 1] = '\0';   return buf; }
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.
#Elena
Elena
import system'routines; import extensions;   class Node { string theValue; Node[] theChildren;   constructor new(string value, Node[] children) { theValue := value;   theChildren := children; }   constructor new(string value) <= new(value, new Node[](0));   constructor new(Node[] children) <= new(emptyString, children);   get() = theValue;   Children = theChildren; }   extension treeOp { writeTree(node, prefix) { var children := node.Children; var length := children.Length;   children.zipForEach(new Range(1, length), (child,index) { self.printLine(prefix,"|"); self.printLine(prefix,"+---",child.get());   var nodeLine := prefix + (index==length).iif(" ","| ");   self.writeTree(child,nodeLine); });   ^ self }   writeTree(node) = self.writeTree(node,""); }   public program() { var tree := Node.new( new Node[]{ Node.new("a", new Node[] { Node.new("b", new Node[]{Node.new("c")}), Node.new("d") }), Node.new("e") });   console.writeTree(tree).readChar() }
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.
#Erlang
Erlang
9> io:fwrite("~1p", [{1, 2, {30, 40}, {{500, 600}, 70}}]). {1, 2, {30, 40}, {{500, 600}, 70}}
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. Note: Please be careful when running any code presented here. Related task   Walk Directory Tree   (read entire directory tree).
#Nanoquery
Nanoquery
import Nanoquery.IO   for fname in new(File).listDir("/foo/bar") if lower(new(File, fname).getExtension()) = ".mp3" println filename end end
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. Note: Please be careful when running any code presented here. Related task   Walk Directory Tree   (read entire directory tree).
#Nemerle
Nemerle
using System.Console; using System.IO;   module DirWalk { Main() : void { def files = Directory.GetFiles(@"C:\MyDir"); // retrieves only files def files_subs = Directory.GetFileSystemEntries(@"C:\MyDir"); // also retrieves (but does not enter) sub-directories // (like ls command) foreach (file in files) WriteLine(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.
#Python
Python
from string import uppercase from operator import itemgetter   def vigenere_decrypt(target_freqs, input): nchars = len(uppercase) ordA = ord('A') sorted_targets = sorted(target_freqs)   def frequency(input): result = [[c, 0.0] for c in uppercase] for c in input: result[c - ordA][1] += 1 return result   def correlation(input): result = 0.0 freq = frequency(input) freq.sort(key=itemgetter(1))   for i, f in enumerate(freq): result += f[1] * sorted_targets[i] return result   cleaned = [ord(c) for c in input.upper() if c.isupper()] best_len = 0 best_corr = -100.0   # Assume that if there are less than 20 characters # per column, the key's too long to guess for i in xrange(2, len(cleaned) // 20): pieces = [[] for _ in xrange(i)] for j, c in enumerate(cleaned): pieces[j % i].append(c)   # The correlation seems to increase for smaller # pieces/longer keys, so weigh against them a little corr = -0.5 * i + sum(correlation(p) for p in pieces)   if corr > best_corr: best_len = i best_corr = corr   if best_len == 0: return ("Text is too short to analyze", "")   pieces = [[] for _ in xrange(best_len)] for i, c in enumerate(cleaned): pieces[i % best_len].append(c)   freqs = [frequency(p) for p in pieces]   key = "" for fr in freqs: fr.sort(key=itemgetter(1), reverse=True)   m = 0 max_corr = 0.0 for j in xrange(nchars): corr = 0.0 c = ordA + j for frc in fr: d = (ord(frc[0]) - c + nchars) % nchars corr += frc[1] * target_freqs[d]   if corr > max_corr: m = j max_corr = corr   key += chr(m + ordA)   r = (chr((c - ord(key[i % best_len]) + nchars) % nchars + ordA) for i, c in enumerate(cleaned)) return (key, "".join(r))     def main(): 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"""   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]   (key, decoded) = vigenere_decrypt(english_frequences, encoded) print "Key:", key print "\nText:", decoded   main()
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).
#Erlang
Erlang
  walk_dir(Path, Pattern) -> filelib:fold_files( Path, Pattern, true, % Recurse fun(File, Accumulator) -> [File|Accumulator] end, [] )  
http://rosettacode.org/wiki/Water_collected_between_towers
Water collected between towers
Task In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, completely filling all convex enclosures in the chart with water. 9 ██ 9 ██ 8 ██ 8 ██ 7 ██ ██ 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.
#Factor
Factor
USING: formatting kernel math.statistics math.vectors sequences ;   : area ( seq -- n ) [ cum-max ] [ <reversed> cum-max reverse vmin ] [ v- sum ] tri ;   { { 1 5 3 7 2 } { 5 3 7 2 6 4 5 9 1 2 } { 2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1 } { 5 5 5 5 } { 5 6 7 8 } { 8 7 7 6 } { 6 7 10 7 6 } } [ dup area "%[%d, %] -> %d\n" printf ] each
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
#Elixir
Elixir
defmodule VerifyDistribution do def naive( generator, times, delta_percent ) do dict = Enum.reduce( List.duplicate(generator, times), Map.new, &update_counter/2 ) values = Map.values(dict) average = Enum.sum( values ) / map_size( dict ) delta = average * (delta_percent / 100) fun = fn {_key, value} -> abs(value - average) > delta end too_large_dict = Enum.filter( dict, fun ) return( length(too_large_dict), too_large_dict, average, delta_percent ) end   def return( 0, _too_large_dict, _average, _delta ), do: :ok def return( _n, too_large_dict, average, delta ) do {:error, {too_large_dict, :failed_expected_average, average, 'with_delta_%', delta}} end   def update_counter( fun, dict ), do: Map.update( dict, fun.(), 1, &(&1+1) ) end   fun = fn -> Dice.dice7 end IO.inspect VerifyDistribution.naive( fun, 100000, 3 ) IO.inspect VerifyDistribution.naive( fun, 100, 3 )
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
#Erlang
Erlang
  -module( verify_distribution_uniformity ).   -export( [naive/3] ).   naive( Generator, Times, Delta_percent ) -> Dict = lists:foldl( fun update_counter/2, dict:new(), lists:duplicate(Times, Generator) ), Values = [dict:fetch(X, Dict) || X <- dict:fetch_keys(Dict)], Average = lists:sum( Values ) / dict:size( Dict ), Delta = Average * (Delta_percent / 100), Fun = fun(_Key, Value) -> erlang:abs(Value - Average) > Delta end, Too_large_dict = dict:filter( Fun, Dict ), return( dict:size(Too_large_dict), Too_large_dict, Average, Delta_percent ).       return( 0, _Too_large_dict, _Average, _Delta ) -> ok; return( _N, Too_large_dict, Average, Delta ) -> {error, {dict:to_list(Too_large_dict), failed_expected_average, Average, 'with_delta_%', Delta}}.   update_counter( Fun, Dict ) -> dict:update_counter( Fun(), 1, Dict ).  
http://rosettacode.org/wiki/Voronoi_diagram
Voronoi diagram
A Voronoi diagram is a diagram consisting of a number of sites. Each Voronoi site s also has a Voronoi cell consisting of all points closest to s. Task Demonstrate how to generate and display a Voroni diagram. See algo K-means++ clustering.
#.D0.9C.D0.9A-61.2F52
МК-61/52
0 П4 0 П5 ИП0 1 - x^2 ИП1 1 - x^2 + КвКор П3 9 П6 КИП6 П8 {x} 2 10^x * П9 [x] ИП5 - x^2 ИП9 {x} 2 10^x * ИП4 - x^2 + КвКор П9 ИП3 - x<0 47 ИП9 П3 ИП6 П7 ИП6 ИП2 - 9 - x>=0 17 КИП7 [x] С/П КИП5 ИП5 ИП1 - x>=0 04 КИП4 ИП4 ИП0 - x>=0 02
http://rosettacode.org/wiki/Voronoi_diagram
Voronoi diagram
A Voronoi diagram is a diagram consisting of a number of sites. Each Voronoi site s also has a Voronoi cell consisting of all points closest to s. Task Demonstrate how to generate and display a Voroni diagram. See algo K-means++ clustering.
#Nim
Nim
  from sequtils import newSeqWith from random import rand, randomize from times import now import libgd   const img_width = 400 img_height = 300 nSites = 20   proc dot(x, y: int): int = x * x + y * y   proc generateVoronoi(img: gdImagePtr) =   randomize(cast[int64](now()))   # random sites let sx = newSeqWith(nSites, rand(img_width)) let sy = newSeqWith(nSites, rand(img_height))   # generate a random color for each site let sc = newSeqWith(nSites, img.setColor(rand(255), rand(255), rand(255)))   # generate diagram by coloring each pixel with color of nearest site for x in 0 ..< img_width: for y in 0 ..< img_height: var dMin = dot(img_width, img_height) var sMin: int for s in 0 ..< nSites: if (let d = dot(sx[s] - x, sy[s] - y); d) < dMin: (sMin, dMin) = (s, d)   img.setPixel(point=[x, y], color=sc[sMin])   # mark each site with a black box let black = img.setColor(0x000000) for s in 0 ..< nSites: img.drawRectangle( startCorner=[sx[s] - 2, sy[s] - 2], endCorner=[sx[s] + 2, sy[s] + 2], color=black, fill=true)   proc main() =   withGd imageCreate(img_width, img_height, trueColor=true) as img: img.generateVoronoi()   let png_out = open("outputs/voronoi_diagram.png", fmWrite) img.writePng(png_out) png_out.close()   main()  
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at the time thought impossible with such a code. As the workings of the algorithm are clearly described in the linked Wikipedia article they will not be repeated here. Task Write routines, methods, procedures etc. in your language to generate a Verhoeff checksum digit for non-negative integers of any length and to validate the result. A combined routine is also acceptable. The more mathematically minded may prefer to generate the 3 tables required from the description provided rather than to hard-code them. Write your routines in such a way that they can optionally display digit by digit calculations as in the Wikipedia example. Use your routines to calculate check digits for the integers: 236, 12345 and 123456789012 and then validate them. Also attempt to validate the same integers if the check digits in all cases were 9 rather than what they actually are. Display digit by digit calculations for the first two integers but not for the third. Related task   Damm algorithm
#F.23
F#
  // Verhoeff algorithm. Nigel Galloway: August 26th., 2021 let d,inv,p=let d=[|0;1;2;3;4;5;6;7;8;9;1;2;3;4;0;6;7;8;9;5;2;3;4;0;1;7;8;9;5;6;3;4;0;1;2;8;9;5;6;7;4;0;1;2;3;9;5;6;7;8;5;9;8;7;6;0;4;3;2;1;6;5;9;8;7;1;0;4;3;2;7;6;5;9;8;2;1;0;4;3;8;7;6;5;9;3;2;1;0;4;9;8;7;6;5;4;3;2;1;0|] let p=[|0;1;2;3;4;5;6;7;8;9;1;5;7;6;2;8;3;0;9;4;5;8;0;3;7;9;6;1;4;2;8;9;1;6;0;4;3;5;2;7;9;4;5;3;1;2;6;8;7;0;4;2;8;6;5;7;3;9;0;1;2;7;9;3;8;0;6;4;1;5;7;0;4;6;9;1;3;2;5;8|] let inv=[|0;4;3;2;1;5;6;7;8;9|] in (fun n g->d.[10*n+g]),(fun g->inv.[g]),(fun n g->p.[10*(n%8)+g]) let fN g=Seq.unfold(fun(i,g,l)->if i=0I then None else let ni=int(i%10I) in let l=d l (p g ni) in Some((ni,l),(i/10I,g+1,l)))(g,0,0) let csum g=let _,g=Seq.last(fN g) in inv g let printTable g=printfn $"Work Table for %A{g}\n i nᵢ p[i,nᵢ] c\n--------------"; fN g|>Seq.iteri(fun i (n,g)->printfn $"%d{i}  %d{n}  %d{p i n}  %d{g}") printTable 2360I printfn $"\nThe CheckDigit for 236 is %d{csum 2360I}\n" printTable 2363I printfn $"\nThe assertion that 2363 is valid is %A{csum 2363I=0}\n" printTable 2369I printfn $"\nThe assertion that 2369 is valid is %A{csum 2369I=0}\n" printTable 123450I printfn $"\nThe CheckDigit for 12345 is %d{csum 123450I}\n" printTable 123451I printfn $"\nThe assertion that 123451 is valid is %A{csum 123451I=0}\n" printTable 123459I printfn $"\nThe assertion that 123459 is valid is %A{csum 123459I=0}" printfn $"The CheckDigit for 123456789012 is %d{csum 1234567890120I}" printfn $"The assertion that 1234567890120 is valid is %A{csum 1234567890120I=0}" printfn $"The assertion that 1234567890129 is valid is %A{csum 1234567890129I=0}"  
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
#C.23
C#
  using System;   namespace VigenereCipher { class VCipher { public string encrypt(string txt, string pw, int d) { int pwi = 0, tmp; string ns = ""; txt = txt.ToUpper(); pw = pw.ToUpper(); foreach (char t in txt) { if (t < 65) continue; tmp = t - 65 + d * (pw[pwi] - 65); if (tmp < 0) tmp += 26; ns += Convert.ToChar(65 + ( tmp % 26) ); if (++pwi == pw.Length) pwi = 0; }   return ns; } };   class Program { static void Main(string[] args) { VCipher v = new VCipher();   string s0 = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!", pw = "VIGENERECIPHER";   Console.WriteLine(s0 + "\n" + pw + "\n"); string s1 = v.encrypt(s0, pw, 1); Console.WriteLine("Encrypted: " + s1); s1 = v.encrypt(s1, "VIGENERECIPHER", -1); Console.WriteLine("Decrypted: " + s1); Console.WriteLine("\nPress any key to continue..."); Console.ReadKey(); } } }  
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.
#F.23
F#
type tree = | T of string * tree list   let prefMid = seq { yield "├─"; while true do yield "│ " } let prefEnd = seq { yield "└─"; while true do yield " " } let prefNone = seq { while true do yield "" }   let c2 x y = Seq.map2 (fun u v -> String.concat "" [u; v]) x y   let rec visualize (T(label, children)) pre = seq { yield (Seq.head pre) + label if children <> [] then let preRest = Seq.skip 1 pre let last = Seq.last (List.toSeq children) for e in children do if e = last then yield! visualize e (c2 preRest prefEnd) else yield! visualize e (c2 preRest prefMid) }   let example = T ("root", [T ("a", [T ("a1", [T ("a11", []); T ("a12", []) ]) ]); T ("b", [T ("b1", []) ]) ])   visualize example prefNone |> Seq.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).
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   import java.util.List   runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method getFileNames(dirname, pattern) public static returns List dir = File(dirname) contents = dir.list() fileNames = ArrayList() loop fname over contents if fname.matches(pattern) then do fileNames.add(fname) end end fname Collections.sort(fileNames) return fileNames   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static parse arg dirname pattern if dirname = '' then dirname = System.getProperty('user.dir') if pattern = '' then pattern = '^RW.*\\.nrx$'   fileNames = getFileNames(dirname, pattern) say 'Search of' dirname 'for files matching pattern "'pattern'" found' fileNames.size() 'files.' loop fn = 0 while fn < fileNames.size() say (fn + 1).right(5)':' fileNames.get(fn) end fn   return  
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. Note: Please be careful when running any code presented here. Related task   Walk Directory Tree   (read entire directory tree).
#Nim
Nim
import os   for file in walkFiles "/foo/bar/*.mp3": echo file
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis
Vigenère cipher/Cryptanalysis
Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text: MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS 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.
#Racket
Racket
  #lang at-exp racket   (define max-keylen 30)   (define text @~a{MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB 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})   (define first-char (char->integer #\A)) (define chars# (- (char->integer #\Z) first-char -1))   (define freqs ; english letter frequencies from wikipedia ((compose1 list->vector (curry map (curryr / 100000.0))) '(8167 1492 2782 4253 12702 2228 2015 6094 6966 153 772 4025 2406 6749 7507 1929 95 5987 6327 9056 2758 978 2360 150 1974 74)))   (define text* (for/vector ([c (regexp-replace* #px"\\s+" text "")]) (- (char->integer c) first-char))) (define N (vector-length text*))   (define (col-guesses len) (for/list ([ofs len]) (define text (for/list ([i (in-range ofs N len)]) (vector-ref text* i))) (define cN (length text)) (define cfreqs (make-vector chars# 0)) (for ([c (in-list text)]) (vector-set! cfreqs c (add1 (vector-ref cfreqs c)))) (for ([i chars#]) (vector-set! cfreqs i (/ (vector-ref cfreqs i) cN))) (argmin car (for/list ([d chars#]) (cons (for/sum ([i chars#]) (expt (- (vector-ref freqs i) (vector-ref cfreqs (modulo (+ i d) chars#))) 2)) d)))))   (define best-key (cdr (argmin car (for/list ([len (range 1 (add1 max-keylen))]) (define guesses (col-guesses len)) (cons (/ (apply + (map car guesses)) len) (map cdr guesses))))))   (printf "Best key found: ") (for ([c best-key]) (display (integer->char (+ c first-char)))) (newline)   (printf "Decoded text:\n") (define decode-num (let ([cur '()]) (λ(n) (when (null? cur) (set! cur best-key)) (begin0 (modulo (- n (car cur)) chars#) (set! cur (cdr cur)))))) (for ([c text]) (define n (- (char->integer c) first-char)) (if (not (< -1 n chars#)) (display c) (display (integer->char (+ first-char (decode-num n)))))) (newline)  
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.
#Raku
Raku
# from Wikipedia constant %English-letter-freq = ( E => 12.70, L => 4.03, Y => 1.97, P => 1.93, T => 9.06, A => 8.17, O => 7.51, I => 6.97, N => 6.75, S => 6.33, H => 6.09, R => 5.99, D => 4.25, C => 2.78, U => 2.76, M => 2.41, W => 2.36, F => 2.23, G => 2.02, B => 1.29, V => 0.98, K => 0.77, J => 0.15, X => 0.15, Q => 0.10, Z => 0.07 ); constant @alphabet = %English-letter-freq.keys.sort; constant max_key_lengths = 5; # number of keylengths to try   sub myguess ($text) { my ($seqtext, @spacing, @factors, $pos, %freq, %Keys);   # Kasiski examination $seqtext = $text; while ($seqtext ~~ /$<sequence>=[...].*$<sequence>/) { $seqtext = substr($seqtext, 1+index($seqtext, $<sequence>)); push @spacing, 1 + index($seqtext, $<sequence>); } for @spacing -> $j { %freq{$_}++ for grep { $j %% $_ }, 2..$j; }   # discard very short keys, and test only the most likely remaining key lengths (%freq.keys.grep(* > 3).sort({%freq{$_}}).tail(max_key_lengths)).race(:1batch).map: -> $keylen { my $key-guess = ''; loop (my $i = 0; $i < $keylen; $i++) { my ($mykey, %chi-square, $best-guess); loop (my $j = 0; $j < $text.chars; $j += $keylen) { $mykey ~= substr($text, ($j+$i) % $text.chars, 1); }   for @alphabet -> $subkey { my $decrypted = mycrypt($mykey, $subkey); my $length = $decrypted.chars; for @alphabet -> $char { my $expected = %English-letter-freq{$char} * $length / 100; my $observed = $decrypted.comb.grep(* eq $char).elems; %chi-square{$subkey} += ($observed - $expected)² / $expected if $observed; } } %Keys{$keylen}{'score'} = %chi-square{@alphabet[0]}; for %chi-square.keys.sort -> $sk { if (%chi-square{$sk} <= %Keys{$keylen}{'score'}) { $best-guess = $sk; %Keys{$keylen}{'score'} = %chi-square{$sk}; } } $key-guess ~= $best-guess; } %Keys{$keylen}{'key'} = $key-guess; } %Keys.keys.sort({ %Keys{$_}{'score'} }).map:{ %Keys{$_}{'key'} }; }   sub mycrypt ($text, $key) { constant %values-numbers = @alphabet Z=> ^@alphabet; constant %values-letters = %values-numbers.invert;   my ($new-text); my $keylen = $key.chars; loop (my $i = 0; $i < $text.chars; $i++) { my $val = -1 * %values-numbers{substr( $key, $i%$keylen, 1)} # negative shift for decode + %values-numbers{substr($text, $i, 1)}; $new-text ~= %values-letters{ $val % @alphabet }; } return $new-text; }   my $cipher-text = .uc.trans(@alphabet => '', :c) given q:to/EOD/; 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 EOD   for myguess($cipher-text) -> $key { say "Key $key\n" ~ "Key length {$key.chars}\n" ~ "Plaintext {substr(mycrypt($cipher-text, $key), 0, 80)}...\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).
#F.23
F#
open System.IO   let rec getAllFiles dir pattern = seq { yield! Directory.EnumerateFiles(dir, pattern) for d in Directory.EnumerateDirectories(dir) do yield! getAllFiles d pattern }   getAllFiles "c:\\temp" "*.xml" |> Seq.iter (printfn "%s")
http://rosettacode.org/wiki/Water_collected_between_towers
Water collected between towers
Task In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, completely filling all convex enclosures in the chart with water. 9 ██ 9 ██ 8 ██ 8 ██ 7 ██ ██ 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.
#FreeBASIC
FreeBASIC
type tower hght as uinteger posi as uinteger end type   sub shellsort( a() as tower ) 'quick and dirty shellsort, not the focus of this exercise dim as uinteger gap = ubound(a), i, j, n=ubound(a) dim as tower temp do gap = int(gap / 2.2) if gap=0 then gap=1 for i=gap to n temp = a(i) j=i while j>=gap andalso a(j-gap).hght < temp.hght a(j) = a(j - gap) j -= gap wend a(j) = temp next i loop until gap = 1 end sub   'heights of towers in each city prefixed by the number of towers data 5, 1, 5, 3, 7, 2 data 10, 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 data 16, 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 data 4, 5, 5, 5, 5 data 4, 5, 6, 7, 8 data 4, 8, 7, 7, 6 data 5, 6, 7, 10, 7, 6   dim as uinteger i, n, j, first, last, water dim as tower manhattan(0 to 1) for i = 1 to 7 read n redim manhattan( 0 to n-1 ) for j = 0 to n-1 read manhattan(j).hght manhattan(j).posi = j next j shellsort( manhattan() ) if manhattan(0).posi < manhattan(1).posi then first = manhattan(0).posi last = manhattan(1).posi else first = manhattan(1).posi last = manhattan(0).posi end if water = manhattan(1).hght * (last-first-1) for j = 2 to n-1 if first<manhattan(j).posi and manhattan(j).posi<last then water -= manhattan(j).hght if manhattan(j).posi < first then water += manhattan(j).hght * (first-manhattan(j).posi-1) first = manhattan(j).posi end if if manhattan(j).posi > last then water += manhattan(j).hght * (manhattan(j).posi-last-1) last = manhattan(j).posi end if next j print using "City configuration ## collected #### units of water."; i; water next i
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive
Verify distribution uniformity/Naive
This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) producing random integers. The number of times 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
#Euler_Math_Toolbox
Euler Math Toolbox
  >function checkrandom (frand$, n:index, delta:positive real) ... $ v=zeros(1,n); $ loop 1 to n; v{#}=frand$(); end; $ K=max(v); $ fr=getfrequencies(v,1:K); $ return max(fr/n-1/K)<delta/sqrt(n); $ endfunction >function dice () := intrandom(1,1,6); >checkrandom("dice",1000000,1) 1 >wd = 0|((1:6)+[-0.01,0.01,0,0,0,0])/6 [ 0 0.165 0.335 0.5 0.666666666667 0.833333333333 1 ] >function wrongdice () := find(wd,random()) >checkrandom("wrongdice",1000000,1) 0  
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive
Verify distribution uniformity/Naive
This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) producing random integers. The number of times to call the integer generator. A 'delta' value of some sort that indicates how close to a flat distribution is close enough. The function should produce: Some indication of the distribution achieved. An 'error' if the distribution is not flat enough. Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice). See also: Verify distribution uniformity/Chi-squared test
#Factor
Factor
USING: kernel random sequences assocs locals sorting prettyprint math math.functions math.statistics math.vectors math.ranges ; IN: rosetta-code.dice7   ! Output a random integer 1..5. : dice5 ( -- x ) 5 [1,b] random ;   ! Output a random integer 1..7 using dice5 as randomness source. : dice7 ( -- x ) 0 [ dup 21 < ] [ drop dice5 5 * dice5 + 6 - ] do until 7 rem 1 + ;   ! Roll the die by calling the quotation the given number of times and return ! an array with roll results. ! Sample call: 1000 [ dice7 ] roll : roll ( times quot: ( -- x ) -- array ) [ call( -- x ) ] curry replicate ;   ! Input array contains outcomes of a number of die throws. Each die result is ! an integer in the range 1..X. Calculate and return the number of each ! of the results in the array so that in the first position of the result ! there is the number of ones in the input array, in the second position ! of the result there is the number of twos in the input array, etc. : count-dice-outcomes ( X array -- array ) histogram swap [1,b] [ over [ 0 or ] change-at ] each sort-keys values ;   ! Verify distribution uniformity/Naive. Delta is the acceptable deviation ! from the ideal number of items in each bucket, expressed as a fraction of ! the total count. Sides is the number of die sides. Die-func is a word that ! produces a random number on stack in the range [1..sides], times is the ! number of times to call it. ! Sample call: 0.02 7 [ dice7 ] 100000 verify :: verify ( delta sides die-func: ( -- random ) times -- ) sides times die-func roll count-dice-outcomes dup . times sides / :> ideal-count ideal-count v-n vabs times v/n delta [ < ] curry all? [ "Random enough" . ] [ "Not random enough" . ] if ;     ! Call verify with 1, 10, 100, ... 1000000 rolls of 7-sided die. : verify-all ( -- ) { 1 10 100 1000 10000 100000 1000000 } [| times | 0.02 7 [ dice7 ] times verify ] each ;
http://rosettacode.org/wiki/Voronoi_diagram
Voronoi diagram
A Voronoi diagram is a diagram consisting of a number of sites. Each Voronoi site s also has a Voronoi cell consisting of all points closest to s. Task Demonstrate how to generate and display a Voroni diagram. See algo K-means++ clustering.
#OCaml
OCaml
let n_sites = 220   let size_x = 640 let size_y = 480   let sq2 ~x ~y = (x * x + y * y)   let rand_int_range a b = a + Random.int (b - a + 1)   let nearest_site ~site ~x ~y = let ret = ref 0 in let dist = ref 0 in Array.iteri (fun k (sx, sy) -> let d = sq2 (x - sx) (y - sy) in if k = 0 || d < !dist then begin dist := d; ret := k; end ) site; !ret   let gen_map ~site ~rgb = let nearest = Array.make (size_x * size_y) 0 in let buf = Bytes.create (3 * size_x * size_y) in   for y = 0 to pred size_y do for x = 0 to pred size_x do nearest.(y * size_x + x) <- nearest_site ~site ~x ~y; done; done;   for i = 0 to pred (size_y * size_x) do let j = i * 3 in let r, g, b = rgb.(nearest.(i)) in Bytes.set buf (j+0) (char_of_int r); Bytes.set buf (j+1) (char_of_int g); Bytes.set buf (j+2) (char_of_int b); done;   Printf.printf "P6\n%d %d\n255\n" size_x size_y; print_bytes buf; ;;   let () = Random.self_init (); let site = Array.init n_sites (fun i -> (Random.int size_x, Random.int size_y)) in let rgb = Array.init n_sites (fun i -> (rand_int_range 160 255, rand_int_range 40 160, rand_int_range 20 140)) in gen_map ~site ~rgb
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at the time thought impossible with such a code. As the workings of the algorithm are clearly described in the linked Wikipedia article they will not be repeated here. Task Write routines, methods, procedures etc. in your language to generate a Verhoeff checksum digit for non-negative integers of any length and to validate the result. A combined routine is also acceptable. The more mathematically minded may prefer to generate the 3 tables required from the description provided rather than to hard-code them. Write your routines in such a way that they can optionally display digit by digit calculations as in the Wikipedia example. Use your routines to calculate check digits for the integers: 236, 12345 and 123456789012 and then validate them. Also attempt to validate the same integers if the check digits in all cases were 9 rather than what they actually are. Display digit by digit calculations for the first two integers but not for the third. Related task   Damm algorithm
#Go
Go
package main   import "fmt"   var d = [][]int{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, 1, 0, 4, 3}, {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, }   var inv = []int{0, 4, 3, 2, 1, 5, 6, 7, 8, 9}   var p = [][]int{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8}, }   func verhoeff(s string, validate, table bool) interface{} { if table { t := "Check digit" if validate { t = "Validation" } fmt.Printf("%s calculations for '%s':\n\n", t, s) fmt.Println(" i nᵢ p[i,nᵢ] c") fmt.Println("------------------") } if !validate { s = s + "0" } c := 0 le := len(s) - 1 for i := le; i >= 0; i-- { ni := int(s[i] - 48) pi := p[(le-i)%8][ni] c = d[c][pi] if table { fmt.Printf("%2d  %d  %d  %d\n", le-i, ni, pi, c) } } if table && !validate { fmt.Printf("\ninv[%d] = %d\n", c, inv[c]) } if !validate { return inv[c] } return c == 0 }   func main() { ss := []string{"236", "12345", "123456789012"} ts := []bool{true, true, false, true} for i, s := range ss { c := verhoeff(s, false, ts[i]).(int) fmt.Printf("\nThe check digit for '%s' is '%d'\n\n", s, c) for _, sc := range []string{s + string(c+48), s + "9"} { v := verhoeff(sc, true, ts[i]).(bool) ans := "correct" if !v { ans = "incorrect" } fmt.Printf("\nThe validation for '%s' is %s\n\n", sc, ans) } } }
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
#C.2B.2B
C++
#include <iostream> #include <string> using namespace std;   class Vigenere { public: string key;   Vigenere(string key) { for(int i = 0; i < key.size(); ++i) { if(key[i] >= 'A' && key[i] <= 'Z') this->key += key[i]; else if(key[i] >= 'a' && key[i] <= 'z') this->key += key[i] + 'A' - 'a'; } }   string encrypt(string text) { string out;   for(int i = 0, j = 0; i < text.length(); ++i) { char c = text[i];   if(c >= 'a' && c <= 'z') c += 'A' - 'a'; else if(c < 'A' || c > 'Z') continue;   out += (c + key[j] - 2*'A') % 26 + 'A'; j = (j + 1) % key.length(); }   return out; }   string decrypt(string text) { string out;   for(int i = 0, j = 0; i < text.length(); ++i) { char c = text[i];   if(c >= 'a' && c <= 'z') c += 'A' - 'a'; else if(c < 'A' || c > 'Z') continue;   out += (c - key[j] + 26) % 26 + 'A'; j = (j + 1) % key.length(); }   return out; } };   int main() { Vigenere cipher("VIGENERECIPHER");   string original = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; string encrypted = cipher.encrypt(original); string decrypted = cipher.decrypt(encrypted);   cout << original << endl; cout << "Encrypted: " << encrypted << endl; cout << "Decrypted: " << decrypted << endl; }
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.
#Factor
Factor
USE: literals   CONSTANT: mammals { "mammals" { "deer" "gorilla" "dolphin" } } CONSTANT: reptiles { "reptiles" { "turtle" "lizard" "snake" } }   { "animals" ${ mammals reptiles } } dup . 10 margin set .
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. Note: Please be careful when running any code presented here. Related task   Walk Directory Tree   (read entire directory tree).
#Objeck
Objeck
use IO;   bundle Default { class Test { function : Main(args : System.String[]) ~ Nil { dir := Directory->List("/src/code"); for(i := 0; i < dir->Size(); i += 1;) { if(dir[i]->EndsWith(".obs")) { dir[i]->PrintLine(); }; }; } } }
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. Note: Please be careful when running any code presented here. Related task   Walk Directory Tree   (read entire directory tree).
#Objective-C
Objective-C
NSString *dir = @"/foo/bar";   // Pre-OS X 10.5 NSArray *contents = [[NSFileManager defaultManager] directoryContentsAtPath:dir]; // OS X 10.5+ NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dir error:NULL];   for (NSString *file in contents) if ([[file pathExtension] isEqualToString:@"mp3"]) NSLog(@"%@", 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.
#Rust
Rust
  use std::iter::FromIterator;   const CRYPTOGRAM: &str = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG ALWQC SNWBU BYHCU 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 FREQUENCIES: [f32; 26] = [ 0.08167, 0.01492, 0.02202, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.01292, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09356, 0.02758, 0.00978, 0.02560, 0.00150, 0.01994, 0.00077, ];   fn best_match(a: &[f32]) -> u8 { let sum: f32 = a.iter().sum(); let mut best_fit = std::f32::MAX; let mut best_rotate = 0; for rotate in 0..=25 { let mut fit = 0.; for i in 0..=25 { let char_freq = FREQUENCIES[i]; let idx = (i + rotate as usize) % 26 as usize; let d = a[idx] / sum - char_freq; fit += d * d / char_freq; } if fit < best_fit { best_fit = fit; best_rotate = rotate; } }   best_rotate }   fn freq_every_nth(msg: &[u8], key: &mut [char]) -> f32 { let len = msg.len(); let interval = key.len(); let mut accu = [0.; 26]; for j in 0..interval { let mut out = [0.; 26]; for i in (j..len).step_by(interval) { let idx = msg[i] as usize; out[idx] += 1.; } let rot = best_match(&out); key[j] = char::from(rot + b'A'); for i in 0..=25 { let idx: usize = (i + rot as usize) % 26; accu[i] += out[idx]; } } let sum: f32 = accu.iter().sum(); let mut ret = 0.; for i in 0..=25 { let char_freq = FREQUENCIES[i]; let d = accu[i] / sum - char_freq; ret += d * d / char_freq; } ret }   fn decrypt(text: &str, key: &str) -> String { let key_chars_cycle = key.as_bytes().iter().map(|b| *b as i32).cycle(); let is_ascii_uppercase = |c: &u8| (b'A'..=b'Z').contains(c); text.as_bytes() .iter() .filter(|c| is_ascii_uppercase(c)) .map(|b| *b as i32) .zip(key_chars_cycle) .fold(String::new(), |mut acc, (c, key_char)| { let ci: u8 = ((c - key_char + 26) % 26) as u8; acc.push(char::from(b'A' + ci)); acc }) } fn main() { let enc = CRYPTOGRAM .split_ascii_whitespace() .collect::<Vec<_>>() .join(""); let cryptogram: Vec<u8> = enc.as_bytes().iter().map(|b| u8::from(b - b'A')).collect(); let mut best_fit = std::f32::MAX; let mut best_key = String::new(); for j in 1..=26 { let mut key = vec!['\0'; j]; let fit = freq_every_nth(&cryptogram, &mut key); let s_key = String::from_iter(key); // 'from_iter' is imported from std::iter::FromIterator; if fit < best_fit { best_fit = fit; best_key = s_key; } }   println!("best key: {}", &best_key); println!("\nDecrypted text:\n{}", decrypt(&enc, &best_key)); }  
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.
#Tcl
Tcl
package require Tcl 8.6   oo::class create VigenereAnalyzer { variable letterFrequencies sortedTargets constructor {{frequencies { 0.08167 0.01492 0.02782 0.04253 0.12702 0.02228 0.02015 0.06094 0.06966 0.00153 0.00772 0.04025 0.02406 0.06749 0.07507 0.01929 0.00095 0.05987 0.06327 0.09056 0.02758 0.00978 0.02360 0.00150 0.01974 0.00074 }}} { set letterFrequencies $frequencies set sortedTargets [lsort -real $frequencies] if {[llength $frequencies] != 26} { error "wrong length of frequency table" } }   ### Utility methods # Find the value of $idxvar in the range [$from..$to) that maximizes the value # in $scorevar (which is computed by evaluating $body) method Best {idxvar from to scorevar body} { upvar 1 $idxvar i $scorevar s set bestI $from for {set i $from} {$i < $to} {incr i} { uplevel 1 $body if {![info exist bestS] || $bestS < $s} { set bestI $i set bestS $s } } return $bestI } # Simple list map method Map {var list body} { upvar 1 $var v set result {} foreach v $list {lappend result [uplevel 1 $body]} return $result } # Simple partition of $list into $groups groups; thus, the partition of # {a b c d e f} into 3 produces {a d} {b e} {c f} method Partition {list groups} { set i 0 foreach val $list { dict lappend result $i $val if {[incr i] >= $groups} { set i 0 } } return [dict values $result] }   ### Helper methods # Get the actual counts of different types of characters in the given list method Frequency cleaned { for {set i 0} {$i < 26} {incr i} { dict set tbl $i 0 } foreach ch $cleaned { dict incr tbl [expr {[scan $ch %c] - 65}] } return $tbl }   # Get the correlation factor of the characters in a given list with the # class-specified language frequency corpus method Correlation cleaned { set result 0.0 set freq [lsort -integer [dict values [my Frequency $cleaned]]] foreach f $freq s $sortedTargets { set result [expr {$result + $f * $s}] } return $result }   # Compute an estimate for the key length method GetKeyLength {cleaned {required 20}} { # Assume that we need at least 20 characters per column to guess set bestLength [my Best i 2 [expr {[llength $cleaned] / $required}] corr { set corr [expr {-0.5 * $i}] foreach chars [my Partition $cleaned $i] { set corr [expr {$corr + [my Correlation $chars]}] } }] if {$bestLength == 0} { error "text is too short to analyze" } return $bestLength }   # Compute the key from the given frequency tables and the class-specified # language frequency corpus method GetKeyFromFreqs freqs { foreach f $freqs { set m [my Best i 0 26 corr { set corr 0.0 foreach {ch count} $f { set d [expr {($ch - $i) % 26}] set corr [expr {$corr + $count*[lindex $letterFrequencies $d]}] } }] append key [format %c [expr {65 + $m}]] } return $key }   ##### The main analyzer method ##### method analyze input { # Turn the input into a clean letter sequence set cleaned [regexp -all -inline {[A-Z]} [string toupper $input]] # Get the (estimated) key length set bestLength [my GetKeyLength $cleaned] # Get the frequency mapping for the partitioned input text set freqs [my Map p [my Partition $cleaned $bestLength] {my Frequency $p}] # Get the key itself return [my GetKeyFromFreqs $freqs] } }
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).
#Factor
Factor
USE: io.directories.search   "." t [ dup ".factor" tail? [ print ] [ drop ] if ] each-file
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   (read a single directory).
#Forth
Forth
  require unix/filestat.fs require unix/libc.fs   : $append ( from len to -- ) 2DUP >R >R COUNT + SWAP MOVE R> R@ C@ + R> C! ;   defer ls-filter   : dots? ( name len -- ? ) drop c@ [char] . = ;   file-stat buffer: statbuf   : isdir ( addr u -- flag ) statbuf lstat ?ior statbuf st_mode w@ S_IFMT and S_IFDIR = ;   : (ls-r) ( dir len -- ) pad c@ >r pad $append s" /" pad $append pad count open-dir if drop r> pad c! exit then ( dirid) begin dup pad count + 256 rot read-dir throw while pad count + over dots? 0= if \ ignore all hidden names dup pad count rot + 2dup ls-filter if cr 2dup type then isdir if pad count + swap recurse else drop then else drop then repeat drop r> pad c! close-dir throw ;   : ls-r ( dir len -- ) 0 pad c! (ls-r) ;   : c-files ( str len -- ? ) dup 3 < if 2drop false exit then + 1- dup c@ 32 or dup [char] c <> swap [char] h <> and if drop false exit then 1- dup c@ [char] . <> if drop false exit then drop true ; ' c-files is ls-filter   : all-files ( str len -- ? ) 2drop true ; ' all-files is ls-filter   s" ." ls-r cr  
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.
#Go
Go
  package main   import "fmt"   func maxl(hm []int ) []int{ res := make([]int,len(hm)) max := 1 for i := 0; i < len(hm);i++{ if(hm[i] > max){ max = hm[i] } res[i] = max; } return res } func maxr(hm []int ) []int{ res := make([]int,len(hm)) max := 1 for i := len(hm) - 1 ; i >= 0;i--{ if(hm[i] > max){ max = hm[i] } res[i] = max; } return res } func min(a,b []int) []int { res := make([]int,len(a)) for i := 0; i < len(a);i++{ if a[i] >= b[i]{ res[i] = b[i] }else { res[i] = a[i] } } return res } func diff(hm, min []int) []int { res := make([]int,len(hm)) for i := 0; i < len(hm);i++{ if min[i] > hm[i]{ res[i] = min[i] - hm[i] } } return res } func sum(a []int) int { res := 0 for i := 0; i < len(a);i++{ res += a[i] } return res }   func waterCollected(hm []int) int { maxr := maxr(hm) maxl := maxl(hm) min := min(maxr,maxl) diff := diff(hm,min) sum := sum(diff) return sum }     func main() { fmt.Println(waterCollected([]int{1, 5, 3, 7, 2})) fmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2})) fmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1})) fmt.Println(waterCollected([]int{5, 5, 5, 5})) fmt.Println(waterCollected([]int{5, 6, 7, 8})) fmt.Println(waterCollected([]int{8, 7, 7, 6})) fmt.Println(waterCollected([]int{6, 7, 10, 7, 6})) }
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
#Forth
Forth
: .bounds ( u1 u2 -- ) ." lower bound = " . ." upper bound = " 1- . cr ; : init-bins ( n -- addr ) cells dup allocate throw tuck swap erase ; : expected ( u1 cnt -- u2 ) over 2/ + swap / ; : calc-limits ( n cnt pct -- low high ) >r expected r> over 100 */ 2dup + 1+ >r - r> ; : make-histogram ( bins xt cnt -- ) 0 ?do 2dup execute 1- cells + 1 swap +! loop 2drop ; : valid-bin? ( addr n low high -- f ) 2>r cells + @ dup . 2r> within ;   : check-distribution {: xt cnt n pct -- f :} \ assumes xt generates numbers from 1 to n n init-bins {: bins :} n cnt pct calc-limits {: low high :} high low .bounds bins xt cnt make-histogram true \ result flag n 0 ?do i 1+ . ." : " bins i low high valid-bin? dup 0= if ." not " then ." ok" cr and loop bins free throw ;
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
#Fortran
Fortran
subroutine distcheck(randgen, n, delta)   interface function randgen integer :: randgen end function randgen end interface   real, intent(in) :: delta integer, intent(in) :: n integer :: i, mval, lolim, hilim integer, allocatable :: buckets(:) integer, allocatable :: rnums(:) logical :: skewed = .false.   allocate(rnums(n))   do i = 1, n rnums(i) = randgen() end do   mval = maxval(rnums) allocate(buckets(mval)) buckets = 0   do i = 1, n buckets(rnums(i)) = buckets(rnums(i)) + 1 end do   lolim = n/mval - n/mval*delta hilim = n/mval + n/mval*delta   do i = 1, mval if(buckets(i) < lolim .or. buckets(i) > hilim) then write(*,"(a,i0,a,i0,a,i0)") "Distribution potentially skewed for bucket ", i, " Expected: ", & n/mval, " Actual: ", buckets(i) skewed = .true. end if end do   if (.not. skewed) write(*,"(a)") "Distribution uniform"   deallocate(rnums) deallocate(buckets)   end subroutine
http://rosettacode.org/wiki/Voronoi_diagram
Voronoi diagram
A Voronoi diagram is a diagram consisting of a number of sites. Each Voronoi site s also has a Voronoi cell consisting of all points closest to s. Task Demonstrate how to generate and display a Voroni diagram. See algo K-means++ clustering.
#Perl
Perl
use strict; use warnings; use Imager;   my %type = ( Taxicab => sub { my($px, $py, $x, $y) = @_; abs($px - $x) + abs($py - $y) }, Euclidean => sub { my($px, $py, $x, $y) = @_; ($px - $x)**2 + ($py - $y)**2 }, Minkowski => sub { my($px, $py, $x, $y) = @_; abs($px - $x)**3 + abs($py - $y)**3 }, );   my($xmax, $ymax) = (400, 400); my @domains; for (1..30) { push @domains, { x => int 5 + rand $xmax-10, y => int 5 + rand $ymax-10, rgb => [int rand 255, int rand 255, int rand 255] } }   for my $type (keys %type) { our $img = Imager->new(xsize => $xmax, ysize => $ymax, channels => 3); voronoi($type, $xmax, $ymax, @domains); dot(1,@domains); $img->write(file => "voronoi-$type.png");   sub voronoi { my($type, $xmax, $ymax, @d) = @_; for my $x (0..$xmax) { for my $y (0..$ymax) { my $i = 0; my $d = 10e6; for (0..$#d) { my $dd = &{$type{$type}}($d[$_]{'x'}, $d[$_]{'y'}, $x, $y); if ($dd < $d) { $d = $dd; $i = $_ } } $img->setpixel(x => $x, y => $y, color => $d[$i]{rgb} ); } } }   sub dot { my($radius, @d) = @_; for (0..$#d) { my $dx = $d[$_]{'x'}; my $dy = $d[$_]{'y'}; for my $x ($dx-$radius .. $dx+$radius) { for my $y ($dy-$radius .. $dy+$radius) { $img->setpixel(x => $x, y => $y, color => [0,0,0]); } } } } }
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce. Reference   an entry at the MathWorld website:   chi-squared distribution.
#11l
11l
V a = 12 V k1_factrl = 1.0 [Float] c c.append(sqrt(2.0 * math:pi)) L(k) 1 .< a c.append(exp(a - k) * (a - k) ^ (k - 0.5) / k1_factrl) k1_factrl *= -k   F gamma_spounge(z) V accm = :c[0] L(k) 1 .< :a accm += :c[k] / (z + k) accm *= exp(-(z + :a)) * (z + :a) ^ (z + 0.5) R accm / z   F GammaInc_Q(a, x) V a1 = a - 1 V a2 = a - 2 F f0(t) R t ^ @a1 * exp(-t)   F df0(t) R (@a1 - t) * t ^ @a2 * exp(-t)   V y = a1 L f0(y) * (x - y) > 2.0e-8 & y < x y += 0.3 I y > x y = x   V h = 3.0e-4 V n = Int(y / h) h = y / n V hh = 0.5 * h V gamax = h * sum(((n - 1 .< -1).step(-1).map(j -> @h * j)).map(t -> @f0(t) + @hh * @df0(t)))   R gamax / gamma_spounge(a)   F chi2UniformDistance(dataSet) V expected = sum(dataSet) * 1.0 / dataSet.len V cntrd = (dataSet.map(d -> d - @expected)) R sum(cntrd.map(x -> x * x)) / expected   F chi2Probability(dof, distance) R 1.0 - GammaInc_Q(0.5 * dof, 0.5 * distance)   F chi2IsUniform(dataSet, significance) V dof = dataSet.len - 1 V dist = chi2UniformDistance(dataSet) R chi2Probability(dof, dist) > significance   V dset1 = [199809, 200665, 199607, 200270, 199649] V dset2 = [522573, 244456, 139979, 71531, 21461]   L(ds) (dset1, dset2) print(‘Data set: ’ds) V dof = ds.len - 1 V distance = chi2UniformDistance(ds) print(‘dof: #. distance: #.4’.format(dof, distance), end' ‘ ’) V prob = chi2Probability(dof, distance) print(‘probability: #.4’.format(prob), end' ‘ ’) print(‘uniform? ’(I chi2IsUniform(ds, 0.05) {‘Yes’} E ‘No’))
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at the time thought impossible with such a code. As the workings of the algorithm are clearly described in the linked Wikipedia article they will not be repeated here. Task Write routines, methods, procedures etc. in your language to generate a Verhoeff checksum digit for non-negative integers of any length and to validate the result. A combined routine is also acceptable. The more mathematically minded may prefer to generate the 3 tables required from the description provided rather than to hard-code them. Write your routines in such a way that they can optionally display digit by digit calculations as in the Wikipedia example. Use your routines to calculate check digits for the integers: 236, 12345 and 123456789012 and then validate them. Also attempt to validate the same integers if the check digits in all cases were 9 rather than what they actually are. Display digit by digit calculations for the first two integers but not for the third. Related task   Damm algorithm
#J
J
cyc=: | +/~@i. NB. cyclic group, order y ac=: |(+-/~@i.) NB. anticyclic group, order y a2n=: (+#)@ NB. add 2^n di=: (cyc,.cyc a2n),((ac a2n),.ac)   D=: di 5 INV=: ,I.0=D P=: {&(C.1 5 8 9 4 2 7 0;3 6)^:(i.8) i.10   verhoeff=: {{ c=. 0 for_N. |.10 #.inv y do. c=. D{~<c,P{~<(8|N_index),N end. }}   traceverhoeff=: {{ r=. EMPTY c=. 0 for_N. |.10 #.inv y do. c0=. c c=. D{~<c,p=.P{~<(j=.8|N_index),N r=. r, c,p,j,N_index,N,c0 end. labels=. cut 'cᵢ p[i,nᵢ] i nᵢ n cₒ' 1 1}.}:~.":labels,(<;._1"1~[:*/' '=])' ',.":r }}   checkdigit=: INV {~ verhoeff@*&10 valid=: 0 = verhoeff
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
#Ceylon
Ceylon
shared void run() {   function normalize(String text) => text.uppercased.filter(Character.letter);   function crypt(String text, String key, Character(Character, Character) transform) => String { for ([a, b] in zipPairs(normalize(text), normalize(key).cycled)) transform(a, b) };   function encrypt(String clearText, String key) => crypt(clearText, key, (Character a, Character b) => ('A'.integer + ((a.integer + b.integer - 130) % 26)).character);   function decrypt(String cipherText, String key) => crypt(cipherText, key, (Character a, Character b) => ('A'.integer + ((a.integer - b.integer + 26) % 26)).character);   value key = "VIGENERECIPHER"; value message = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; value encrypted = encrypt(message, key); value decrypted = decrypt(encrypted, key);   print(encrypted); print(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.
#F.C5.8Drmul.C3.A6
Fōrmulæ
Dim Shared As Ubyte colores(4) => {7,13,14,3,2}   Sub showTree(n As Integer, A As String) Dim As Integer i, co = 0, b = 1, col Dim As String cs = Left(A, 1)   If cs = "" Then Exit Sub   Select Case cs Case "[" co += 1 : showTree(n + 1, Right(A, Len(A) - 1)) Exit Select Case "]" co -= 1 : showTree(n - 1, Right(A, Len(A) - 1)) Exit Select Case Else For i = 2 To n Print " "; co = n Next i Color colores(co) : Print !"\&hc0-"; cs showTree(n, Right(A, Len(A) - 1)) Exit Select End Select End Sub   Cls showTree(0, "[1[2[3][4[5][6]][7]][8[9]]]") Print !"\n\n\n" showTree(0, "[1[2[3[4]]][5[6][7[8][9]]]]") Sleep
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).
#OCaml
OCaml
#load "str.cma" let contents = Array.to_list (Sys.readdir ".") in let select pat str = Str.string_match (Str.regexp pat) str 0 in List.filter (select ".*\\.jpg") contents
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. Note: Please be careful when running any code presented here. Related task   Walk Directory Tree   (read entire directory tree).
#Oz
Oz
declare [Path] = {Module.link ['x-oz://system/os/Path.ozf']} [Regex] = {Module.link ['x-oz://contrib/regex']}   Files = {Filter {Path.readdir "."} Path.isFile} Pattern = ".*\\.oz$" MatchingFiles = {Filter Files fun {$ File} {Regex.search Pattern File} \= false end} in {ForAll MatchingFiles System.showInfo}
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis
Vigenère cipher/Cryptanalysis
Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text: MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS 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.
#Vedit_macro_language
Vedit macro language
// (1) Copy text into tmp buffer and remove non-alpha chars.   Chdir(PATH_ONLY) BOF Reg_Copy(10, ALL) // copy text to new buffer Buf_Switch(Buf_Free) Reg_Ins(10) BOF Replace ("|!|A", "", BEGIN+ALL+NOERR) // remove non-alpha chars Reg_Copy_Block(10,0,EOB_pos) // @10 = text to be analysed   #20 = Buf_Num // buffer for text being analyzed #21 = Buf_Free // buffer for English frequency list (A-Z) Buf_Switch(#21) Ins_Text("8167 1492 2782 4253 12702 2228 2015 6094 6966 153 772 4025 2406 6749 7507 1929 95 5987 6327 9056 2758 978 2360 150 1974 74") File_Open("unixdict.txt") // or use "|(MACRO_DIR)\scribe\english.vdf" #23 = Buf_Num // buffer for dictionary #24 = Buf_Free // buffer for key canditates   Buf_Switch(#24) for (#1=0; #1<5; #1++) { // Fill table for 5 keys of 50 chars Ins_Char('.', COUNT, 50) Ins_Newline } #22 = Buf_Free // buffer for results   #25 = Reg_Size(10) // number of letters in the text #26 = 26 // number of characters in the alphabet #61 = min(#25/10, 50) // max key length to try   // (2) Check Index of coincidence (or Kp) for each key length   Buf_Switch(#22) // buffer for results Ins_Text("KeyLen Kp dist ") Ins_Newline Ins_Text("-----------------") Ins_Newline #13 = Cur_Pos #7 = 0 // no Caesar encryption for (#5=1; #5<=#61; #5++) { Buf_Switch(#20) // text being analyzed BOF #54 = 0; // sum of Kp's for (#6=0; #6<#5; #6++) { // for each slide Goto_Pos(#6) Call("CHARACTER_FREQUENCIES") Call("INDEX_OF_COINCIDENCE") // #51 = Kp * 10000 #54 += #51 } #54 /= #5 // average of Kp's Buf_Switch(#22) Num_Ins(#5, COUNT, 3) // write key length IT(": ") Num_Ins(#54, NOCR) // average Kp Num_Ins(670-#54) // distance to English Kp } Buf_Switch(#22) Sort_Merge("5,12", #13, Cur_Pos, REVERSE) // sort the results by Kp value Ins_Newline   // (3) Check the best 4 key lengths to find which one gives the best decrypt result   #38 = 0 // max number of correct characters found #19 = 1 // best key length for (#14 = 0; #14<4; #14++) { // try 4 best key lengths Buf_Switch(#22) // results buffer Goto_Pos(#13) Line(#14) #5 = Num_Eval(SUPPRESS) // #5 = key length Call("FIND_KEYS") // find Caesar key for each key character #4 = -1 // try best match key chars only Call("BUILD_KEY") EOF Ins_Text("Key length ") Num_Ins(#5, LEFT) Reg_Ins(10) // encrypted text BOL Call("DECRYPT_LINE") BOL Call("FIND_ENGLISH_WORDS") // #37 = number of English chars EOL Ins_Newline Ins_Text("Correct chars: ") Num_Ins(#37) if (#37 > #38) { #38 = #37 #19 = #5 } Update() }   Ins_Text("Using key length: ") Num_Ins(#19) Ins_Newline #5 = #19 Call("FIND_KEYS") // find Caesar key for each key character   // (4) Decrypt with different key combinations and try to find English words. // Try key combinations where max one char is taken from 2nd best Caesar key.   #38 = 0 // max number of chars in English words found #39 = -1 // best key number found for (#4 = -1; #4 < #19; #4++) { Call("BUILD_KEY") Buf_Switch(#22) // results Reg_Ins(10) // encrypted text BOL Call("DECRYPT_LINE") BOL Update() Call("FIND_ENGLISH_WORDS") // #37 := number of correct letters in text if (#37 > #38) { #38 = #37 // new highest number of correct chars #39 = #4 // new best key }   EOL IT(" -- ") // display results Num_Ins(#4, COUNT, 3) // key number Ins_Text(": ") for (#6=0; #6<#19; #6++) { // display key #9 = 130 + #6 Ins_Char(#@9) } Ins_Text(" correct chars =") Num_Ins(#37) } Ins_Text("Best key = ") Num_Ins(#39, LEFT) #4 = #39 Ins_Newline   // Display results // Buf_Switch(#24) // table for key canditates BOF Reg_Copy_Block(14, Cur_Pos, Cur_Pos+#19) // best Caesar key chars Line(1) Reg_Copy_Block(15, Cur_Pos, Cur_Pos+#19) // 2nd best Caesar key chars Call("BUILD_KEY") Buf_Switch(#22) Ins_Text("Key 1: ") Reg_Ins(14) Ins_Newline Ins_Text("Key 2: ") Reg_Ins(15) Ins_Newline Ins_Text("Key: ") for (#6=0; #6 < #19; #6++) { #9 = #6+130 Ins_Char(#@9) } Ins_Newline Ins_Newline   // decrypt the text with selected key Ins_Text("Decrypted text:") Ins_Newline Reg_Ins(10) BOL Call("DECRYPT_LINE") BOL Reg_Copy(13,1) EOL Ins_Newline   // Find English words from the text Reg_Ins(13) Call("FIND_ENGLISH_WORDS") EOL Ins_Newline Num_Ins(#37, NOCR) IT(" of ") Num_Ins(#25, NOCR) IT(" characters are English words. ") Ins_Newline   Buf_Switch(#20) Buf_Quit(OK) Buf_Switch(#21) Buf_Quit(OK) Buf_Switch(#23) Buf_Quit(OK) Buf_Switch(#24) Buf_Quit(OK)   Statline_Message("Done!") Return   ///////////////////////////////////////////////////////////////////////////// // // Caesar decrypt current line and count character frequencies. // in: #5 = step size, #7 = encryption key, #26 = num of chars in alphabet // out: #65...#90 = frequencies, #60 = number of chars   :CHARACTER_FREQUENCIES: Save_Pos for (#8 = 'A'; #8<='Z'; #8++) { #@8 = 0 // reset frequency counters } #60 = 0 // total number of chars while (!At_EOL) { if (Cur_Char >= 'A' && Cur_Char <= 'Z') { #8 = (Cur_Char-'A'+#26-#7) % #26 + 'A' // decrypted char #@8++ #60++ } Char(#5) } Restore_Pos Return   // Calculate Index of Coincidence (Kp). // in: character frequencies in #65...#90, #60 = num of chars // out: #51 = IC * 10000 // :INDEX_OF_COINCIDENCE: Num_Push(10,15) #10 = 0 for (#11 = 'A'; #11<='Z'; #11++) { #10 += (#@11 * (#@11-1)) // Calculate sigma{ni * (ni-1)} } #12 = #60 * (#60-1) // #12 = N * (N-1) #51 = #10 * 10000 / #12 // #51 = Kp * 10000 Num_Pop(10,15) Return   // Find best and 2nd best Caesar key for each character position of Vigenère key. // in: #5=step size (key length) // out: keys in buffer #24 // :FIND_KEYS: for (#6 = 0; #6 < #5; #6++) { // for each char position in the key #30 = -1 // best key char found so far #31 = -1 // 2nd best key char #32 = MAXNUM // smallest error found so far #33 = MAXNUM // 2nd smallest error found so far for (#7 = 0; #7 < #26; #7++) { // for each possible key value #35 = 0 // total frequency error compared to English Buf_Switch(#20) // text being analyzed Goto_Pos(#6) Call("CHARACTER_FREQUENCIES") Buf_Switch(#21) // English frequency table BOF for (#8 = 'A'; #8<='Z'; #8++) { // calculate total frequency error #34 = Num_Eval(SUPPRESS+ADVANCE) #35 += abs((#@8*100000+50000)/#60-#34) }   if (#35 < #32) { // found better match? #33 = #32 #32 = #35 #31 = #30 #30 = #7 } else { if (#35 < #33) { // 2nd best match? #33 = #35 #31 = #7 } } } Buf_Switch(#24) // table for key canditates BOF Goto_Col(#6+1) Ins_Char(#30+'A', OVERWRITE) // save the best match Line(1) Goto_Col(#6+1) Ins_Char(#31+'A', OVERWRITE) // save 2nd best match } Buf_Switch(#22) // results buffer Return   // Combine actual key from 1st and 2nd best Caesar key characters // Use 1st key chars and (possibly) one character from 2nd key. // #4 = index of the char to be picked from 2nd key, -1 = none. // #5 = key length // :BUILD_KEY: Buf_Switch(#24) // table for key canditates BOF for (#6=0; #6<#5; #6++) { // copy 1st key #8 = 130 + #6 #@8 = Cur_Char Char(1) } if (#4 >= 0) { #8 = 130 + #4 // pick one char from 2st key Line(1) Goto_Col(#4+1) #@8 = Cur_Char } Buf_Switch(#22) // results buffer Return   // Decrypt text on current line // in: #5 = key length, #130...#189 = key // :DECRYPT_LINE: Num_Push(6,9) #6 = 0 While (!At_EOL) { #9 = #6+130 #7 = #@9 #8 = (Cur_Char - #7 + #26) % #26 + 'A' // decrypted char Ins_Char(#8, OVERWRITE) #6++ if (#6 >= #5) { #6 = 0 } } Num_Pop(6,9) Return   // Find English words from text on current line // out: #37 = number of chars matched // :FIND_ENGLISH_WORDS: Buf_Switch(#23) // dictionary BOF While (!At_EOF) { Reg_Copy_Block(12, Cur_Pos, EOL_Pos) if (Reg_Size(12) > 2) { Buf_Switch(#22) // buffer for results BOL while (Search_Block(@12, Cur_Pos, EOL_Pos, NOERR)) { Reg_Ins(12, OVERWRITE) } Buf_Switch(#23) } Line(1, ERRBREAK) }   Buf_Switch(#22) BOL #37 = Search_Block("|V", Cur_Pos, EOL_Pos, ALL+NOERR) Return
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).
#FreeBASIC
FreeBASIC
#include "dir.bi"   Sub listFiles(Byref filespec As String, Byval attrib As Integer) Dim As Integer count = 0 Dim As String filename = Dir(filespec, attrib) Do While Len(filename) > 0 count += 1 Print filename filename = Dir() Loop Print !"\nArchives count:"; count End Sub   Dim As String mylist = "C:\FreeBASIC\"" Print "Directories:" listFiles(mylist & "*", fbDirectory) Print Print "Archive files:" listFiles(mylist & "*", fbArchive) Sleep
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).
#Gambas
Gambas
Public Sub Main() Dim sTemp As String   For Each sTemp In RDir("/etc", "*.d") Print sTemp Next   End
http://rosettacode.org/wiki/Water_collected_between_towers
Water collected between towers
Task In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, completely filling all convex enclosures in the chart with water. 9 ██ 9 ██ 8 ██ 8 ██ 7 ██ ██ 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.
#Groovy
Groovy
  Integer waterBetweenTowers(List<Integer> towers) { // iterate over the vertical axis. There the amount of water each row can hold is // the number of empty spots, minus the empty spots at the beginning and end return (1..towers.max()).collect { height -> // create a string representing the row, '#' for tower material and ' ' for air // use .trim() to remove spaces at beginning and end and then count remaining spaces towers.collect({ it >= height ? "#" : " " }).join("").trim().count(" ") }.sum() }   tasks = [ [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] ]   tasks.each { println "$it => total water: ${waterBetweenTowers it}" }  
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
#FreeBASIC
FreeBASIC
  Randomize Timer Function dice5() As Integer Return Int(Rnd * 5) + 1 End Function   Function dice7() As Integer Dim As Integer temp Do temp = dice5() * 5 + dice5() -6 Loop Until temp < 21 Return (temp Mod 7) +1 End Function   Function distCheck(n As Ulongint, delta As Double) As Ulongint   Dim As Ulongint a(n) Dim As Ulongint maxBucket = 0 Dim As Ulongint minBucket = 1000000 For i As Ulongint = 1 To n a(i) = dice5() If a(i) > maxBucket Then maxBucket = a(i) If a(i) < minBucket Then minBucket = a(i) Next i   Dim As Ulongint nBuckets = maxBucket + 1 Dim As Ulongint buckets(maxBucket) For i As Ulongint = 1 To n buckets(a(i)) += 1 Next i 'check buckets Dim As Ulongint expected = n / (maxBucket-minBucket+1) Dim As Ulongint minVal = Int(expected*(1-delta)) Dim As Ulongint maxVal = Int(expected*(1+delta)) expected = Int(expected) Print "minVal", "Expected", "maxVal" Print minVal, expected, maxVal Print "Bucket", "Counter", "pass/fail" distCheck = true For i As Ulongint = minBucket To maxBucket Print i, buckets(i), Iif((minVal > buckets(i)) Or (buckets(i) > maxVal),"fail","") If (minVal > buckets(i)) Or (buckets(i) > maxVal) Then Return false Next i End Function   Dim Shared As Ulongint n = 1000 Print "Testing ";n;" times" If Not(distCheck(n, 0.05)) Then Print "Test failed" Else Print "Test passed" Print   n = 10000 Print "Testing ";n;" times" If Not(distCheck(n, 0.05)) Then Print "Test failed" Else Print "Test passed" Print   n = 50000 Print "Testing ";n;" times" If Not(distCheck(n, 0.05)) Then Print "Test failed" Else Print "Test passed" Print Sleep  
http://rosettacode.org/wiki/Voronoi_diagram
Voronoi diagram
A Voronoi diagram is a diagram consisting of a number of sites. Each Voronoi site s also has a Voronoi cell consisting of all points closest to s. Task Demonstrate how to generate and display a Voroni diagram. See algo K-means++ clustering.
#Phix
Phix
-- -- demo\rosetta\VoronoiDiagram.exw -- =============================== -- -- Can resize, double or halve the number of sites (press +/-), and toggle -- between Euclid, Manhattan, and Minkowski (press e/m/w). -- with javascript_semantics include pGUI.e Ihandle dlg, canvas, timer cdCanvas cddbuffer, cdcanvas -- Stop any current drawing process before starting a new one: -- Without this it /is/ going to crash, if it tries to finish -- drawing all 100 sites, when there are now only 50, for eg. integer timer_active = 0 integer nsites = 200 integer last_width = -1, last_height sequence siteX, siteY, siteC enum EUCLID, MANHATTAN, MINKOWSKI constant dmodes = {"Euclid", "Manhattan", "Minkowski"} integer dmode = EUCLID, drawn = 0 -- (last dmode actually shown) function distance(integer x1, integer y1, integer x2, integer y2) atom d x1 -= x2 y1 -= y2 switch dmode do case EUCLID: d = x1*x1+y1*y1 -- (no need for sqrt) case MANHATTAN: d = abs(x1)+abs(y1) case MINKOWSKI: d = power(abs(x1),3)+power(abs(y1),3) -- ("" power(d,1/3)) end switch return d end function sequence nearestIndex, dist function checkRow(integer site, integer x, integer height) bool res = false atom dxSquared integer x1 = siteX[site]-x switch dmode do case EUCLID: dxSquared = x1*x1 case MANHATTAN: dxSquared = abs(x1) case MINKOWSKI: dxSquared = power(abs(x1),3) end switch for y=1 to height do -- atom dSquared = distance(siteX[site],siteY[site],x,y) -- (sub-optimal..) atom dSquared integer y1 = siteY[site]-y switch dmode do case EUCLID: dSquared = dxSquared+y1*y1 case MANHATTAN: dSquared = dxSquared+abs(y1) case MINKOWSKI: dSquared = dxSquared+power(abs(y1),3) end switch if dSquared<=dist[x,y] then dist[x,y] = dSquared nearestIndex[x,y] = site res = true end if end for return res end function function redraw_cb(Ihandle /*ih*/) integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE") if width!=last_width or height!=last_height or nsites!=length(siteX) then if nsites<1 then nsites = 1 end if siteX = sq_rand(repeat(width,nsites)) siteY = sq_rand(repeat(height,nsites)) siteC = sq_rand(repeat(#FFFFFF,nsites)) last_width = width last_height = height drawn = 0 end if if drawn!=dmode -- (prevent double-draw, and) and not timer_active then -- (drawing when rug moved..) drawn = dmode cdCanvasActivate(cddbuffer) cdCanvasClear(cddbuffer) atom t0 = time(), t1 t1 = time()+0.25 nearestIndex = repeat(repeat(1,height),width) dist = repeat(repeat(0,height),width) -- fill distance table with distances from the first site integer x1 = siteX[1], y1 = siteY[1] for x=1 to width do for y=1 to height do dist[x,y] = distance(x1,y1,x,y) end for if timer_active then exit end if end for --for other towns for i=2 to nsites do -- look left for x=siteX[i] to 1 by -1 do if not checkRow(i, x, height) then exit end if end for -- look right for x=siteX[i]+1 to width do if not checkRow(i, x, height) then exit end if end for if timer_active then exit end if if time()>t1 then IupSetStrAttribute(dlg, "TITLE", "Voronoi diagram (generating - %3.2f%%)",{100*i/nsites}) IupFlush() t1 = time()+0.25 end if end for t1 = time() for y=1 to height do integer nearest = nearestIndex[1,y] integer s = 1 for x=2 to width do if nearestIndex[x,y]<>nearest then cdCanvasSetForeground(cddbuffer, siteC[nearest]) cdCanvasLine(cddbuffer, s-1, y-1, x-2, y-1) nearest = nearestIndex[x,y] s = x end if end for if timer_active then exit end if cdCanvasSetForeground(cddbuffer, siteC[nearest]) cdCanvasLine(cddbuffer, s-1, y-1, width-1, y-1) end for if not timer_active then cdCanvasSetForeground(cddbuffer, CD_BLACK) for i=1 to nsites do cdCanvasSector(cddbuffer, siteX[i], siteY[i], 2, 2, 0, 360) end for cdCanvasFlush(cddbuffer) IupSetStrAttribute(dlg, "TITLE", "Voronoi diagram - %s, %dx%d, %d sites, %3.2fs", {dmodes[dmode],width,height,nsites,time()-t0}) end if end if return IUP_DEFAULT end function function map_cb(Ihandle ih) cdcanvas = cdCreateCanvas(CD_IUP, ih) cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) cdCanvasSetBackground(cddbuffer, CD_WHITE) cdCanvasSetForeground(cddbuffer, CD_BLACK) return IUP_DEFAULT end function function key_cb(Ihandle /*ih*/, atom c) if c=K_ESC then return IUP_CLOSE end if integer wasdmode = dmode switch c do case '+': nsites *= 2 case '-': nsites = max(floor(nsites/2),1) case 'E','e': dmode = EUCLID case 'M','m': dmode = MANHATTAN case 'W','w': dmode = MINKOWSKI end switch if dmode!=wasdmode or nsites!=length(siteX) then -- give any current drawing process 0.1s to abandon: timer_active = 1 IupStoreAttribute(timer, "RUN", "YES") -- IupUpdate(canvas) end if return IUP_CONTINUE end function function timer_cb(Ihandle /*ih*/) timer_active = 0 IupStoreAttribute(timer, "RUN", "NO") IupUpdate(canvas) return IUP_IGNORE end function procedure main() IupOpen() canvas = IupCanvas("RASTERSIZE=600x400") IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"), "ACTION", Icallback("redraw_cb")}) timer = IupTimer(Icallback("timer_cb"), 100, 0) -- (inactive) dlg = IupDialog(canvas,`TITLE="Voronoi diagram"`) IupSetCallback(dlg, "KEY_CB", Icallback("key_cb")) IupShow(dlg) IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce. Reference   an entry at the MathWorld website:   chi-squared distribution.
#Ada
Ada
package Chi_Square is   type Flt is digits 18; type Bins_Type is array(Positive range <>) of Natural;   function Distance(Bins: Bins_Type) return Flt;   end Chi_Square;
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce. Reference   an entry at the MathWorld website:   chi-squared distribution.
#C
C
#include <stdlib.h> #include <stdio.h> #include <math.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif   typedef double (* Ifctn)( double t); /* Numerical integration method */ double Simpson3_8( Ifctn f, double a, double b, int N) { int j; double l1; double h = (b-a)/N; double h1 = h/3.0; double sum = f(a) + f(b);   for (j=3*N-1; j>0; j--) { l1 = (j%3)? 3.0 : 2.0; sum += l1*f(a+h1*j) ; } return h*sum/8.0; }   #define A 12 double Gamma_Spouge( double z ) { int k; static double cspace[A]; static double *coefs = NULL; double accum; double a = A;   if (!coefs) { double k1_factrl = 1.0; coefs = cspace; coefs[0] = sqrt(2.0*M_PI); for(k=1; k<A; k++) { coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl; k1_factrl *= -k; } }   accum = coefs[0]; for (k=1; k<A; k++) { accum += coefs[k]/(z+k); } accum *= exp(-(z+a)) * pow(z+a, z+0.5); return accum/z; }   double aa1; double f0( double t) { return pow(t, aa1)*exp(-t); }   double GammaIncomplete_Q( double a, double x) { double y, h = 1.5e-2; /* approximate integration step size */   /* this cuts off the tail of the integration to speed things up */ y = aa1 = a-1; while((f0(y) * (x-y) > 2.0e-8) && (y < x)) y += .4; if (y>x) y=x;   return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a); }
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at the time thought impossible with such a code. As the workings of the algorithm are clearly described in the linked Wikipedia article they will not be repeated here. Task Write routines, methods, procedures etc. in your language to generate a Verhoeff checksum digit for non-negative integers of any length and to validate the result. A combined routine is also acceptable. The more mathematically minded may prefer to generate the 3 tables required from the description provided rather than to hard-code them. Write your routines in such a way that they can optionally display digit by digit calculations as in the Wikipedia example. Use your routines to calculate check digits for the integers: 236, 12345 and 123456789012 and then validate them. Also attempt to validate the same integers if the check digits in all cases were 9 rather than what they actually are. Display digit by digit calculations for the first two integers but not for the third. Related task   Damm algorithm
#jq
jq
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;   def d: [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], [2, 3, 4, 0, 1, 7, 8, 9, 5, 6], [3, 4, 0, 1, 2, 8, 9, 5, 6, 7], [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], [5, 9, 8, 7, 6, 0, 4, 3, 2, 1], [6, 5, 9, 8, 7, 1, 0, 4, 3, 2], [7, 6, 5, 9, 8, 2, 1, 0, 4, 3], [8, 7, 6, 5, 9, 3, 2, 1, 0, 4], [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] ];   def inv: [0, 4, 3, 2, 1, 5, 6, 7, 8, 9];   def p: [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 5, 7, 6, 2, 8, 3, 0, 9, 4], [5, 8, 0, 3, 7, 9, 6, 1, 4, 2], [8, 9, 1, 6, 0, 4, 3, 5, 2, 7], [9, 4, 5, 3, 1, 2, 6, 8, 7, 0], [4, 2, 8, 6, 5, 7, 3, 9, 0, 1], [2, 7, 9, 3, 8, 0, 6, 4, 1, 5], [7, 0, 4, 6, 9, 1, 3, 2, 5, 8] ];   # Output: an object: {emit, c} def verhoeff($s; $validate; $table):   {emit: (if $table then ["\(if $validate then "Validation" else "Check digit" end) calculations for '\($s)':\n", " i nᵢ p[i,nᵢ] c", "------------------"] else [] end), s: (if $validate then $s else $s + "0" end), c: 0 } | ((.s|length) - 1) as $le | reduce range($le; -1; -1) as $i (.; (.s[$i:$i+1]|explode[] - 48) as $ni | (p[($le-$i) % 8][$ni]) as $pi | .c = d[.c][$pi] | if $table then .emit += ["\($le-$i|lpad(2)) \($ni) \($pi) \(.c)"] else . end ) | if $table and ($validate|not) then .emit += ["\ninv[\(.c)] = \(inv[.c])"] else . end | .c = (if $validate then (.c == 0) else inv[.c] end);   def sts: [ ["236", true], ["12345", true], ["123456789012", false]];   def task: sts[] | . as $st | verhoeff($st[0]; false; $st[1]) as {c: $c, emit: $emit} | $emit[], "\nThe check digit for '\($st[0])' is '\($c)'\n", ( ($st[0] + ($c|tostring)), ($st[0] + "9") | . as $stc | verhoeff($stc; true; $st[1]) as {emit: $emit, c: $v} | (if $v then "correct" else "incorrect" end) as $v | $emit[], "\nThe validation for '\($stc)' is \($v).\n" );   task
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at the time thought impossible with such a code. As the workings of the algorithm are clearly described in the linked Wikipedia article they will not be repeated here. Task Write routines, methods, procedures etc. in your language to generate a Verhoeff checksum digit for non-negative integers of any length and to validate the result. A combined routine is also acceptable. The more mathematically minded may prefer to generate the 3 tables required from the description provided rather than to hard-code them. Write your routines in such a way that they can optionally display digit by digit calculations as in the Wikipedia example. Use your routines to calculate check digits for the integers: 236, 12345 and 123456789012 and then validate them. Also attempt to validate the same integers if the check digits in all cases were 9 rather than what they actually are. Display digit by digit calculations for the first two integers but not for the third. Related task   Damm algorithm
#Julia
Julia
const multiplicationtable = [ 0 1 2 3 4 5 6 7 8 9; 1 2 3 4 0 6 7 8 9 5; 2 3 4 0 1 7 8 9 5 6; 3 4 0 1 2 8 9 5 6 7; 4 0 1 2 3 9 5 6 7 8; 5 9 8 7 6 0 4 3 2 1; 6 5 9 8 7 1 0 4 3 2; 7 6 5 9 8 2 1 0 4 3; 8 7 6 5 9 3 2 1 0 4; 9 8 7 6 5 4 3 2 1 0]   const permutationtable = [ 0 1 2 3 4 5 6 7 8 9; 1 5 7 6 2 8 3 0 9 4; 5 8 0 3 7 9 6 1 4 2; 8 9 1 6 0 4 3 5 2 7; 9 4 5 3 1 2 6 8 7 0; 4 2 8 6 5 7 3 9 0 1; 2 7 9 3 8 0 6 4 1 5; 7 0 4 6 9 1 3 2 5 8]   const inv = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9]   """ verhoeffchecksum(n::Integer, validate=true, terse=true, verbose=false)   Calculate the Verhoeff checksum over `n`. Terse mode or with single argument: return true if valid (last digit is a correct check digit). If checksum mode, return the expected correct checksum digit. If validation mode, return true if last digit checks correctly. """ function verhoeffchecksum(n::Integer, validate=true, terse=true, verbose=false) verbose && println("\n", validate ? "Validation" : "Check digit", " calculations for '$n':\n\n", " i nᵢ p[i,nᵢ] c\n------------------") # transform number list c, dig = 0, reverse(digits(validate ? n : 10 * n)) for i in length(dig):-1:1 ni = dig[i] p = permutationtable[(length(dig) - i) % 8 + 1, ni + 1] c = multiplicationtable[c + 1, p + 1] verbose && println(lpad(length(dig) - i, 2), " $ni $p $c") end verbose && !validate && println("\ninv($c) = $(inv[c + 1])")  !terse && println(validate ? "\nThe validation for '$n' is $(c == 0 ? "correct" : "incorrect")." : "\nThe check digit for '$n' is $(inv[c + 1]).") return validate ? c == 0 : inv[c + 1] end   for args in [(236, false, false, true), (2363, true, false, true), (2369, true, false, true), (12345, false, false, true), (123451, true, false, true), (123459, true, false, true), (123456789012, false, false), (1234567890120, true, false), (1234567890129, true, false)] verhoeffchecksum(args...) 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
#Clojure
Clojure
(ns org.rosettacode.clojure.vigenere (:require [clojure.string :as string]))   ; convert letter to offset from \A (defn to-num [char] (- (int char) (int \A)))   ; convert number to letter, treating it as modulo 26 offset from \A (defn from-num [num] (char (+ (mod num 26) (int \A))))   ; Convert a string to a sequence of just the letters as uppercase chars (defn to-normalized-seq [str] (map #'first (re-seq #"[A-Z]" (string/upper-case str))))   ; add (op=+) or subtract (op=-) the numerical value of the key letter from the ; text letter. (defn crypt1 [op text key] (from-num (apply op (list (to-num text) (to-num key)))))   (defn crypt [op text key] (let [xcrypt1 (partial #'crypt1 op)] (apply #'str (map xcrypt1 (to-normalized-seq text) (cycle (to-normalized-seq key))))))   ; encipher a text (defn encrypt [plaintext key] (crypt #'+ plaintext key))   ; decipher a text (defn decrypt [ciphertext key] (crypt #'- ciphertext key))
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.
#FreeBASIC
FreeBASIC
Dim Shared As Ubyte colores(4) => {7,13,14,3,2}   Sub showTree(n As Integer, A As String) Dim As Integer i, co = 0, b = 1, col Dim As String cs = Left(A, 1)   If cs = "" Then Exit Sub   Select Case cs Case "[" co += 1 : showTree(n + 1, Right(A, Len(A) - 1)) Exit Select Case "]" co -= 1 : showTree(n - 1, Right(A, Len(A) - 1)) Exit Select Case Else For i = 2 To n Print " "; co = n Next i Color colores(co) : Print !"\&hc0-"; cs showTree(n, Right(A, Len(A) - 1)) Exit Select End Select End Sub   Cls showTree(0, "[1[2[3][4[5][6]][7]][8[9]]]") Print !"\n\n\n" showTree(0, "[1[2[3[4]]][5[6][7[8][9]]]]") Sleep
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).
#Pascal
Pascal
{$H+}   program Walk;   uses SysUtils;   var Res: TSearchRec; Pattern, Path, Name: String; FileAttr: LongInt; Attr: Integer;   begin Write('File pattern: '); ReadLn(Pattern); { For example .\*.pas }   Attr := faAnyFile; if FindFirst(Pattern, Attr, Res) = 0 then begin Path := ExtractFileDir(Pattern); repeat Name := ConcatPaths([Path, Res.Name]); FileAttr := FileGetAttr(Name); if FileAttr and faDirectory = 0 then begin { Do something with file name } WriteLn(Name); end until FindNext(Res) <> 0; end; FindClose(Res); 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).
#Perl
Perl
use 5.010; opendir my $dh, '/home/foo/bar'; say for grep { /php$/ } readdir $dh; closedir $dh;
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis
Vigenère cipher/Cryptanalysis
Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text: MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS 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.
#Vlang
Vlang
import strings const encoded = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" + "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" + "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" + "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" + "ALWQC SNWBU 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 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, ]   fn sum(a []f64) f64 { mut s := 0.0 for f in a { s += f } return s }   fn best_match(a []f64) int { s := sum(a) mut best_fit, mut best_rotate := 1e100, 0 for rotate in 0..26 { mut fit := 0.0 for i in 0..26 { d := a[(i+rotate)%26]/s - freq[i] fit += d * d / freq[i] } if fit < best_fit { best_fit, best_rotate = fit, rotate } } return best_rotate }   fn freq_every_nth(msg []int, mut key []u8) f64 { l := msg.len interval := key.len mut out := []f64{len: 26} mut accu := []f64{len: 26} for j in 0..interval { for z in 0..26 { out[z] = 0.0 } for i := j; i < l; i += interval { out[msg[i]]++ } rot := best_match(out) key[j] = u8(rot + 65) for i := 0; i < 26; i++ { accu[i] += out[(i+rot)%26] } } s := sum(accu) mut ret := 0.0 for i := 0; i < 26; i++ { d := accu[i]/s - freq[i] ret += d * d / freq[i] } return ret }   fn decrypt(text string, key string) string { mut sb := strings.new_builder(128) mut ki := 0 for c in text { if c < 'A'[0] || c > 'Z'[0] { continue } ci := (c - key[ki] + 26) % 26 sb.write_rune(ci + 65) ki = (ki + 1) % key.len } return sb.str() }   fn main() { enc := encoded.replace(" ", "") mut txt := []int{len: enc.len} for i in 0..txt.len { txt[i] = int(enc[i] - 'A'[0]) } mut best_fit, mut best_key := 1e100, "" println(" Fit Length Key") for j := 1; j <= 26; j++ { mut key := []u8{len: j} fit := freq_every_nth(txt, mut key) s_key := key.bytestr() print("${fit:.6} ${j:2} $s_key") if fit < best_fit { best_fit, best_key = fit, s_key print(" <--- best so far") } println('') } println("\nBest key : $best_key") println("\nDecrypted text:\n${decrypt(enc, best_key)}") }
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.
#Wren
Wren
import "/math" for Nums import "/trait" for Stepped import "/str" for Char, Str import "/fmt" for Fmt   var encoded = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" + "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" + "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" + "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 = [ 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 ]   var bestMatch = Fn.new { |a| var sum = Nums.sum(a) var bestFit = 1e100 var bestRotate = 0 for (rotate in 0..25) { var fit = 0 for (i in 0..25) { var d = a[(i + rotate) % 26] / sum - freq[i] fit = fit + d * d / freq[i] } if (fit < bestFit) { bestFit = fit bestRotate = rotate } } return bestRotate }   var freqEveryNth = Fn.new { |msg, key| var len = msg.count var interval = key.count var out = List.filled(26, 0) var accu = List.filled(26, 0) for (j in 0...interval) { for (i in 0..25) out[i] = 0 for (i in Stepped.new(j...len, interval)) out[msg[i]] = out[msg[i]] + 1 var rot = bestMatch.call(out) key[j] = Char.fromCode(rot + 65) for (i in 0..25) accu[i] = accu[i] + out[(i + rot) % 26] } var sum = Nums.sum(accu) var ret = 0 for (i in 0..25) { var d = accu[i] / sum - freq[i] ret = ret + d * d / freq[i] } return ret }   var decrypt = Fn.new { |text, key| var sb = "" var ki = 0 for (c in text) { if (Char.isAsciiUpper(c)) { var ci = (c.bytes[0] - key[ki].bytes[0] + 26) % 26 sb = sb + Char.fromCode(ci + 65) ki = (ki + 1) % key.count } } return sb }   var enc = encoded.replace(" ", "") var txt = List.filled(enc.count, 0) for (i in 0...txt.count) txt[i] = Char.code(enc[i]) - 65 var bestFit = 1e100 var bestKey = "" var f = "$f $2d $s" System.print(" Fit Length Key") for (j in 1..26) { var key = List.filled(j, "") var fit = freqEveryNth.call(txt, key) var sKey = key.join("") Fmt.write(f, fit, j, sKey) if (fit < bestFit) { bestFit = fit bestKey = sKey System.write(" <--- best so far") } System.print() } System.print() System.print("Best key : %(bestKey)") System.print("\nDecrypted text:\n%(decrypt.call(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).
#GAP
GAP
Walk := function(name, op) local dir, file, e; dir := Directory(name); for e in SortedList(DirectoryContents(name)) do file := Filename(dir, e); if IsDirectoryPath(file) then if not (e in [".", ".."]) then Walk(file, op); fi; else op(file); fi; od; end;   # This will print filenames Walk(".", Display);
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).
#Go
Go
package main   import ( "fmt" "os" "path/filepath" )   func VisitFile(fp string, fi os.FileInfo, err error) error { if err != nil { fmt.Println(err) // can't walk here, return nil // but continue walking elsewhere } if fi.IsDir() { return nil // not a file. ignore. } matched, err := filepath.Match("*.mp3", fi.Name()) if err != nil { fmt.Println(err) // malformed pattern return err // this is fatal. } if matched { fmt.Println(fp) } return nil }   func main() { filepath.Walk("/", VisitFile) }
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.
#Haskell
Haskell
import Data.Vector.Unboxed (Vector) import qualified Data.Vector.Unboxed as V   waterCollected :: Vector Int -> Int waterCollected = V.sum . -- Sum of the water depths over each of V.filter (> 0) . -- the columns that are covered by some water. (V.zipWith (-) =<< -- Where coverages are differences between: (V.zipWith min . -- the lower water level in each case of: V.scanl1 max <*> -- highest wall to left, and V.scanr1 max)) -- highest wall to right.   main :: IO () main = mapM_ (print . waterCollected . V.fromList) [ [1, 5, 3, 7, 2] , [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] , [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1] , [5, 5, 5, 5] , [5, 6, 7, 8] , [8, 7, 7, 6] , [6, 7, 10, 7, 6] ]
http://rosettacode.org/wiki/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
#Go
Go
package main   import ( "fmt" "math" "math/rand" "time" )   // "given" func dice5() int { return rand.Intn(5) + 1 }   // function specified by task "Seven-sided dice from five-sided dice" func dice7() (i int) { for { i = 5*dice5() + dice5() if i < 27 { break } } return (i / 3) - 1 }   // function specified by task "Verify distribution uniformity/Naive" // // Parameter "f" is expected to return a random integer in the range 1..n. // (Values out of range will cause an unceremonious crash.) // "Max" is returned as an "indication of distribution achieved." // It is the maximum delta observed from the count representing a perfectly // uniform distribution. // Also returned is a boolean, true if "max" is less than threshold // parameter "delta." func distCheck(f func() int, n int, repeats int, delta float64) (max float64, flatEnough bool) { count := make([]int, n) for i := 0; i < repeats; i++ { count[f()-1]++ } expected := float64(repeats) / float64(n) for _, c := range count { max = math.Max(max, math.Abs(float64(c)-expected)) } return max, max < delta }   // Driver, produces output satisfying both tasks. func main() { rand.Seed(time.Now().UnixNano()) const calls = 1000000 max, flatEnough := distCheck(dice7, 7, calls, 500) fmt.Println("Max delta:", max, "Flat enough:", flatEnough) max, flatEnough = distCheck(dice7, 7, calls, 500) fmt.Println("Max delta:", max, "Flat enough:", flatEnough) }
http://rosettacode.org/wiki/Voronoi_diagram
Voronoi diagram
A Voronoi diagram is a diagram consisting of a number of sites. Each Voronoi site s also has a Voronoi cell consisting of all points closest to s. Task Demonstrate how to generate and display a Voroni diagram. See algo K-means++ clustering.
#Processing
Processing
void setup() { size(500, 500); generateVoronoiDiagram(width, height, 25); saveFrame("VoronoiDiagram.png"); }   void generateVoronoiDiagram(int w, int h, int num_cells) { int nx[] = new int[num_cells]; int ny[] = new int[num_cells]; int nr[] = new int[num_cells]; int ng[] = new int[num_cells]; int nb[] = new int[num_cells]; for (int n=0; n < num_cells; n++) { nx[n]=int(random(w)); ny[n]=int(random(h)); nr[n]=int(random(256)); ng[n]=int(random(256)); nb[n]=int(random(256)); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { float dmin = dist(0, 0, w - 1, h - 1); int j = -1; for (int i=0; i < num_cells; i++) { float d = dist(0, 0, nx[i] - x, ny[i] - y); if (d < dmin) { dmin = d; j = i; } } set(x, y, color(nr[j], ng[j], nb[j])); } } } }  
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce. Reference   an entry at the MathWorld website:   chi-squared distribution.
#D
D
import std.stdio, std.algorithm, std.mathspecial;   real x2Dist(T)(in T[] data) pure nothrow @safe @nogc { immutable avg = data.sum / data.length; immutable sqs = reduce!((a, b) => a + (b - avg) ^^ 2)(0.0L, data); return sqs / avg; }   real x2Prob(in real dof, in real distance) pure nothrow @safe @nogc { return gammaIncompleteCompl(dof / 2, distance / 2); }   bool x2IsUniform(T)(in T[] data, in real significance=0.05L) pure nothrow @safe @nogc { return x2Prob(data.length - 1.0L, x2Dist(data)) > significance; }   void main() { immutable dataSets = [[199809, 200665, 199607, 200270, 199649], [522573, 244456, 139979, 71531, 21461]]; writefln(" %4s %12s  %12s %8s  %s", "dof", "distance", "probability", "Uniform?", "dataset"); foreach (immutable ds; dataSets) { immutable dof = ds.length - 1; immutable dist = ds.x2Dist; immutable prob = x2Prob(dof, dist); writefln("%4d %12.3f  %12.8f  %5s  %6s", dof, dist, prob, ds.x2IsUniform ? "YES" : "NO", ds); } }
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at the time thought impossible with such a code. As the workings of the algorithm are clearly described in the linked Wikipedia article they will not be repeated here. Task Write routines, methods, procedures etc. in your language to generate a Verhoeff checksum digit for non-negative integers of any length and to validate the result. A combined routine is also acceptable. The more mathematically minded may prefer to generate the 3 tables required from the description provided rather than to hard-code them. Write your routines in such a way that they can optionally display digit by digit calculations as in the Wikipedia example. Use your routines to calculate check digits for the integers: 236, 12345 and 123456789012 and then validate them. Also attempt to validate the same integers if the check digits in all cases were 9 rather than what they actually are. Display digit by digit calculations for the first two integers but not for the third. Related task   Damm algorithm
#Nim
Nim
import strformat   const   D = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], [2, 3, 4, 0, 1, 7, 8, 9, 5, 6], [3, 4, 0, 1, 2, 8, 9, 5, 6, 7], [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], [5, 9, 8, 7, 6, 0, 4, 3, 2, 1], [6, 5, 9, 8, 7, 1, 0, 4, 3, 2], [7, 6, 5, 9, 8, 2, 1, 0, 4, 3], [8, 7, 6, 5, 9, 3, 2, 1, 0, 4], [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]]   Inv = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9]   P = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 5, 7, 6, 2, 8, 3, 0, 9, 4], [5, 8, 0, 3, 7, 9, 6, 1, 4, 2], [8, 9, 1, 6, 0, 4, 3, 5, 2, 7], [9, 4, 5, 3, 1, 2, 6, 8, 7, 0], [4, 2, 8, 6, 5, 7, 3, 9, 0, 1], [2, 7, 9, 3, 8, 0, 6, 4, 1, 5], [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]]   type Digit = 0..9   proc verhoeff[T: SomeInteger](n: T; validate, verbose = false): T = ## Compute or validate a check digit. ## Return the check digit if computation or the number with the check digit ## removed if validation. ## If not in verbose mode, an exception is raised if validation failed.   doAssert n >= 0, "Argument must not be negative."   # Extract digits. var digits: seq[Digit] if not validate: digits.add 0 var val = n while val != 0: digits.add val mod 10 val = val div 10   if verbose: echo if validate: &"Check digit validation for {n}:" else: &"Check digit computation for {n}:" echo " i ni p(i, ni) c"   # Compute c. var c = 0 for i, ni in digits: let p = P[i mod 8][ni] c = D[c][p] if verbose: echo &"{i:2} {ni} {p} {c}"   if validate: if verbose: let verb = if c == 0: "is" else: "is not" echo &"Validation {verb} successful.\n" elif c != 0: raise newException(ValueError, &"Check digit validation failed for {n}.") result = n div 10   else: result = Inv[c] if verbose: echo &"The check digit for {n} is {result}.\n"     for n in [236, 12345]: let d = verhoeff(n, false, true) discard verhoeff(10 * n + d, true, true) discard verhoeff(10 * n + 9, true, true)   let n = 123456789012 let d = verhoeff(n) echo &"Check digit for {n} is {d}." discard verhoeff(10 * n + d, true) echo &"Check digit validation was successful for {10 * n + d}." try: discard verhoeff(10 * n + 9, true) except ValueError: echo getCurrentExceptionMsg()
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at the time thought impossible with such a code. As the workings of the algorithm are clearly described in the linked Wikipedia article they will not be repeated here. Task Write routines, methods, procedures etc. in your language to generate a Verhoeff checksum digit for non-negative integers of any length and to validate the result. A combined routine is also acceptable. The more mathematically minded may prefer to generate the 3 tables required from the description provided rather than to hard-code them. Write your routines in such a way that they can optionally display digit by digit calculations as in the Wikipedia example. Use your routines to calculate check digits for the integers: 236, 12345 and 123456789012 and then validate them. Also attempt to validate the same integers if the check digits in all cases were 9 rather than what they actually are. Display digit by digit calculations for the first two integers but not for the third. Related task   Damm algorithm
#Perl
Perl
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Verhoeff_algorithm use warnings;   my @inv = qw(0 4 3 2 1 5 6 7 8 9);   my @d = map [ split ], split /\n/, <<END; 0 1 2 3 4 5 6 7 8 9 1 2 3 4 0 6 7 8 9 5 2 3 4 0 1 7 8 9 5 6 3 4 0 1 2 8 9 5 6 7 4 0 1 2 3 9 5 6 7 8 5 9 8 7 6 0 4 3 2 1 6 5 9 8 7 1 0 4 3 2 7 6 5 9 8 2 1 0 4 3 8 7 6 5 9 3 2 1 0 4 9 8 7 6 5 4 3 2 1 0 END   my @p = map [ split ], split /\n/, <<END; 0 1 2 3 4 5 6 7 8 9 1 5 7 6 2 8 3 0 9 4 5 8 0 3 7 9 6 1 4 2 8 9 1 6 0 4 3 5 2 7 9 4 5 3 1 2 6 8 7 0 4 2 8 6 5 7 3 9 0 1 2 7 9 3 8 0 6 4 1 5 7 0 4 6 9 1 3 2 5 8 END   my $debug;   sub generate { local $_ = shift() . 0; my $c = my $i = 0; my ($n, $p); $debug and print "i ni d(c,p(i%8,ni)) c\n"; while( length ) { $c = $d[ $c ][ $p = $p[ $i % 8 ][ $n = chop ] ]; $debug and printf "%d%3d%7d%10d\n", $i, $n, $p, $c; $i++; } return $inv[ $c ]; }   sub validate { shift =~ /(\d+)(\d)/ and $2 == generate($1) }   for ( 236, 12345, 123456789012 ) { print "testing $_\n"; $debug = length() < 6; my $checkdigit = generate($_); print "check digit for $_ is $checkdigit\n"; $debug = 0; for my $cd ( $checkdigit, 9 ) { print "$_$cd is ", validate($_ . $cd) ? '' : 'not ', "valid\n"; } print "\n"; }
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar cipher   Rot-13   Substitution Cipher
#CoffeeScript
CoffeeScript
# Simple helper since charCodeAt is quite long to write. code = (char) -> char.charCodeAt()   encrypt = (text, key) -> res = [] j = 0   for c in text.toUpperCase() continue if c < 'A' or c > 'Z'   res.push ((code c) + (code key[j]) - 130) % 26 + 65 j = ++j % key.length   String.fromCharCode res...   decrypt = (text, key) -> res = [] j = 0   for c in text.toUpperCase() continue if c < 'A' or c > 'Z'   res.push ((code c) - (code key[j]) + 26) % 26 + 65 j = ++j % key.length   String.fromCharCode res...   # Trying it out key = "VIGENERECIPHER" original = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!" encrypted = encrypt original, key   console.log "Original  : #{original}" console.log "Encrypted : #{encrypted}" console.log "Decrypted : #{decrypt encrypted, key}"
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.
#Go
Go
package main   import ( "encoding/json" "fmt" "log" )   type Node struct { Name string Children []*Node }   func main() { tree := &Node{"root", []*Node{ &Node{"a", []*Node{ &Node{"d", nil}, &Node{"e", []*Node{ &Node{"f", nil}, }}}}, &Node{"b", nil}, &Node{"c", nil}, }} b, err := json.MarshalIndent(tree, "", " ") if err != nil { log.Fatal(err) } fmt.Println(string(b)) }
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).
#Phix
Phix
puts(1,join(columnize(dir("*.txt"))[D_NAME],"\n"))
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. Note: Please be careful when running any code presented here. Related task   Walk Directory Tree   (read entire directory tree).
#PHP
PHP
$pattern = 'php'; $dh = opendir('c:/foo/bar'); // Or '/home/foo/bar' for Linux while (false !== ($file = readdir($dh))) { if ($file != '.' and $file != '..') { if (preg_match("/$pattern/", $file)) { echo "$file matches $pattern\n"; } } } closedir($dh);
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis
Vigenère cipher/Cryptanalysis
Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text: MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS 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.
#zkl
zkl
var[const] uppercase=["A".."Z"].pump(String), english_frequences=T( // A..Z 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074);   fcn vigenere_decrypt(target_freqs, input){ // ( (float,...), string) nchars,ordA  :=uppercase.len(),"A".toAsc(); sorted_targets:=target_freqs.sort();   frequency:='wrap(input){ // (n,n,n,n,...), n is ASCII index ("A"==65) result:=uppercase.pump(List(),List.fp1(0)); // ( ("A",0),("B",0) ...) foreach c in (input){ result[c - ordA][1] += 1 } result // --> mutable list of mutable lists ( ("A",Int)...("Z",Int) ) }; correlation:='wrap(input){ // (n,n,n,n,...), n is ASCII index ("A"==65) result,freq:=0.0, frequency(input); freq.sort(fcn([(_,a)],[(_,b)]){ a<b }); // sort letters by frequency foreach i,f in (freq.enumerate()){ result+=sorted_targets[i]*f[1] } result // -->Float };   cleaned:=input.toUpper().pump(List,uppercase.holds,Void.Filter,"toAsc");   best_len,best_corr := 0,-100.0; # Assume that if there are less than 20 characters # per column, the key's too long to guess foreach i in ([2..cleaned.len()/20]){ pieces:=(i).pump(List,List.copy); // ( (),() ... ) foreach c in (cleaned){ pieces[__cWalker.idx%i].append(c) }   # The correlation seems to increase for smaller # pieces/longer keys, so weigh against them a little corr:=-0.5*i + pieces.apply(correlation).sum(0.0); if(corr>best_corr) best_len,best_corr=i,corr; } if(best_len==0) return("Text is too short to analyze", "");   pieces:=best_len.pump(List,List.copy); foreach c in (cleaned){ pieces[__cWalker.idx%best_len].append(c) }   key,freqs := "",pieces.apply(frequency); foreach fr in (freqs){ fr.sort(fcn([(_,a)],[(_,b)]){ a>b }); // reverse sort by freq m,max_corr := 0,0.0; foreach j in (nchars){ corr,c := 0.0,ordA + j; foreach frc in (fr){ d:=(frc[0].toAsc() - c + nchars) % nchars; corr+=target_freqs[d]*frc[1]; if(corr>max_corr) m,max_corr=j,corr; } } key+=(m + ordA).toChar(); }   cleaned.enumerate().apply('wrap([(i,c])){ ( (c - (key[i%best_len]).toAsc() + nchars)%nchars + ordA ).toChar() }).concat() : T(key,_); }