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/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   ...
#Groovy
Groovy
new File('.').eachFileRecurse { if (it.name =~ /.*\.txt/) println it; }
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   ...
#GUISS
GUISS
Start,Find,Files and Folders,Dropdown: Look in>My Documents, Inputbox: filename>m*.txt,Button:Search
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 ██ ...
#J
J
collectLevels =: >./\ <. >./\. NB. collect levels after filling waterLevels=: collectLevels - ] NB. water levels for each tower collectedWater=: +/@waterLevels NB. sum the units of water collected printTowers =: ' ' , [: |.@|: '#~' #~ ] ,. waterLe...
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#6502_Assembly
6502 Assembly
LDA #3 JSR $FE95
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 ...
#Haskell
Haskell
import System.Random import Data.List import Control.Monad import Control.Arrow   distribCheck :: IO Int -> Int -> Int -> IO [(Int,(Int,Bool))] distribCheck f n d = do nrs <- replicateM n f let group = takeWhile (not.null) $ unfoldr (Just. (partition =<< (==). head)) nrs avg = (fromIntegral n) / fromInteg...
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.
#Prolog
Prolog
:- dynamic pt/6. voronoi :- V is random(20) + 20, retractall(pt(_,_,_,_)), forall(between(1, V, I), ( X is random(390) + 5, Y is random(390) + 5, R is random(65535), G is random(65535), B is random(65535), assertz(pt(I,X,Y, R, G, B)) )), voronoi(manhattan, V), voronoi(euclide,...
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribut...
#Elixir
Elixir
defmodule Verify do defp gammaInc_Q(a, x) do a1 = a-1 f0 = fn t -> :math.pow(t, a1) * :math.exp(-t) end df0 = fn t -> (a1-t) * :math.pow(t, a-2) * :math.exp(-t) end y = while_loop(f0, x, a1) n = trunc(y / 3.0e-4) h = y / n hh = 0.5 * h sum = Enum.reduce(n-1 .. 0, 0, fn j,sum -> ...
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at t...
#Phix
Phix
with javascript_semantics sequence d = {tagset(9,0)}, inv = tagset(9,0), p = {tagset(9,0)} for i=1 to 4 do d = append(d,extract(d[$],{2,3,4,5,1,7,8,9,10,6})) end for for i=5 to 8 do d = append(d,reverse(d[-4])) end for d = append(d,reverse(d[1])) inv[2..5] = reverse(inv[2..5]) for i=1 ...
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar ...
#Common_Lisp
Common Lisp
(defun strip (s) (remove-if-not (lambda (c) (char<= #\A c #\Z)) (string-upcase s)))   (defun vigenère (s key &key decipher &aux (A (char-code #\A)) (op (if decipher #'- #'+))) (labels ((to-char (c) (code-char (+ c A))) (to-code (c) (- (char-code c) A))) (let ((k (map 'list #'to-code ...
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 ...
#Haskell
Haskell
data Tree a = Empty | Node { value :: a, left :: Tree a, right :: Tree a } deriving (Show, Eq)   tree = Node 1 (Node 2 (Node 4 (Node 7 Empty Empty) Empty) (Node 5 Empty Empty)) (Node 3 (Node 6 (Node 8 Empty Empty) (Node 9 Empty Empty)) Empty)   treeIndent Empty = ["-- (nil)"] treeIndent t = ["--" ++ show (value t)] ...
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. ...
#PicoLisp
PicoLisp
(for F (dir "@src/") # Iterate directory (when (match '`(chop "s@.c") (chop F)) # Matches 's*.c'? (println F) ) ) # Yes: Print it
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. ...
#Pike
Pike
array(string) files = get_dir("/home/foo/bar"); foreach(files, string file) write(file + "\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   ...
#Haskell
Haskell
import System.Environment import System.Directory import System.FilePath.Find   search pat = find always (fileName ~~? pat)   main = do [pat] <- getArgs dir <- getCurrentDirectory files <- search pat dir mapM_ putStrLn files
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   ...
#Icon_and_Unicon
Icon and Unicon
  ########################### # A sequential solution # ###########################   procedure main() every write(!getdirs(".")) # writes out all directories from the current directory down end   procedure getdirs(s) #: return a list of directories beneath the directory 's' local D,d,f   if ( stat(s).mode ? ="d" ...
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 ██ ...
#Java
Java
public class WaterBetweenTowers { public static void main(String[] args) { int i = 1; int[][] tba = new int[][]{ 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, ...
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#8086_Assembly
8086 Assembly
mov ah,00h mov al,videoMode int 10h
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#Action.21
Action!
PROC ShowMode(BYTE m,split,gr CARD w, BYTE h, CARD size, CHAR ARRAY descr) BYTE CH=$02FC CARD i BYTE POINTER ptr   Graphics(0) PrintF("Next video mode: %B%E",m) IF split THEN PrintF("Split video mode%E%EUpper part:%E") FI   IF gr THEN Print("Graphics") ...
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#AmigaBASIC
AmigaBASIC
SCREEN 1,320,200,5,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 ...
#Hy
Hy
(import [collections [Counter]]) (import [random [randint]])   (defn uniform? [f repeats delta] ; Call 'f' 'repeats' times, then check if the proportion of each ; value seen is within 'delta' of the reciprocal of the count ; of distinct values. (setv bins (Counter (list-comp (f) [i (range repeats)]))) (setv target ...
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 ...
#Icon_and_Unicon
Icon and Unicon
# rnd  : a co-expression, which will generate the random numbers # n  : the number of numbers to test # delta: tolerance in non-uniformity # This procedure fails if after the sampling the difference # in uniformity exceeds delta, a proportion of n / number-of-alternatives procedure verify_uniform (rnd, n, delta) #...
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.
#PureBasic
PureBasic
Structure VCoo x.i: y.i Colour.i: FillColour.i EndStructure   Macro RandInt(MAXLIMIT) Int(MAXLIMIT*(Random(#MAXLONG)/#MAXLONG)) EndMacro   Macro SQ2(X, Y) ((X)*(X) + (Y)*(Y)) EndMacro   Procedure GenRandomPoints(Array a.VCoo(1), xMax, yMax, cnt) Protected i, j, k, l cnt-1 Dim a(cnt) For i=0 To cnt ...
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribut...
#Fortran
Fortran
module gsl_mini_bind_m   use iso_c_binding implicit none private   public :: p_value   interface function gsl_cdf_chisq_q(x, nu) bind(c, name='gsl_cdf_chisq_Q') import real(c_double), value :: x real(c_double), value :: nu real(c_double) :: gsl...
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at t...
#Python
Python
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,...
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 ...
#D
D
import std.stdio, std.string;   string encrypt(in string txt, in string key) pure @safe in { assert(key.removechars("^A-Z") == key); } body { string res; foreach (immutable i, immutable c; txt.toUpper.removechars("^A-Z")) res ~= (c + key[i % $] - 2 * 'A') % 26 + 'A'; return res; }   string 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 ...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) showTree("", " -", [1, [2,[3],[4,[5],[6]],[7,[11]]], [8,[9,[10]]] ]) write() showTree("", " -", [1, [2,[3,[4]]], [5,[6],[7,[8],[9]],[10]] ]) end   procedure showTree(prefix, lastc, A) write(prefix, lastc, "--", A[1]) if *A > 1 then { prefix ||:= if prefix[-1] == "|" then " ...
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. ...
#Pop11
Pop11
lvars repp, fil; ;;; create path repeater sys_file_match('*.p', '', false, 0) -> repp; ;;; iterate over files while (repp() ->> fil) /= termin do  ;;; print the file printf(fil, '%s\n'); endwhile;
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. ...
#PowerShell
PowerShell
Get-ChildItem *.txt -Name Get-ChildItem f* -Name
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   ...
#IDL
IDL
result = file_search( directory, '*.txt', count=cc )
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   ...
#J
J
require 'dir' >{."1 dirtree '*.html'
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 ██ ...
#JavaScript
JavaScript
(function () { 'use strict';   // waterCollected :: [Int] -> Int var waterCollected = function (xs) { return sum( // water above each bar zipWith(function (a, b) { return a - b; // difference between water level and bar }, ...
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#Applesoft_BASIC
Applesoft BASIC
TEXT, page 1, 40 x 24 GR, page 1, 40 x 40, 16 colors, mixed with four lines of text HGR, page 1, 280 x 160, 6 colors, mixed with four lines of text HGR2, page 2, 280 x 192, 6 colors, full screen text, page 2, 40 x 24 gr, page 1, 40 x 48, 16 colors, full screen gr, page 2, 40 x 40, 16 colors, mixed with four lines of te...
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#ARM_Assembly
ARM Assembly
  MOV R1,#0x04000000 MOV R0,#0x403 STR r0,[r1] ;the game boy advance is little-endian, so I would have expected this not to work. However it does indeed work.  
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#BBC_BASIC
BBC BASIC
10 MODE 1: REM 320x256 4 colour graphics
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#Commodore_BASIC
Commodore BASIC
10 rem video modes - c64 15 rem rosetta code 20 print chr$(147);chr$(14):poke 53280,0:poke 53281,0:poke 646,1 25 poke 53282,2:poke 53283,11:poke 53284,9:rem set extended and multi colors 30 if peek(12288)=60 and peek(12289)=102 then goto 100 35 poke 52,32:poke 56,32:clr 40 print "Initializing - Please wait..." 45 poke ...
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 ...
#J
J
checkUniform=: adverb define 0.05 u checkUniform y  : n=. */y delta=. x sample=. u n NB. the "u" refers to the verb to left of adverb freqtable=. /:~ (~. sample) ,. #/.~ sample expected=. n % # freqtable errmsg=. 'Distribution is potentially skewed' errmsg assert (delta * expected) > | exp...
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 ...
#Java
Java
import static java.lang.Math.abs; import java.util.*; import java.util.function.IntSupplier;   public class Test {   static void distCheck(IntSupplier f, int nRepeats, double delta) { Map<Integer, Integer> counts = new HashMap<>();   for (int i = 0; i < nRepeats; i++) counts.compute(f.ge...
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (209...
#11l
11l
F to_str(v) R ‘[ ’v.map(n -> hex(n).lowercase().zfill(2)).join(‘ ’)‘ ]’   F to_seq(UInt64 x) V i = 0 L(ii) (9.<0).step(-1) I x [&] (UInt64(127) << ii * 7) != 0 i = ii L.break   [Byte] out L(j) 0 .. i out [+]= ((x >> ((i - j) * 7)) [&] 127) [|] 128   out[i] (+)= 128 R o...
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.
#Python
Python
from PIL import Image import random import math   def generate_voronoi_diagram(width, height, num_cells): image = Image.new("RGB", (width, height)) putpixel = image.putpixel imgx, imgy = image.size nx = [] ny = [] nr = [] ng = [] nb = [] for i in range(num_cells): nx.append(random.randrange(imgx)) ny.appen...
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribut...
#Go
Go
package main   import ( "fmt" "math" )   type ifctn func(float64) float64   func simpson38(f ifctn, a, b float64, n int) float64 { h := (b - a) / float64(n) h1 := h / 3 sum := f(a) + f(b) for j := 3*n - 1; j > 0; j-- { if j%3 == 0 { sum += 2 * f(a+h1*float64(j)) } els...
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at t...
#Raku
Raku
my @d = [^10] xx 5; @d[$_][^5].=rotate($_), @d[$_][5..*].=rotate($_) for 1..4; push @d: [@d[$_].reverse] for flat 1..4, 0;   my @i = 0,4,3,2,1,5,6,7,8,9;   my %h = flat (0,1,5,8,9,4,2,7,0).rotor(2 =>-1).map({.[0]=>.[1]}), 6=>3, 3=>6; my @p = [^10],; @p.push: [@p[*-1].map: {%h{$_}}] for ^7;   sub checksum (Int $int wher...
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 ...
#Elena
Elena
import system'text; import system'math; import system'routines; import extensions;   class VCipher { string encrypt(string txt, string pw, int d) { auto output := new TextBuilder(); int pwi := 0;   string PW := pw.upperCase();   txt.upperCase().forEach:(t) { i...
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 ...
#Elixir
Elixir
defmodule VigenereCipher do @base  ?A @size  ?Z - @base + 1   def encrypt(text, key), do: crypt(text, key, 1)   def decrypt(text, key), do: crypt(text, key, -1)   defp crypt(text, key, dir) do text = String.upcase(text) |> String.replace(~r/[^A-Z]/, "") |> to_char_list key_iterator = String.upcase(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 ...
#J
J
BOXC=: 9!:6 '' NB. box drawing characters EW =: {: BOXC NB. east-west   showtree=: 4 : 0 NB. y is parent index for each node (non-indices for root nodes) NB. x is label for each node t=. (<EW,' ') ,@<@,:@,&":&.> x NB. tree fragments c=. |:(#~ e./@|:);(~.,"0&.>(</. i.@#)) y while. +./ b=. ({.c)*.//.-...
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. ...
#PureBasic
PureBasic
Procedure walkDirectory(directory.s = "", pattern.s = "") Protected directoryID   directoryID = ExamineDirectory(#PB_Any,directory,pattern) If directoryID While NextDirectoryEntry(directoryID) PrintN(DirectoryEntryName(directoryID)) Wend FinishDirectory(directoryID) EndIf EndProcedure   If Op...
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. ...
#Python
Python
import glob for filename in glob.glob('/foo/bar/*.mp3'): print(filename)
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   ...
#Java
Java
import java.io.File;   public class MainEntry { public static void main(String[] args) { walkin(new File("/home/user")); //Replace this with a suitable directory }   /** * Recursive function to descend into the directory tree and find all the files * that end with ".mp3" * @param dir...
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 ██ ...
#jq
jq
def waterCollected: . as $tower | ($tower|length) as $n | ([0] + [range(1;$n) | ($tower[0:.] | max) ]) as $highLeft | ( [range(1;$n) | ($tower[.:$n] | max) ] + [0]) as $highRight | [ range(0;$n) | [ ([$highLeft[.], $highRight[.] ]| min) - $tower[.], 0 ] | max] | add ;   def towers: [ [1, 5, 3, 7, ...
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#ERRE
ERRE
dim as integer i, w, h, d   for i = 0 to 21 if i>2 and i<7 then continue for 'screens 3-6 are not defined screen i screeninfo w, h, d print "Screen ";i print using "#### x ####, color depth ##";w;h;d sleep next i   'a more flexible alternative is ScreenRes   'this sets up a window of 1618x971...
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#FreeBASIC
FreeBASIC
dim as integer i, w, h, d   for i = 0 to 21 if i>2 and i<7 then continue for 'screens 3-6 are not defined screen i screeninfo w, h, d print "Screen ";i print using "#### x ####, color depth ##";w;h;d sleep next i   'a more flexible alternative is ScreenRes   'this sets up a window of 1618x971...
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#Go
Go
package main   import ( "fmt" "log" "os/exec" "time" )   func main() { // query supported display modes out, err := exec.Command("xrandr", "-q").Output() if err != nil { log.Fatal(err) } fmt.Println(string(out)) time.Sleep(3 * time.Second)   // change display mode to ...
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive
Verify distribution uniformity/Naive
This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) producing random integers. The number of times ...
#JavaScript
JavaScript
function distcheck(random_func, times, opts) { if (opts === undefined) opts = {} opts['delta'] = opts['delta'] || 2;   var count = {}, vals = []; for (var i = 0; i < times; i++) { var val = random_func(); if (! has_property(count, val)) { count[val] = 1; vals.push...
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (209...
#Ada
Ada
with Ada.Containers.Vectors; with Ada.Text_IO; with Ada.Unchecked_Conversion;   procedure VLQ is   package Nat_IO is new Ada.Text_IO.Integer_IO (Natural);   type Byte is mod 2**8;   package Byte_IO is new Ada.Text_IO.Modular_IO (Byte);   type Int7 is mod 2**7;   package Int7_IO is new Ada.Text_IO.Modular...
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#11l
11l
T Vector Float x, y   F (x, y) .x = x .y = y   F +(vector) R Vector(.x + vector.x, .y + vector.y)   F -(vector) R Vector(.x - vector.x, .y - vector.y)   F *(mult) R Vector(.x * mult, .y * mult)   F /(denom) R Vector(.x / denom, .y / denom)   F String() R ‘(...
http://rosettacode.org/wiki/Variable_size/Set
Variable size/Set
Task Demonstrate how to specify the minimum size of a variable or a data type.
#11l
11l
  * Binary interger (H,F) I2 DS H half word 2 bytes I4 DS F full word 4 bytes * Real (floating point) (E,D,L) X4 DS E short 4 bytes X8 DS D double 8 bytes X16 DS L extended 16 bytes * ...
http://rosettacode.org/wiki/Voronoi_diagram
Voronoi diagram
A Voronoi diagram is a diagram consisting of a number of sites. Each Voronoi site s also has a Voronoi cell consisting of all points closest to s. Task Demonstrate how to generate and display a Voroni diagram. See algo K-means++ clustering.
#QB64
QB64
_Title "Voronoi Diagram"   Dim As Integer pnt, px, py, i, x, y, adjct, sy, ly Dim As Double st   '===================================================================== ' Changes number of points and screen size here '===================================================================== pnt = 100 px = 512 py = 512 '====...
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.
#R
R
  ## HF#1 Random Hex color randHclr <- function() { m=255;r=g=b=0; r <- sample(0:m, 1, replace=TRUE); g <- sample(0:m, 1, replace=TRUE); b <- sample(0:m, 1, replace=TRUE); return(rgb(r,g,b,maxColorValue=m)); } ## HF#2 Metrics: Euclidean, Manhattan and Minkovski Metric <- function(x, y, mt) { if(mt==1) {retu...
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribut...
#Hy
Hy
(import [scipy.stats [chisquare]] [collections [Counter]])   (defn uniform? [f repeats &optional [alpha .05]] "Call 'f' 'repeats' times and do a chi-squared test for uniformity of the resulting discrete distribution. Return false iff the null hypothesis of uniformity is rejected for the test with size 'alph...
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribut...
#J
J
require 'stats/base'   countCats=: #@~. NB. counts the number of unique items getExpected=: #@] % [ NB. divides no of items by category count getObserved=: #/.~@] NB. counts frequency for each category calcX2=: [: +/ *:@(getObserved - getExpected) % getExpected NB. calc...
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at t...
#Vlang
Vlang
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, ...
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 ...
#Erlang
Erlang
% Erlang implementation of Vigenère cipher -module(vigenere). -export([encrypt/2, decrypt/2]). -import(lists, [append/2, filter/2, map/2, zipwith/3]).   % Utility functions for character tests and conversions isupper([C|_]) -> isupper(C); isupper(C) -> (C >= $A) and (C =< $Z).   islower([C|_]) -> islower(C); islowe...
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 ...
#Java
Java
public class VisualizeTree { public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree();   tree.insert(100); for (int i = 0; i < 20; i++) tree.insert((int) (Math.random() * 200)); tree.display(); } }   class BinarySearchTree { private ...
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. ...
#R
R
dir("/foo/bar", "mp3")
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. ...
#Racket
Racket
  -> (for ([f (directory-list "/tmp")] #:when (regexp-match? "\\.rkt$" f)) (displayln f)) ... *.rkt files ...  
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   ...
#JavaScript
JavaScript
var fso = new ActiveXObject("Scripting.FileSystemObject");   function walkDirectoryTree(folder, folder_name, re_pattern) { WScript.Echo("Files in " + folder_name + " matching '" + re_pattern + "':"); walkDirectoryFilter(folder.files, re_pattern);   var subfolders = folder.SubFolders; WScript.Echo("Folde...
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 ██ ...
#Julia
Julia
using Printf   function watercollected(towers::Vector{Int}) high_lft = vcat(0, accumulate(max, towers[1:end-1])) high_rgt = vcat(reverse(accumulate(max, towers[end:-1:2])), 0) waterlvl = max.(min.(high_lft, high_rgt) .- towers, 0) return waterlvl end   function towerprint(towers, levels) ctowers = c...
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#Groovy
Groovy
def invoke(String cmd) { println(cmd.execute().text) }   invoke("xrandr -q") Thread.sleep(3000)   invoke("xrandr -s 1024x768") Thread.sleep(3000)   invoke("xrandr -s 1366x768")
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#GW-BASIC
GW-BASIC
10 REM GW Basic can switch VGA modes 20 SCREEN 18: REM Mode 12h 640x480 16 colour graphics
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#Icon_and_Unicon
Icon and Unicon
procedure main(A) mode := A[1] if \mode then system("xrandr -s " || \mode || " >/dev/null") else system("xrandr -q") # Display available modes end
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#Julia
Julia
  if Base.Sys.islinux() run(`xrandr -s 640x480`) sleep(3) run(`xrandr -s 1280x960`) else # windows run(`mode CON: COLS=40 LINES=100`) sleep(3) run(`mode CON: COLS=100 LINES=50`) end  
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 ...
#Julia
Julia
using Printf   function distcheck(f::Function, rep::Int=10000, Δ::Int=3) smpl = f(rep) counts = Dict(k => count(smpl .== k) for k in unique(smpl)) expected = rep / length(counts) lbound = expected * (1 - 0.01Δ) ubound = expected * (1 + 0.01Δ) noobs = count(x -> !(lbound ≤ x ≤ ubound), values(cou...
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 ...
#Kotlin
Kotlin
// version 1.1.3   import java.util.Random   val r = Random()   fun dice5() = 1 + r.nextInt(5)   fun checkDist(gen: () -> Int, nRepeats: Int, tolerance: Double = 0.5) { val occurs = mutableMapOf<Int, Int>() for (i in 1..nRepeats) { val d = gen() if (occurs.containsKey(d)) occurs[d] =...
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (209...
#ANSI_Standard_BASIC
ANSI Standard BASIC
INPUT s$ LET s$ = LTRIM$(RTRIM$(s$)) LET v = 0 FOR i = 1 TO LEN(s$) LET c$ = s$(i:i) LET k = POS("0123456789abcdef", c$) IF k > 0 THEN LET v = v*16 + k - 1 NEXT i PRINT "S= ";s$, "V=";v   ! Convert back to hex LET hex$ ="0123456789abcdef" LET hs$=" "   FOR i = LEN(hs$) TO 1 STEP -1 IF v =...
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (209...
#Bracmat
Bracmat
( ( VLQ = b07 b8 vlq . 0:?b8 & :?vlq & whl ' ( !arg:>0 & mod$(!arg.128):?b07 & (chr$(!b8+!b07)|) !vlq:?vlq & 128:?b8 & div$(!arg.128):?arg ) & str$!vlq ) & ( NUM = c num d . 0:?num:?d & whl ' ( @(!arg:%@...
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   DEFINE X_="+0" DEFINE Y_="+6"   TYPE Vector=[CARD x1,x2,x3,y1,y2,y3]   PROC PrintVec(Vector POINTER v) Print("[") PrintR(v X_) Print(",") PrintR(v Y_) Print("]") RETURN   PROC VecIntInit(Vector POINTER v INT ix,iy) IntToReal(ix,v X_) IntToReal(iy,v Y_) RETURN  ...
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#ALGOL_68
ALGOL 68
# the standard mode COMPLEX is a two element vector # MODE VECTOR = COMPLEX; # the operations required for the task plus many others are provided as standard for COMPLEX and REAL items # # the two components are fields called "re" and "im" # # we can define a "pretty-print" operator: # # returns a formatted representat...
http://rosettacode.org/wiki/Variable_size/Set
Variable size/Set
Task Demonstrate how to specify the minimum size of a variable or a data type.
#360_Assembly
360 Assembly
  * Binary interger (H,F) I2 DS H half word 2 bytes I4 DS F full word 4 bytes * Real (floating point) (E,D,L) X4 DS E short 4 bytes X8 DS D double 8 bytes X16 DS L extended 16 bytes * ...
http://rosettacode.org/wiki/Variable_size/Set
Variable size/Set
Task Demonstrate how to specify the minimum size of a variable or a data type.
#6502_Assembly
6502 Assembly
MyByte: byte 0  ;most assemblers will also accept DB or DFB MyWord: word 0  ;most assemblers will also accept DW or DFW MyDouble: dd 0
http://rosettacode.org/wiki/Variable_size/Set
Variable size/Set
Task Demonstrate how to specify the minimum size of a variable or a data type.
#68000_Assembly
68000 Assembly
MyByte: DC.B 0 EVEN ;you need this to prevent alignment problems if you define an odd number of bytes. MyWord: DC.W 0 ;this takes up 2 bytes even though only one 0 was written MyLong: DC.L 0 ;this takes up 4 bytes even though only one 0 was written
http://rosettacode.org/wiki/Variable_size/Set
Variable size/Set
Task Demonstrate how to specify the minimum size of a variable or a data type.
#8086_Assembly
8086 Assembly
  .data ;data segment   TestValue_00 byte 0 ;an 8-bit variable TestValue_01 word 0 ;a 16-bit variable TestValue_02 dword 0 ;a 32-bit variable   .code   start:   mov dh, byte ptr [ds:TestValue_00] ;load the value stored at the address "TestValue_00" mov ax, word ptr [ds:TestValue_01] ...
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.
#Racket
Racket
  #lang racket   (require plot)   ;; Performs clustering of points in a grid ;; using the nearest neigbour approach and shows ;; clusters in different colors (define (plot-Voronoi-diagram point-list) (define pts (for*/list ([x (in-range 0 1 0.005)] [y (in-range 0 1 0.005)]) (vector x y)))   ...
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribut...
#Java
Java
import static java.lang.Math.pow; import java.util.Arrays; import static java.util.Arrays.stream; import org.apache.commons.math3.special.Gamma;   public class Test {   static double x2Dist(double[] data) { double avg = stream(data).sum() / data.length; double sqs = stream(data).reduce(0, (a, b) -> ...
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at t...
#Wren
Wren
import "/fmt" for Fmt   var 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]...
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 ...
#F.23
F#
  module vigenere = let keyschedule (key:string) = let s = key.ToUpper().ToCharArray() |> Array.filter System.Char.IsLetter let l = Array.length s (fun n -> int s.[n % l])   let enc k c = ((c + k - 130) % 26) + 65 let dec k c = ((c - k + 130) % 26) + 65 let crypt f key = Array.ma...
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 ...
#JavaScript
JavaScript
<!doctype html> <html id="doc"> <head><meta charset="utf-8"/> <title>Stuff</title> <script type="application/javascript"> function gid(id) { return document.getElementById(id); }   function ce(tag, cls, parent_node) { var e = document.createElement(tag); e.className = cls; if (parent_node) parent_node...
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. ...
#Raku
Raku
.say for dir ".", :test(/foo/);
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. ...
#Rascal
Rascal
import IO; public void Walk(loc a, str pattern){ for (entry <- listEntries(a)) endsWith(entry, pattern) ? println(entry); }
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   ...
#Julia
Julia
rootpath = "/home/user/music" pattern = r".mp3$"   for (root, dirs, files) in walkdir(rootpath) for file in files if occursin(pattern, file) println(file) end end end
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   ...
#Kotlin
Kotlin
// version 1.2.0   import java.io.File   fun walkDirectoryRecursively(dirPath: String, pattern: Regex): Sequence<String> { val d = File(dirPath) require (d.exists() && d.isDirectory()) return d.walk().map { it.name }.filter { it.matches(pattern) }.sorted().distinct() }   fun main(args: Array<String>) { ...
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 ██ ...
#Kotlin
Kotlin
// version 1.1.2   fun waterCollected(tower: IntArray): Int { val n = tower.size val highLeft = listOf(0) + (1 until n).map { tower.slice(0 until it).max()!! } val highRight = (1 until n).map { tower.slice(it until n).max()!! } + 0 return (0 until n).map { maxOf(minOf(highLeft[it], highRight[it]) - towe...
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#Kotlin
Kotlin
// version 1.1.51   import java.util.Scanner   fun runSystemCommand(command: String) { val proc = Runtime.getRuntime().exec(command) Scanner(proc.inputStream).use { while (it.hasNextLine()) println(it.nextLine()) } proc.waitFor() println() }   fun main(args: Array<String>) { // query sup...
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#Locomotive_Basic
Locomotive Basic
10 MODE 0: REM switch to mode 0
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#Lua
Lua
print("\33[?3h") -- 132-column text print("\33[?3l") -- 80-column text
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#Nim
Nim
import os, osproc, strformat, strscans   # Retrieve video modes. let p = startProcess("xrandr", "", ["-q"], nil, {poUsePath}) var currWidth, currHeight = 0 # Current video mode. var width, height = 0 # Some other video mode. for line in p.lines: echo line # Find current display mode, marked by an asteri...
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 ...
#Liberty_BASIC
Liberty BASIC
  n=1000 print "Testing ";n;" times" if not(check(n, 0.05)) then print "Test failed" else print "Test passed" print   n=10000 print "Testing ";n;" times" if not(check(n, 0.05)) then print "Test failed" else print "Test passed" print   n=50000 print "Testing ";n;" times" if not(check(n, 0.05)) then print "Test failed...
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (209...
#C
C
#include <stdio.h> #include <stdint.h>   void to_seq(uint64_t x, uint8_t *out) { int i, j; for (i = 9; i > 0; i--) { if (x & 127ULL << i * 7) break; } for (j = 0; j <= i; j++) out[j] = ((x >> ((i - j) * 7)) & 127) | 128;   out[i] ^= 128; }   uint64_t from_seq(uint8_t *in) { uint64_t r = 0;   do { r = (r <<...
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#ACL2
ACL2
(defun print-all-fn (xs) (if (endp xs) nil (prog2$ (cw "~x0~%" (first xs)) (print-all-fn (rest xs)))))   (defmacro print-all (&rest args) `(print-all-fn (quote ,args)))
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#BASIC256
BASIC256
arraybase 1 dim vect1(2) vect1[1] = 5 : vect1[2] = 7 dim vect2(2) vect2[1] = 2 : vect2[2] = 3 dim vect3(vect1[?])   subroutine showarray(vect3) print "["; svect$ = "" for n = 1 to vect3[?] svect$ &= vect3[n] & ", " next n svect$ = left(svect$, length(svect$) - 2) print svect$; print ...
http://rosettacode.org/wiki/Variable_size/Set
Variable size/Set
Task Demonstrate how to specify the minimum size of a variable or a data type.
#Ada
Ada
type Response is (Yes, No); -- Definition of an enumeration type with two values for Response'Size use 1; -- Setting the size of Response to 1 bit, rather than the default single byte size
http://rosettacode.org/wiki/Variable_size/Set
Variable size/Set
Task Demonstrate how to specify the minimum size of a variable or a data type.
#ARM_Assembly
ARM Assembly
.byte 0xFF .align 4 .word 0xFFFF .align 4 .long 0xFFFFFFFF
http://rosettacode.org/wiki/Variable_size/Set
Variable size/Set
Task Demonstrate how to specify the minimum size of a variable or a data type.
#AutoHotkey
AutoHotkey
10 DIM A%(10): REM the array size is 10 integers 20 DIM B(10): REM the array will hold 10 floating point values 30 DIM C$(12): REM a character array of 12 bytes