task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #C.2B.2B | C++ |
#include <windows.h>
#include <vector>
#include <string>
using namespace std;
//////////////////////////////////////////////////////
struct Point {
int x, y;
};
//////////////////////////////////////////////////////
class MyBitmap {
public:
MyBitmap() : pen_(nullptr) {}
~MyBitmap() {
DeleteObject(pen... |
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 ... | #11l | 11l | T Node
String value
Node? left
Node? right
F (value, Node? left = N, Node? right = N)
.value = String(value)
.left = left
.right = right
F tree_indent() -> [String]
V tr = I .right != N {.right.tree_indent()} E [‘-- (null)’]
R [‘--’(.value)] [+] (I .left != N {.left.tree... |
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours ... | #Sidef | Sidef | var costs = :(
W => :(A => 16, B => 16, C => 13, D => 22, E => 17),
X => :(A => 14, B => 14, C => 13, D => 19, E => 15),
Y => :(A => 19, B => 19, C => 20, D => 23, E => 50),
Z => :(A => 50, B => 12, C => 50, D => 15, E => 11)
)
var demand = :(A => 30, B => 20, C => 70, D => 30, E => 60)
var supply = :... |
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.
... | #F.23 | F# | System.IO.Directory.GetFiles("c:\\temp", "*.xml")
|> Array.iter (printfn "%s") |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
... | #Factor | Factor | USING: globs io io.directories kernel regexp sequences ;
IN: walk-directory-non-recursively
: print-files ( path pattern -- )
[ directory-files ] [ <glob> ] bi* [ matches? ] curry filter
[ print ] each ; |
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ██ 9 ██
8 ██ 8 ██
7 ██ ... | #AppleScript | AppleScript | --------------- WATER COLLECTED BETWEEN TOWERS -------------
-- waterCollected :: [Int] -> Int
on waterCollected(xs)
set leftWalls to scanl1(my max, xs)
set rightWalls to scanr1(my max, xs)
set waterLevels to zipWith(my min, leftWalls, rightWalls)
-- positive :: Num a => a -> Bool
script posit... |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #D | D | import std.random, std.algorithm, std.range, bitmap;
struct Point { uint x, y; }
enum randomPoints = (in size_t nPoints, in size_t nx, in size_t ny) =>
nPoints.iota
.map!((int) => Point(uniform(0, nx), uniform(0, ny)))
.array;
Image!RGB generateVoronoi(in Point[] pts,
in size... |
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 ... | #Ada | Ada | with Ada.Text_IO, Ada.Directories;
procedure Directory_Tree is
procedure Print_Tree(Current: String; Indention: Natural := 0) is
function Spaces(N: Natural) return String is
(if N= 0 then "" else " " & Spaces(N-1));
use Ada.Directories;
Search: Search_Type;
Found: Directory_Entry_T... |
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours ... | #Tcl | Tcl | package require Tcl 8.6
# A sort that works by sorting by an auxiliary key computed by a lambda term
proc sortByFunction {list lambda} {
lmap k [lsort -index 1 [lmap k $list {
list $k [uplevel 1 [list apply $lambda $k]]
}]] {lindex $k 0}
}
# A simple way to pick a “best” item from a list
proc minimax {list... |
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.
... | #Forth | Forth | defer ls-filter ( name len -- ? )
: ls-all 2drop true ;
: ls-visible drop c@ [char] . <> ;
: ls ( dir len -- )
open-dir throw ( dirid )
begin
dup pad 256 rot read-dir throw
while
pad over ls-filter if
cr pad swap type
else drop then
repeat
drop close-dir throw ;
\ only show C language... |
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.
... | #FreeBASIC | FreeBASIC |
Sub show (pattern As String)
Dim As String f = Dir$(pattern)
While Len(f)
Print f
f = Dir$
Wend
End Sub
show "*.*"
Sleep
|
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis | Vigenère cipher/Cryptanalysis | Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text:
MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH
VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS... | #11l | 11l | -V ascii_uppercase = Array(‘A’..‘Z’)
F vigenere_decrypt(target_freqs, input)
V nchars = :ascii_uppercase.len
V ordA = ‘A’.code
V sorted_targets = sorted(target_freqs)
F frequency(input)
V result = :ascii_uppercase.map(c -> (c, 0.0))
L(c) input
result[c - @ordA][1]++
R result
... |
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 ... | #11l | 11l | L(filename) fs:walk_dir(‘/’)
I re:‘.*\.mp3’.match(filename)
print(filename) |
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ██ 9 ██
8 ██ 8 ██
7 ██ ... | #AutoHotkey | AutoHotkey | WCBT(oTwr){
topL := Max(oTwr*), l := num := 0, barCh := lbarCh := "", oLvl := []
while (++l <= topL)
for t, h in oTwr
oLvl[l,t] := h ? "██" : "≈≈" , oTwr[t] := oTwr[t]>0 ? oTwr[t]-1 : 0
for l, obj in oLvl{
while (oLvl[l, A_Index] = "≈≈")
oLvl[l, A_Index] := " "
while (oLvl[l, obj.Count() +1 - A_Index] =... |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #Delphi | Delphi |
uses System.Generics.Collections;
procedure TForm1.Voronoi;
const
p = 3;
cells = 100;
size = 1000;
var
aCanvas : TCanvas;
px, py: array of integer;
color: array of Tcolor;
Img: TBitmap;
lastColor:Integer;
auxList: TList<TPoint>;
poligonlist : TDictionary<integer,TList<TPoint>>;
pointarray... |
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 ... | #ALGOL_68 | ALGOL 68 | # outputs nested html tables to visualise a tree #
# mode representing nodes of the tree #
MODE NODE = STRUCT( STRING value, REF NODE child, REF NODE sibling );
REF NODE nil node = NIL;
# tags etc. #
STRING table = "<table border=""1"" cellspacing=""4"">"
, elbat = "</table>"
, tr = "<tr>"
, rt ... |
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours ... | #Wren | Wren | import "/math" for Int, Nums
import "/fmt" for Fmt
var supply = [50, 60, 50, 50]
var demand = [30, 20, 70, 30, 60]
var costs = [
[16, 16, 13, 22, 17],
[14, 14, 13, 19, 15],
[19, 19, 20, 23, 50],
[50, 12, 50, 15, 11]
]
var nRows = supply.count
var nCols = demand.count
var rowDone = List.filled(nR... |
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.
... | #Frink | Frink | for f = select[files["."], {|f1| f1.getName[] =~ %r/\.frink$/}]
println[f.getName[]] |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
... | #Gambas | Gambas | Public Sub Main()
Dim sTemp As String
For Each sTemp In Dir("/etc", "*.d")
Print sTemp
Next
End |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis | Vigenère cipher/Cryptanalysis | Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text:
MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH
VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS... | #Ada | Ada | with Ada.Text_IO;
procedure Vignere_Cryptanalysis is
subtype Letter is Character range 'A' .. 'Z';
function "+"(X, Y: Letter) return Letter is
begin
return Character'Val( ( (Character'Pos(X)-Character'Pos('A'))
+ (Character'Pos(Y)-Character'Pos('A')) ) mod 26
... |
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 ... | #8th | 8th |
"*.c" f:rglob \ top of stack now has list of all "*.c" files, recursively
|
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Walk a directory/Non-recursively ... | #Ada | Ada | with Ada.Directories; use Ada.Directories;
with Ada.Text_IO;
procedure Test_Directory_Walk is
procedure Walk (Name : String; Pattern : String) is
procedure Print (Item : Directory_Entry_Type) is
begin
Ada.Text_IO.Put_Line (Full_Name (Item));
end Print;
procedure Walk (Item : Direc... |
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 ██ ... | #AWK | AWK |
# syntax: GAWK -f WATER_COLLECTED_BETWEEN_TOWERS.AWK [-v debug={0|1}]
BEGIN {
wcbt("1,5,3,7,2")
wcbt("5,3,7,2,6,4,5,9,1,2")
wcbt("2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1")
wcbt("5,5,5,5")
wcbt("5,6,7,8")
wcbt("8,7,7,6")
wcbt("6,7,10,7,6")
exit(0)
}
function wcbt(str, ans,hl,hr,i,n,tower) {
... |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #FreeBASIC | FreeBASIC | Dim Shared As Integer ancho = 500, alto = 500
Screenres ancho, alto, 8
Cls
Randomize Timer
Function hypot(a As Integer, b As Integer) As Double
Return Sqr(a^2 + b^2)
End Function
Sub Generar_Diagrama_Voronoi(ancho As Integer, alto As Integer, num_celdas As Integer)
Dim As Integer nx(num_celdas), ny(num_celd... |
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 ... | #AppleScript | AppleScript | -- Vertically centered textual tree using UTF8 monospaced
-- box-drawing characters, with options for compacting
-- and pruning.
-- ┌── Gamma
-- ┌─ Beta ┼── Delta
-- │ └ Epsilon
-- Alpha ┼─ Zeta ───── Eta
-- │ ┌─── Iota
-- └ Theta ┼── Kappa
-- └─ L... |
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours ... | #Yabasic | Yabasic |
N_ROWS = 4 : N_COLS = 5
dim supply(N_ROWS)
dim demand(N_COLS)
restore sup
for n = 0 to N_ROWS - 1
read supply(n)
next n
restore dem
for n = 0 to N_COLS - 1
read demand(n)
next n
label sup
data 50, 60, 50, 50
label dem
data 30, 20, 70, 30, 60
dim costs(N_ROWS, N_COLS)
label cost
data 16, 16, 13, 22, 17... |
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.
... | #Go | Go | package main
import (
"fmt"
"path/filepath"
)
func main() {
fmt.Println(filepath.Glob("*.go"))
} |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
... | #Groovy | Groovy | // *** print *.txt files in current directory
new File('.').eachFileMatch(~/.*\.txt/) {
println it
}
// *** print *.txt files in /foo/bar
new File('/foo/bar').eachFileMatch(~/.*\.txt/) {
println it
} |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis | Vigenère cipher/Cryptanalysis | Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text:
MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH
VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
const char *encoded =
"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH"
"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD"
"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS"
... |
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 ... | #ALGOL_68 | ALGOL 68 | INT match=0, no match=1, out of memory error=2, other error=3;
STRING slash = "/", pwd=".", parent="..";
PROC walk tree = (STRING path, PROC (STRING)VOID call back)VOID: (
[]STRING files = get directory(path);
FOR file index TO UPB files DO
STRING file = files[file index];
STRING path file = path+slash+... |
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 ██ ... | #BASIC | BASIC | 10 DEFINT A-Z: DIM T(20): K=0
20 K=K+1: READ N: IF N=0 THEN END
30 FOR I=0 TO N-1: READ T(I): NEXT
40 W=0
50 FOR R=N-1 TO 0 STEP -1: IF T(R)=0 THEN NEXT ELSE IF R=0 THEN 110
60 B=0
70 FOR C=0 TO R
80 IF T(C)>0 THEN T(C)=T(C)-1: B=B+1 ELSE IF B>0 THEN W=W+1
90 NEXT
100 IF B>1 THEN 50
110 PRINT "Block";K;"holds";W;"water... |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #Go | Go | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math/rand"
"os"
"time"
)
const (
imageWidth = 300
imageHeight = 200
nSites = 10
)
func main() {
writePngFile(generateVoronoi(randomSites()))
}
func generateVoronoi(sx, sy []int) imag... |
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 ... | #Batch_File | Batch File | @tree %cd% |
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours ... | #zkl | zkl | costs:=Dictionary(
"W",Dictionary("A",16, "B",16, "C",13, "D",22, "E",17),
"X",Dictionary("A",14, "B",14, "C",13, "D",19, "E",15),
"Y",Dictionary("A",19, "B",19, "C",20, "D",23, "E",50),
"Z",Dictionary("A",50, "B",12, "C",50, "D",15, "E",11)).makeReadOnly();
demand:=Dictionary("A",30, "B",20, "C",70, "D",30... |
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.
... | #Hare | Hare | use fmt;
use glob;
export fn main() void = {
ls("/etc/*.conf");
};
fn ls(pattern: str) void = {
let gen = glob::glob(pattern, glob::flags::NONE);
defer glob::finish(&gen);
for (true) match (glob::next(&gen)) {
case void =>
break;
case glob::failure =>
continue;
case let s: str =>
fmt::printfln("{}", s)... |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
... | #Haskell | Haskell | import System.Directory
import Text.Regex
import Data.Maybe
walk :: FilePath -> String -> IO ()
walk dir pattern = do
filenames <- getDirectoryContents dir
mapM_ putStrLn $ filter (isJust.(matchRegex $ mkRegex pattern)) filenames
main = walk "." ".\\.hs$" |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis | Vigenère cipher/Cryptanalysis | Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text:
MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH
VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS... | #C.2B.2B | C++ | #include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <array>
using namespace std;
typedef array<pair<char, double>, 26> FreqArray;
class VigenereAnalyser
{
private:
array<double, 26> targets;
array<double, 26> sortedTargets;
FreqArray freq;
// Update the fr... |
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 ... | #Arturo | Arturo | ; list all files at current path
print list.recursive "."
; get all files at given path
; and select only the ones we want
; just select the files with .md extension
select list.recursive "some/path"
=> [".md" = extract.extension]
; just select the files that contain "test"
select list.recursive "some/path" ... |
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 ... | #AutoHotkey | AutoHotkey | Loop, %A_Temp%\*.tmp,,1
out .= A_LoopFileName "`n"
MsgBox,% out |
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ██ 9 ██
8 ██ 8 ██
7 ██ ... | #C | C |
#include<stdlib.h>
#include<stdio.h>
int getWater(int* arr,int start,int end,int cutoff){
int i, sum = 0;
for(i=start;i<=end;i++)
sum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);
return sum;
}
int netWater(int* arr,int size){
int i, j, ref1, ref2, marker, markerSet = 0,sum = 0;
if(size<3)
... |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #Haskell | Haskell |
-- Compile with: ghc -O2 -fllvm -fforce-recomp -threaded --make
{-# LANGUAGE BangPatterns #-}
module Main where
import System.Random
import Data.Word
import Data.Array.Repa as Repa
import Data.Array.Repa.IO.BMP
{-# INLINE sqDistance #-}
sqDistance :: Word32 -> Word32 -> Word32 -> Word32 -> Word32
sqDistance... |
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 ... | #11l | 11l | F encrypt(key, text)
V out = ‘’
V j = 0
L(c) text
I !c.is_alpha()
L.continue
out ‘’= Char(code' (c.uppercase().code + key[j].code - 2 * ‘A’.code) % 26 + ‘A’.code)
j = (j + 1) % key.len
R out
F decrypt(key, text)
V out = ‘’
V j = 0
L(c) text
I !c.is_alpha()
... |
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 ... | #BBC_BASIC | BBC BASIC | INSTALL @lib$+"WINLIB5"
ON ERROR SYS "MessageBox", @hwnd%, REPORT$, 0, 0 : QUIT
REM!WC Windows constants:
TVI_SORT = -65533
TVIF_TEXT = 1
TVM_INSERTITEM = 4352
TVS_HASBUTTONS = 1
TVS_HASLINES = 2
TVS_LINESATROOT = 4
REM. TV_INSERTSTRUCT
DIM tvi{hPare... |
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.
... | #HicEst | HicEst | CHARACTER dirtxt='dir.txt', filename*80
SYSTEM(DIR='*.*', FIle=dirtxt) ! "file names", length, attrib, Created, LastWrite, LastAccess
OPEN(FIle=dirtxt, Format='"",', LENgth=files) ! parses column 1 ("file names")
DO nr = 1, files
filename = dirtxt(nr,1) ! reads dirtxt row = nr, column = 1 to filename
! write fi... |
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.
... | #Icon_and_Unicon | Icon and Unicon | procedure main()
every write(getdirs(".","icn")) # writes out all directories from the current directory down
end
procedure getdirs(s,pat) #: return a list of directories beneath the directory 's'
local d,f
if ( stat(s).mode ? ="d" ) & ( d := open(s) ) then {
while f := read(d) do
if find(pat,f) t... |
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... | #D | D | import std.stdio, std.algorithm, std.typecons, std.string,
std.array, std.numeric, std.ascii;
string[2] vigenereDecrypt(in double[] targetFreqs, in string input) {
enum nAlpha = std.ascii.uppercase.length;
static double correlation(in string txt, in double[] sTargets)
pure nothrow /*@safe*/ @nogc... |
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 ... | #BaCon | BaCon | PRINT WALK$(".", 1, ".+", TRUE, NL$) |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Walk a directory/Non-recursively ... | #Batch_File | Batch File | dir /s /b "%windir%\System32\*.exe" |
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ██ 9 ██
8 ██ 8 ██
7 ██ ... | #C.23 | C# | class Program
{
static void Main(string[] args)
{
int[][] wta = {
new int[] {1, 5, 3, 7, 2}, new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },
new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },
new int[] { 5, 5, 5, 5 }, new int[] { 5, 6, 7, 8 },
... |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #Icon_and_Unicon | Icon and Unicon | link graphics,printf,strings
record site(x,y,colour) # site data position and colour
invocable all # needed for string metrics
procedure main(A) # voronoi
&window := open("Voronoi","g","bg=black") | stop("Unable to open window")
WAttrib("canvas=hidden") # figure out maximal size width & height... |
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 ... | #Action.21 | Action! | PROC Fix(CHAR ARRAY in,fixed)
INT i
CHAR c
fixed(0)=0
FOR i=1 TO in(0)
DO
c=in(i)
IF c>='a AND c<='z THEN
c==-('a-'A)
FI
IF c>='A AND c<='Z THEN
fixed(0)==+1
fixed(fixed(0))=c
FI
OD
RETURN
PROC Process(CHAR ARRAY in,key,out INT dir)
CHAR ARRAY inFixed(256),keyFixe... |
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 ... | #C | C | #include <stdio.h>
#include <stdlib.h>
typedef struct stem_t *stem;
struct stem_t { const char *str; stem next; };
void tree(int root, stem head)
{
static const char *sdown = " |", *slast = " `", *snone = " ";
struct stem_t col = {0, 0}, *tail;
for (tail = head; tail; tail = tail->next) {
printf("%s", ta... |
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.
... | #IDL | IDL | f = file_search('*.txt', count=cc)
if cc gt 0 then print,f |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
... | #J | J | require 'dir'
0 dir '*.png'
0 dir '/mydir/*.txt' |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis | Vigenère cipher/Cryptanalysis | Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text:
MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH
VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS... | #Go | Go | package main
import (
"fmt"
"strings"
)
var encoded =
"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" +
"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" +
"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" +
"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VO... |
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 ... | #BBC_BASIC | BBC BASIC | directory$ = "C:\Windows\"
pattern$ = "*.chm"
PROClisttree(directory$, pattern$)
END
DEF PROClisttree(dir$, filter$)
LOCAL dir%, sh%, res%
DIM dir% LOCAL 317
IF RIGHT$(dir$) <> "\" IF RIGHT$(dir$) <> "/" dir$ += "\"
SYS "FindFirstFile", dir$ + filter$, dir% TO sh%... |
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 ... | #C | C | #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEF... |
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 ██ ... | #C.2B.2B | C++ |
#include <iostream>
#include <vector>
#include <algorithm>
enum { EMPTY, WALL, WATER };
auto fill(const std::vector<int> b) {
auto water = 0;
const auto rows = *std::max_element(std::begin(b), std::end(b));
const auto cols = std::size(b);
std::vector<std::vector<int>> g(rows);
for (auto& r : g) {
fo... |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #J | J | NB. (number of points) voronoi (shape)
NB. Generates an array of indices of the nearest point
voronoi =: 4 :0
p =. (x,2) ?@$ y
(i.<./)@:(+/@:*:@:-"1&p)"1 ,"0/&i./ y
)
load'viewmat'
viewmat 25 voronoi 500 500 |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a Vigenère cypher, both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Caesar ... | #Ada | Ada | WITH Ada.Text_IO, Ada.Characters.Handling;
USE Ada.Text_IO, Ada.Characters.Handling;
PROCEDURE Main IS
SUBTYPE Alpha IS Character RANGE 'A' .. 'Z';
TYPE Ring IS MOD (Alpha'Range_length);
TYPE Seq IS ARRAY (Integer RANGE <>) OF Ring;
FUNCTION "+" (S, Key : Seq) RETURN Seq IS
R : Seq (S'Range);
B... |
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 ... | #C.2B.2B | C++ | #include <functional>
#include <iostream>
#include <random>
class BinarySearchTree {
private:
struct Node {
int key;
Node *left, *right;
Node(int k) : key(k), left(nullptr), right(nullptr) {
//empty
}
} *root;
public:
BinarySearchTree() : root(nullptr) {
... |
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.
... | #Java | Java | File dir = new File("/foo/bar");
String[] contents = dir.list();
for (String file : contents)
if (file.endsWith(".mp3"))
System.out.println(file); |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
... | #JavaScript | JavaScript | var fso = new ActiveXObject("Scripting.FileSystemObject");
var dir = fso.GetFolder('test_folder');
function walkDirectory(dir, re_pattern) {
WScript.Echo("Files in " + dir.name + " matching '" + re_pattern +"':");
walkDirectoryFilter(dir.Files, re_pattern);
WScript.Echo("Folders in " + dir.name + " matc... |
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... | #Haskell | Haskell | {-# LANGUAGE TupleSections #-}
import Data.List(transpose, nub, sort, maximumBy)
import Data.Ord (comparing)
import Data.Char (ord)
import Data.Map (Map, fromListWith, toList, findWithDefault)
average :: Fractional a => [a] -> a
average as = sum as / fromIntegral (length as)
-- Create a map from each entry in list ... |
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 ... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RosettaRecursiveDirectory
{
class Program
{
static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)
{
var directoryStack = new Stack<DirectoryInfo>();... |
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 ██ ... | #Clojure | Clojure |
(defn trapped-water [towers]
(let [maxes #(reductions max %) ; the seq of increasing max values found in the input seq
maxl (maxes towers) ; the seq of max heights to the left of each tower
maxr (reverse (maxes (reverse towers))) ; the seq of max heights to the r... |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times ... | #11l | 11l | F dice5()
R random:(1..5)
F distcheck(func, repeats, delta)
V bin = DefaultDict[Int, Int]()
L 1..repeats
bin[func()]++
V target = repeats I/ bin.len
V deltacount = Int(delta / 100.0 * target)
assert(all(bin.values().map(count -> abs(@target - count) < @deltacount)), ‘Bin distribution skewed fr... |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #Java | Java | import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Voronoi extends JFrame {
... |
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 ... | #ALGOL_68 | ALGOL 68 | STRING key := "";
PROC vigenere cipher = (REF STRING key)VOID:
(
FOR i FROM LWB key TO UPB key DO
IF key[i] >= "A" AND key[i] <= "Z" THEN
key +:= key[i] FI;
IF key[i] >= "a" AND key[i] <= "z" THEN
key +:= REPR(ABS key[i] + ABS"A" - ABS"a") FI
OD
);
PROC encrypt = (STRING text)STRING:
(
STR... |
http://rosettacode.org/wiki/Visualize_a_tree | Visualize a tree | A tree structure (i.e. a rooted, connected acyclic graph) is often used in programming.
It's often helpful to visually examine such a structure.
There are many ways to represent trees to a reader, such as:
indented text (à la unix tree command)
nested HTML tables
hierarchical GUI widgets
2D or ... | #C.23 | C# | using System;
public static class VisualizeTree
{
public static void Main() {
"A".t(
"B0".t(
"C1",
"C2".t(
"D".t("E1", "E2", "E3")),
"C3".t(
"F1",
"F2",
"F3".t("G"),
... |
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.
... | #Julia | Julia | for filename in readdir("/foo/bar")
if endswith(filename, ".mp3")
print(filename)
end
end |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
... | #Kotlin | Kotlin | // version 1.1.2
import java.io.File
fun walkDirectory(dirPath: String, pattern: Regex): List<String> {
val d = File(dirPath)
require(d.exists() && d.isDirectory())
return d.list().filter { it.matches(pattern) }
}
fun main(args: Array<String>) {
val r = Regex("""^a.*\.h$""") // get all C header f... |
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... | #Java | Java | public class Vig{
static String encodedMessage =
"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG ALWQC SNWBU BYHCU HKOCE XJ... |
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 ... | #C.2B.2B | C++ | #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir("."); //
boost::regex pattern("a.*"); // list all files starting with a
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
... |
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 ... | #Cach.C3.A9_ObjectScript | Caché ObjectScript |
Class Utils.File [ Abstract ]
{
ClassMethod WalkTree(pDir As %String = "", pMask As %String = "*.*") As %Status
{
// do some validation
If pDir="" Quit $$$ERROR($$$GeneralError, "No directory specified.")
// search input directory for files matching wildcard
Set fs=##class(%ResultSet).%New("%File.FileSet")
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 ██ ... | #CLU | CLU | max = proc [T: type] (a,b: T) returns (T)
where T has lt: proctype (T,T) returns (bool)
if a<b then return(b)
else return(a)
end
end max
% based on: https://stackoverflow.com/a/42821623
water = proc (towers: sequence[int]) returns (int)
si = sequence[int]
w: int := 0
left: int := 1
... |
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 ... | #Ada | Ada | with Ada.Numerics.Discrete_Random, Ada.Text_IO;
procedure Naive_Random is
type M_1000 is mod 1000;
package Rand is new Ada.Numerics.Discrete_Random(M_1000);
Gen: Rand.Generator;
procedure Perform(Modulus: Positive; Expected, Margin: Natural;
Passed: out boolean) is
Low: Natu... |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #JavaScript | JavaScript | <!-- VoronoiD.html -->
<html>
<head><title>Voronoi diagram</title>
<script>
// HF#1 Like in PARI/GP: return random number 0..max-1
function randgp(max) {return Math.floor(Math.random()*max)}
// HF#2 Random hex color
function randhclr() {
return "#"+
("00"+randgp(256).toString(16)).slice(-2)+
("00"+randgp(256).toS... |
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 ... | #Applesoft_BASIC | Applesoft BASIC |
100 :
110 REM VIGENERE CIPHER
120 :
200 REM SET-UP
210 K$ = "LEMON": PRINT "KEY: "; K$
220 PT$ = "ATTACK AT DAWN": PRINT "PLAIN TEXT: ";PT$
230 DEF FN MOD(A) = A - INT (A / 26) * 26
300 REM ENCODING
310 K = 1
320 FOR I = 1 TO LEN (PT$)
330 IF ASC ( MID$ (PT$,I,1)) < 65
OR 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 ... | #Arturo | Arturo | Letters: append `A`..`Z` `a`..`z`
encrypt: function [msg, key][
pos: 0
result: new ""
loop msg 'c ->
if in? c Letters [
'result ++ to :char (((to :integer key\[pos]) + to :integer upper c) % 26) + to :integer `A`
pos: (pos + 1) % size key
]
return result
]
decry... |
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 ... | #Clojure | Clojure | (use 'vijual)
(draw-tree [[:A] [:B] [:C [:D [:E] [:F]] [:G]]])
|
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
... | #Lasso | Lasso | local(matchingfilenames = array)
dir('.') -> foreach => {#1 >> 'string' ? #matchingfilenames -> insert(#1)}
#matchingfilenames |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
... | #Lingo | Lingo | -- Usage: printFiles("C:\scripts", ".ls")
on printFiles (dir, fileType)
i = 1
sub = fileType.length -1
repeat while TRUE
fn = getNthFileNameInFolder(dir, i)
if fn = EMPTY then exit repeat
i = i+1
if fn.length<fileType.length then next repeat
if fn.char[fn.length-sub..fn.length]=fileType then ... |
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... | #Julia | Julia | # ciphertext block {{{1
const ciphertext = filter(isalpha, """
MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH
VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD
ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS
FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG
ALWQC SNWBU BYHCU... |
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... | #Kotlin | Kotlin | // version 1.1.3
val encoded =
"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" +
"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" +
"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" +
"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" +
"ALWQC SNW... |
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 ... | #Clojure | Clojure | (use '[clojure.java.io])
(defn walk [dirpath pattern]
(doall (filter #(re-matches pattern (.getName %))
(file-seq (file dirpath)))))
(map #(println (.getPath %)) (walk "src" #".*\.clj"))
|
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Walk a directory/Non-recursively ... | #CoffeeScript | CoffeeScript | fs = require 'fs'
walk = (dir, f_match, f_visit) ->
_walk = (dir) ->
fns = fs.readdirSync dir
for fn in fns
fn = dir + '/' + fn
if f_match fn
f_visit fn
if fs.statSync(fn).isDirectory()
_walk fn
_walk(dir)
dir = '..'
matcher = (fn) -> fn.match /\.coffee/
action = consol... |
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 ██ ... | #Cowgol | Cowgol | include "cowgol.coh";
include "argv.coh";
# Count the amount of water in a given array
sub water(towers: [uint8], length: intptr): (units: uint8) is
units := 0;
loop
var right := towers + length;
loop
right := @prev right;
if right < towers or [right] != 0 then
... |
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 ... | #AutoHotkey | AutoHotkey | MsgBox, % DistCheck("dice7",10000,3)
DistCheck(function, repetitions, delta)
{ Loop, % 7 ; initialize array
{ bucket%A_Index% := 0
}
Loop, % repetitions ; populate buckets
{ v := %function%()
bucket%v% += 1
}
lbnd := round((repetitions/7)*(100-delta)/100)
ubnd := round((repetitions/7... |
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 ... | #BBC_BASIC | BBC BASIC | MAXRND = 7
FOR r% = 2 TO 5
check% = FNdistcheck(FNdice5, 10^r%, 0.05)
PRINT "Over "; 10^r% " runs dice5 ";
IF check% THEN
PRINT "failed distribution check with "; check% " bin(s) out of range"
ELSE
PRINT "passed distribution check"
ENDIF
NEXT... |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #Julia | Julia |
using Images
function voronoi(w, h, n_centroids)
dist = (point,vector) -> sqrt.((point[1].-vector[:,1]).^2 .+ (point[2].-vector[:,2]).^2)
dots = [rand(1:h, n_centroids) rand(1:w, n_centroids) rand(RGB{N0f8}, n_centroids)]
img = zeros(RGB{N0f8}, h, w)
for x in 1:h, y in 1:w
distances = dist([x... |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #Kotlin | Kotlin | // version 1.1.3
import java.awt.Color
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.geom.Ellipse2D
import java.awt.image.BufferedImage
import java.util.Random
import javax.swing.JFrame
fun distSq(x1: Int, x2: Int, y1: Int, y2: Int): Int {
val x = x1 - x2
val y = y1 - y2
return x *... |
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 ... | #AutoHotkey | AutoHotkey | Key = VIGENERECIPHER
Text= Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
out := "Input =" text "`nkey =" key "`nCiphertext =" (c := VigenereCipher(Text, Key)) "`nDecrypted =" VigenereDecipher(c, key)
MsgBox % clipboard := out
VigenereCipher(Text, Key){
StringUpper, Text, T... |
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 ... | #Common_Lisp | Common Lisp | (defun visualize (tree)
(labels
((rprint (list)
(mapc #'princ (reverse list)))
(vis-h (tree branches)
(let ((len (length tree)))
(loop
for item in tree
for idx from 1 to len do
(cond
((listp item)
... |
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.
... | #LiveCode | LiveCode | set the defaultFolder to the documents folder -- the documents folder is a "specialFolderPath"
put the files into docfiles
filter docfiles with "*.txt"
put docfiles |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
... | #Lua | Lua | require "lfs"
directorypath = "." -- current working directory
for filename in lfs.dir(directorypath) do
if filename:match("%.lua$") then -- "%." is an escaped ".", "$" is end of string
print(filename)
end
end |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis | Vigenère cipher/Cryptanalysis | Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text:
MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH
VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS... | #Nim | Nim | import sequtils, strutils, sugar, tables, times
const
CipherText = """MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH
VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD
ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS
FGRPH JOOF... |
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... | #OCaml | OCaml |
(* Task : Vigenere cipher/Cryptanalysis *)
(*
Given some text you suspect has been encrypted
with a Vigenère cipher, extract the key and plaintext.
Uses correlation factors similar to other solutions.
(originally tried Friedman test, didn't produce good result)
Coded in a way that allows non-english (by p... |
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 ... | #Common_Lisp | Common Lisp | (ql:quickload :cl-fad)
(defun mapc-directory-tree (fn directory &key (depth-first-p t))
(dolist (entry (cl-fad:list-directory directory))
(unless depth-first-p
(funcall fn entry))
(when (cl-fad:directory-pathname-p entry)
(mapc-directory-tree fn entry))
(when depth-first-p
(funcall fn en... |
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 ... | #D | D | void main() {
import std.stdio, std.file;
// Recursive breadth-first scan (use SpanMode.depth for
// a depth-first scan):
dirEntries("", "*.d", SpanMode.breadth).writeln;
} |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.