#include <windows.h>
#include <vector>
#include <string>

using namespace std;

//////////////////////////////////////////////////////
struct Point {
  int x, y;
};

//////////////////////////////////////////////////////
class MyBitmap {
 public:
  MyBitmap() : pen_(nullptr) {}
  ~MyBitmap() {
    DeleteObject(pen_);
    DeleteDC(hdc_);
    DeleteObject(bmp_);
  }

  bool Create(int w, int h) {
    BITMAPINFO	bi;
    ZeroMemory(&bi, sizeof(bi));

    bi.bmiHeader.biSize = sizeof(bi.bmiHeader);
    bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;
    bi.bmiHeader.biCompression = BI_RGB;
    bi.bmiHeader.biPlanes = 1;
    bi.bmiHeader.biWidth = w;
    bi.bmiHeader.biHeight = -h;

    void *bits_ptr = nullptr;
    HDC dc = GetDC(GetConsoleWindow());
    bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);
    if (!bmp_) return false;

    hdc_ = CreateCompatibleDC(dc);
    SelectObject(hdc_, bmp_);
    ReleaseDC(GetConsoleWindow(), dc);

    width_ = w;
    height_ = h;

    return true;
  }

  void SetPenColor(DWORD clr) {
    if (pen_) DeleteObject(pen_);
    pen_ = CreatePen(PS_SOLID, 1, clr);
    SelectObject(hdc_, pen_);
  }

  bool SaveBitmap(const char* path) {
    HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
    if (file == INVALID_HANDLE_VALUE) {
      return false;
    }

    BITMAPFILEHEADER fileheader;
    BITMAPINFO infoheader;
    BITMAP bitmap;
    GetObject(bmp_, sizeof(bitmap), &bitmap);

    DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
    ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));
    ZeroMemory(&infoheader, sizeof(BITMAPINFO));
    ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));

    infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;
    infoheader.bmiHeader.biCompression = BI_RGB;
    infoheader.bmiHeader.biPlanes = 1;
    infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);
    infoheader.bmiHeader.biHeight = bitmap.bmHeight;
    infoheader.bmiHeader.biWidth = bitmap.bmWidth;
    infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);

    fileheader.bfType = 0x4D42;
    fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);
    fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;

    GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);

    DWORD wb;
    WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);
    WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);
    WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);
    CloseHandle(file);

    delete[] dwp_bits;
    return true;
  }

  HDC hdc() { return hdc_; }
  int width() { return width_; }
  int height() { return height_; }

 private:
  HBITMAP bmp_;
  HDC hdc_;
  HPEN pen_;
  int width_, height_;
};

static int DistanceSqrd(const Point& point, int x, int y) {
  int xd = x - point.x;
  int yd = y - point.y;
  return (xd * xd) + (yd * yd);
}

//////////////////////////////////////////////////////
class Voronoi {
 public:
  void Make(MyBitmap* bmp, int count) {
    bmp_ = bmp;
    CreatePoints(count);
    CreateColors();
    CreateSites();
    SetSitesPoints();
  }

 private:
  void CreateSites() {
    int w = bmp_->width(), h = bmp_->height(), d;
    for (int hh = 0; hh < h; hh++) {
      for (int ww = 0; ww < w; ww++) {
        int ind = -1, dist = INT_MAX;
        for (size_t it = 0; it < points_.size(); it++) {
          const Point& p = points_[it];
          d = DistanceSqrd(p, ww, hh);
          if (d < dist) {
            dist = d;
            ind = it;
          }
        }

        if (ind > -1)
          SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);
        else
          __asm nop // should never happen!
        }
    }
  }

  void SetSitesPoints() {
    for (const auto& point : points_) {
      int x = point.x, y = point.y;
      for (int i = -1; i < 2; i++)
        for (int j = -1; j < 2; j++)
          SetPixel(bmp_->hdc(), x + i, y + j, 0);
    }
  }

  void CreatePoints(int count) {
    const int w = bmp_->width() - 20, h = bmp_->height() - 20;
    for (int i = 0; i < count; i++) {
      points_.push_back({ rand() % w + 10, rand() % h + 10 });
    }
  }

  void CreateColors() {
    for (size_t i = 0; i < points_.size(); i++) {
      DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);
      colors_.push_back(c);
    }
  }

  vector<Point> points_;
  vector<DWORD> colors_;
  MyBitmap* bmp_;
};

//////////////////////////////////////////////////////
int main(int argc, char* argv[]) {
  ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);
  srand(GetTickCount());

  MyBitmap bmp;
  bmp.Create(512, 512);
  bmp.SetPenColor(0);

  Voronoi v;
  v.Make(&bmp, 50);

  BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);
  bmp.SaveBitmap("v.bmp");

  system("pause");

  return 0;
}


L(filename) fs:walk_dir(‘/’)
   I re:‘.*\.mp3’.match(filename)
      print(filename)


import std.random, std.algorithm, std.range, bitmap;

struct Point { uint x, y; }

enum randomPoints = (in size_t nPoints, in size_t nx, in size_t ny) =>
    nPoints.iota
    .map!((int) => Point(uniform(0, nx), uniform(0, ny)))
    .array;

Image!RGB generateVoronoi(in Point[] pts,
                          in size_t nx, in size_t ny) /*nothrow*/ {
    // Generate a random color for each centroid.
    immutable rndRBG = (int) => RGB(uniform!"[]"(ubyte.min, ubyte.max),
                                    uniform!"[]"(ubyte.min, ubyte.max),
                                    uniform!"[]"(ubyte.min, ubyte.max));
    const colors = pts.length.iota.map!rndRBG.array;

    // Generate diagram by coloring pixels with color of nearest site.
    auto img = new typeof(return)(nx, ny);
    foreach (immutable x; 0 .. nx)
        foreach (immutable y; 0 .. ny) {
            immutable dCmp = (in Point a, in Point b) pure nothrow =>
                ((a.x - x) ^^ 2 + (a.y - y) ^^ 2) <
                ((b.x - x) ^^ 2 + (b.y - y) ^^ 2);
            // img[x, y] = colors[pts.reduce!(min!dCmp)];
            img[x, y] = colors[pts.length - pts.minPos!dCmp.length];
        }

    // Mark each centroid with a white dot.
    foreach (immutable p; pts)
        img[p.tupleof] = RGB.white;
    return img;
}

void main() {
    enum imageWidth = 640,
         imageHeight = 480;
    randomPoints(150, imageWidth, imageHeight)
    .generateVoronoi(imageWidth, imageHeight)
    .savePPM6("voronoi.ppm");
}


"*.c" f:rglob \ top of stack now has list of all "*.c" files, recursively


with Ada.Directories;  use Ada.Directories;
with Ada.Text_IO;

procedure Test_Directory_Walk is
   procedure Walk (Name : String; Pattern : String) is
      procedure Print (Item : Directory_Entry_Type) is
      begin
         Ada.Text_IO.Put_Line (Full_Name (Item));
      end Print;
      procedure Walk (Item : Directory_Entry_Type) is
      begin
         if Simple_Name (Item) /= "." and then Simple_Name (Item) /= ".." then
            Walk (Full_Name (Item), Pattern);
         end if;
      exception
         when Name_Error => null;
      end Walk;
   begin
      Search (Name, Pattern, (others => True), Print'Access);
      Search (Name, "", (Directory => True, others => False), Walk'Access);
   end Walk;
begin
   Walk (".", "*.adb");
end Test_Directory_Walk;


INT match=0, no match=1, out of memory error=2, other error=3;

STRING slash = "/", pwd=".", parent="..";

PROC walk tree = (STRING path, PROC (STRING)VOID call back)VOID: (
  []STRING files = get directory(path);
  FOR file index TO UPB files DO
    STRING file = files[file index];
    STRING path file = path+slash+file;
    IF file is directory(path file) THEN
      IF file NE pwd AND file NE parent THEN
        walk tree(path file, call back)
      FI
    ELSE
      call back(path file)
    FI
  OD
);

STRING re sort a68 = "[Ss]ort[^/]*[.]a68$";

PROC match sort a68 and print = (STRING path file)VOID:
  IF grep in string(re sort a68, path file, NIL, NIL) = match THEN
    print((path file, new line))
  FI;

walk tree(".", match sort a68 and print)


uses System.Generics.Collections;

procedure TForm1.Voronoi;
const
   p = 3;
   cells = 100;
   size = 1000;

var
  aCanvas : TCanvas;
  px, py: array of integer;
  color: array of Tcolor;
  Img: TBitmap;
  lastColor:Integer;
  auxList: TList<TPoint>;
  poligonlist : TDictionary<integer,TList<TPoint>>;
  pointarray : array of TPoint;

  n,i,x,y,k,j: Integer;
  d1,d2: double;

  function distance(x1,x2,y1,y2 :Integer) : Double;
  begin
    result := sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); ///Euclidian
    // result :=  abs(x1 - x2) + abs(y1 - y2); // Manhattan
    // result := power(power(abs(x1 - x2), p) + power(abs(y1 - y2), p), (1 / p)); // Minkovski
  end;

begin

    poligonlist := TDictionary<integer,TList<Tpoint>>.create;

    n := 0;
    Randomize;

    img := TBitmap.Create;
    img.Width :=1000;
    img.Height :=1000;

    setlength(px,cells);
    setlength(py,cells);
    setlength(color,cells);

    for i:= 0 to cells-1 do
    begin
      px[i] := Random(size);
      py[i] := Random(size);

      color[i] := Random(16777215);
      auxList := TList<Tpoint>.Create;
      poligonlist.Add(i,auxList);
    end;

    for x := 0 to size - 1 do
    begin
      lastColor:= 0;
      for y := 0 to size - 1 do
      begin
        n:= 0;

        for i := 0 to cells - 1 do
        begin
          d1:= distance(px[i], x, py[i], y);
          d2:= distance(px[n], x, py[n], y);

          if d1 < d2 then
          begin
            n := i;
	  end;
        end;
        if n <> lastColor then
        begin
           poligonlist[n].Add(Point(x,y));
           poligonlist[lastColor].Add(Point(x,y));
           lastColor := n;
        end;
      end;

      poligonlist[n].Add(Point(x,y));
      poligonlist[lastColor].Add(Point(x,y));
      lastColor := n;
    end;

    for j := 0 to  cells -1 do
    begin

      SetLength(pointarray, poligonlist[j].Count);
      for I := 0 to poligonlist[j].Count - 1 do
      begin
        if Odd(i) then
        pointarray[i] := poligonlist[j].Items[i];
      end;
      for I := 0 to poligonlist[j].Count - 1 do
      begin
        if not Odd(i) then
        pointarray[i] := poligonlist[j].Items[i];
      end;
      Img.Canvas.Pen.Color := color[j];
      Img.Canvas.Brush.Color := color[j];
      Img.Canvas.Polygon(pointarray);

      Img.Canvas.Pen.Color := clBlack;
      Img.Canvas.Brush.Color := clBlack;
      Img.Canvas.Rectangle(px[j] -2, py[j] -2, px[j] +2, py[j] +2);
    end;
    Canvas.Draw(0,0, img);
end;


; list all files at current path
print list.recursive "."

; get all files at given path
; and select only the ones we want

; just select the files with .md extension
select list.recursive "some/path"
    => [".md" = extract.extension]

; just select the files that contain "test"
select list.recursive "some/path"
    => [in? "test"]


Loop, %A_Temp%\*.tmp,,1
 out .= A_LoopFileName "`n"
MsgBox,% out


Dim Shared As Integer ancho = 500, alto = 500
Screenres ancho, alto, 8
Cls
Randomize Timer

Function hypot(a As Integer, b As Integer) As Double
    Return Sqr(a^2 + b^2)
End Function

Sub Generar_Diagrama_Voronoi(ancho As Integer, alto As Integer, num_celdas As Integer)
    Dim As Integer nx(num_celdas), ny(num_celdas), nr(num_celdas), ng(num_celdas), nb(num_celdas)
    Dim As Integer x, i, y, j, dmin, d

    For i = 1 To num_celdas
        nx(i) = (Rnd * ancho)
        ny(i) = (Rnd * alto)
        nr(i) = (Rnd * 256)
        ng(i) = (Rnd * 256)
        nb(i) = (Rnd * 256)
    Next i
    For y = 1 To alto
        For x = 1 To ancho
            dmin = hypot(ancho-1, alto-1)
            j = -1
            For i = 1 To num_celdas
                d = hypot(nx(i)-x, ny(i)-y)
                If d < dmin Then dmin = d : j = i
            Next i
            Pset (x, y), Rgb(nr(j), ng(j), ng(j))
        Next x
    Next y
End Sub

Generar_Diagrama_Voronoi(ancho, alto, 25)
Bsave "Voronoi_diadram.bmp",0
Sleep


package main

import (
    "fmt"
    "image"
    "image/color"
    "image/draw"
    "image/png"
    "math/rand"
    "os"
    "time"
)

const (
    imageWidth  = 300
    imageHeight = 200
    nSites      = 10
)

func main() {
    writePngFile(generateVoronoi(randomSites()))
}

func generateVoronoi(sx, sy []int) image.Image {
    // generate a random color for each site
    sc := make([]color.NRGBA, nSites)
    for i := range sx {
        sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),
            uint8(rand.Intn(256)), 255}
    }

    // generate diagram by coloring each pixel with color of nearest site
    img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))
    for x := 0; x < imageWidth; x++ {
        for y := 0; y < imageHeight; y++ {
            dMin := dot(imageWidth, imageHeight)
            var sMin int
            for s := 0; s < nSites; s++ {
                if d := dot(sx[s]-x, sy[s]-y); d < dMin {
                    sMin = s
                    dMin = d
                }
            }
            img.SetNRGBA(x, y, sc[sMin])
        }
    }
    // mark each site with a black box
    black := image.NewUniform(color.Black)
    for s := 0; s < nSites; s++ {
        draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),
            black, image.ZP, draw.Src)
    }
    return img
}

func dot(x, y int) int {
    return x*x + y*y
}

func randomSites() (sx, sy []int) {
    rand.Seed(time.Now().Unix())
    sx = make([]int, nSites)
    sy = make([]int, nSites)
    for i := range sx {
        sx[i] = rand.Intn(imageWidth)
        sy[i] = rand.Intn(imageHeight)
    }
    return
}

func writePngFile(img image.Image) {
    f, err := os.Create("voronoi.png")
    if err != nil {
        fmt.Println(err)
        return
    }
    if err = png.Encode(f, img); err != nil {
        fmt.Println(err)
    }
    if err = f.Close(); err != nil {
        fmt.Println(err)
    }
}


      directory$ = "C:\Windows\"
      pattern$ = "*.chm"
      PROClisttree(directory$, pattern$)
      END

      DEF PROClisttree(dir$, filter$)
      LOCAL dir%, sh%, res%
      DIM dir% LOCAL 317
      IF RIGHT$(dir$) <> "\" IF RIGHT$(dir$) <> "/" dir$ += "\"
      SYS "FindFirstFile", dir$ + filter$, dir% TO sh%
      IF sh% <> -1 THEN
        REPEAT
          IF (!dir% AND 16) = 0 PRINT dir$ + $$(dir%+44)
          SYS "FindNextFile", sh%, dir% TO res%
        UNTIL res% = 0
        SYS "FindClose", sh%
      ENDIF
      SYS "FindFirstFile", dir$ + "*", dir% TO sh%
      IF sh% <> -1 THEN
        REPEAT
          IF (!dir% AND 16) IF dir%?44 <> &2E THEN
            PROClisttree(dir$ + $$(dir%+44) + "\", filter$)
          ENDIF
          SYS "FindNextFile", sh%, dir% TO res%
        UNTIL res% = 0
        SYS "FindClose", sh%
      ENDIF
      ENDPROC


#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>

enum {
	WALK_OK = 0,
	WALK_BADPATTERN,
	WALK_NAMETOOLONG,
	WALK_BADIO,
};

#define WS_NONE		0
#define WS_RECURSIVE	(1 << 0)
#define WS_DEFAULT	WS_RECURSIVE
#define WS_FOLLOWLINK	(1 << 1)	/* follow symlinks */
#define WS_DOTFILES	(1 << 2)	/* per unix convention, .file is hidden */
#define WS_MATCHDIRS	(1 << 3)	/* if pattern is used on dir names too */

int walk_recur(char *dname, regex_t *reg, int spec)
{
	struct dirent *dent;
	DIR *dir;
	struct stat st;
	char fn[FILENAME_MAX];
	int res = WALK_OK;
	int len = strlen(dname);
	if (len >= FILENAME_MAX - 1)
		return WALK_NAMETOOLONG;

	strcpy(fn, dname);
	fn[len++] = '/';

	if (!(dir = opendir(dname))) {
		warn("can't open %s", dname);
		return WALK_BADIO;
	}

	errno = 0;
	while ((dent = readdir(dir))) {
		if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
			continue;
		if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
			continue;

		strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
		if (lstat(fn, &st) == -1) {
			warn("Can't stat %s", fn);
			res = WALK_BADIO;
			continue;
		}

		/* don't follow symlink unless told so */
		if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
			continue;

		/* will be false for symlinked dirs */
		if (S_ISDIR(st.st_mode)) {
			/* recursively follow dirs */
			if ((spec & WS_RECURSIVE))
				walk_recur(fn, reg, spec);

			if (!(spec & WS_MATCHDIRS)) continue;
		}

		/* pattern match */
		if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
	}

	if (dir) closedir(dir);
	return res ? res : errno ? WALK_BADIO : WALK_OK;
}

int walk_dir(char *dname, char *pattern, int spec)
{
	regex_t r;
	int res;
	if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
		return WALK_BADPATTERN;
	res = walk_recur(dname, &r, spec);
	regfree(&r);

	return res;
}

int main()
{
	int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
	switch(r) {
	case WALK_OK:		break;
	case WALK_BADIO:	err(1, "IO error");
	case WALK_BADPATTERN:	err(1, "Bad pattern");
	case WALK_NAMETOOLONG:	err(1, "Filename too long");
	default:
		err(1, "Unknown error?");
	}
	return 0;
}


-- Compile with: ghc -O2 -fllvm -fforce-recomp -threaded --make
{-# LANGUAGE BangPatterns #-}
module Main where

import System.Random

import Data.Word
import Data.Array.Repa as Repa
import Data.Array.Repa.IO.BMP

{-# INLINE sqDistance #-}
sqDistance :: Word32 -> Word32 -> Word32 -> Word32 -> Word32
sqDistance !x1 !y1 !x2 !y2 = ((x1-x2)^2) + ((y1-y2)^2)

centers :: Int -> Int -> Array U DIM2 Word32
centers nCenters nCells =
    fromListUnboxed (Z :. nCenters :. 2) $ take (2*nCenters) $ randomRs (0, fromIntegral nCells) (mkStdGen 1)

applyReduce2 arr f =
    traverse arr (\(i :. j) -> i) $ \lookup (Z:.i) ->
        f (lookup (Z:.i:.0)) (lookup (Z:.i:.1))

minimize1D arr = foldS f h t
  where
    indexed arr = traverse arr id (\src idx@(Z :. i) -> (src idx, (fromIntegral i)))
    (Z :. n) = extent arr
    iarr = indexed arr
    h = iarr ! (Z :. 0)
    t = extract (Z :. 1) (Z :. (n-1)) iarr

    f min@(!valMin, !iMin ) x@(!val, !i) | val < valMin = x
                                         | otherwise = min

voronoi :: Int -> Int -> Array D DIM2 Word32
voronoi nCenters nCells =
    let
      {-# INLINE cellReducer #-}
      cellReducer = applyReduce2 (centers nCenters nCells)
      {-# INLINE nearestCenterIndex #-}
      nearestCenterIndex = snd . (Repa.! Z) . minimize1D
    in
      Repa.fromFunction (Z :. nCells :. nCells :: DIM2) $ \ (Z:.i:.j) ->
          nearestCenterIndex $ cellReducer (sqDistance (fromIntegral i) (fromIntegral j))

genColorTable :: Int -> Array U DIM1 (Word8, Word8, Word8)
genColorTable n = fromListUnboxed (Z :. n) $ zip3 l1 l2 l3
    where
      randoms = randomRs (0,255) (mkStdGen 1)
      (l1, rest1) = splitAt n randoms
      (l2, rest2) = splitAt n rest1
      l3 = take n rest2

colorize :: Array U DIM1 (Word8, Word8, Word8) -> Array D DIM2 Word32 -> Array D DIM2 (Word8, Word8, Word8)
colorize ctable = Repa.map $ \x -> ctable Repa.! (Z:. fromIntegral x)

main = do
  let nsites = 150
  let ctable = genColorTable nsites
  voro <- computeP $ colorize ctable (voronoi nsites 512) :: IO (Array U DIM2 (Word8, Word8, Word8))
  writeImageToBMP "out.bmp" voro


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace RosettaRecursiveDirectory
{
    class Program
    {
        static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)
        {
            var directoryStack = new Stack<DirectoryInfo>();
            directoryStack.Push(new DirectoryInfo(rootPath));
            while (directoryStack.Count > 0)
            {
                var dir = directoryStack.Pop();
                try
                {
                    foreach (var i in dir.GetDirectories())
                        directoryStack.Push(i);
                }
                catch (UnauthorizedAccessException) {
                    continue; // We don't have access to this directory, so skip it
                }
                foreach (var f in dir.GetFiles().Where(Pattern)) // "Pattern" is a function
                    yield return f;
            }
        }
        static void Main(string[] args)
        {
            // Print the full path of all .wmv files that are somewhere in the C:\Windows directory or its subdirectories
            foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv"))
                Console.WriteLine(file.FullName);
            Console.WriteLine("Done.");
        }
    }
}


#include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>

using namespace boost::filesystem;

int main()
{
  path current_dir("."); //
  boost::regex pattern("a.*"); // list all files starting with a
  for (recursive_directory_iterator iter(current_dir), end;
       iter != end;
       ++iter)
  {
    std::string name = iter->path().filename().string();
    if (regex_match(name, pattern))
      std::cout << iter->path() << "\n";
  }
}


link graphics,printf,strings

record site(x,y,colour)  # site data position and colour
invocable all            # needed for string metrics

procedure main(A)  # voronoi

&window := open("Voronoi","g","bg=black") | stop("Unable to open window")

WAttrib("canvas=hidden")   # figure out maximal size width & height
WAttrib(sprintf("size=%d,%d",WAttrib("displaywidth"),WAttrib("displayheight")))
WAttrib("canvas=maximal")
height := WAttrib("height")
width  := WAttrib("width")

metrics := ["hypot","taxi","taxi3"]  # different metrics

while case a := get(A) of {          # command line arguments
  "--sites"  | "-s" : sites  := 0 < integer(a := get(A)) | runerr(205,a)
  "--height" | "-h" : height := 0 < (height >= integer(a := get(A))) | runerr(205,a)
  "--width"  | "-w" : width  := 0 < (width  >= integer(a := get(A))) | runerr(205,a)
  "--metric" | "-m" : metric := ((a := get(A)) == !metrics) | runerr(205,a)
  "--help"   | "-?" : write("Usage:\n voronoi [[--sites|-s] n] ",
			    "[[--height|-h] pixels] [[--width|-w] pixels]",
			    "[[--metric|-m] metric_procedure]",
			    "[--help|-?]\n\n")
  }

/metric := metrics[1]                     # default to normal
/sites := ?(r := integer(.1*width)) + r   # sites = random .1 to .2 of width if not given

WAttrib(sprintf("label=Voronoi %dx%d %d %s",width,height,sites,metric))
WAttrib(sprintf("size=%d,%d",width,height))

x := "0123456789abcdef"    # hex for random sites (colour)
siteL := []
every 1 to sites do        # random sites
  put(siteL, site(?width,?height,cat("#",?x,?x,?x,?x,?x,?x)))

VoronoiDiagram(width,height,siteL,metric)  # Voronoi-ize it
WDone()
end

procedure hypot(x,y,site)  # normal metric
return sqrt((x-site.x)^2 + (y-site.y)^2)
end

procedure taxi(x,y,site)   # "taxi" metric
return abs(x-site.x)+abs(y-site.y)
end

procedure taxi3(x,y,site)  # copied from a commented out version (TCL)
return (abs(x-site.x)^3+abs(y-site.y)^3)^(.3)
end

procedure VoronoiDiagram(width,height,siteL,metric)
   /metric := hypot
   every y := 1 to height & x := 1 to width do {
      dist := width+height         # anything larger than diagonal
      every site := !siteL do {
         if dist < (dt :=  metric(x,y,site)) then next  # skip
         else if dist >:= dt then Fg(site.colour)       # site
         else Fg("#000000")                             # unowned
         DrawPoint(x,y)
         }
      }

   Fg("Black")
   every site := !siteL do                              # mark sites
      DrawCircle(site.x,site.y,1)
end


Class Utils.File [ Abstract ]
{

ClassMethod WalkTree(pDir As %String = "", pMask As %String = "*.*") As %Status
{
	// do some validation
	If pDir="" Quit $$$ERROR($$$GeneralError, "No directory specified.")

	// search input directory for files matching wildcard
	Set fs=##class(%ResultSet).%New("%File.FileSet")
	Set sc=fs.Execute(pDir, pMask)
	While (fs.Next()) {
		Write !, fs.Name
		// sub-directory
		If fs.Type="D" Set sc=..WalkTree(fs.Name, pMask)
	}

	// finished
	Quit $$$OK
}

}


(use '[clojure.java.io])

(defn walk [dirpath pattern]
  (doall (filter #(re-matches pattern (.getName %))
                 (file-seq (file dirpath)))))

(map #(println (.getPath %)) (walk "src" #".*\.clj"))


fs = require 'fs'

walk = (dir, f_match, f_visit) ->
  _walk = (dir) ->
    fns = fs.readdirSync dir
    for fn in fns
      fn = dir + '/' + fn
      if f_match fn
        f_visit fn
      if fs.statSync(fn).isDirectory()
        _walk fn
  _walk(dir)

dir = '..'
matcher = (fn) -> fn.match /\.coffee/
action = console.log
walk dir, matcher, action


NB. (number of points) voronoi (shape)
NB. Generates an array of indices of the nearest point
voronoi =: 4 :0
  p =. (x,2) [email protected]$ y
  (i.<./)@:(+/@:*:@:-"1&p)"1 ,"0/&i./ y
)

load'viewmat'
viewmat 25 voronoi 500 500


import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

public class Voronoi extends JFrame {
	static double p = 3;
	static BufferedImage I;
	static int px[], py[], color[], cells = 100, size = 1000;

	public Voronoi() {
		super("Voronoi Diagram");
		setBounds(0, 0, size, size);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		int n = 0;
		Random rand = new Random();
		I = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
		px = new int[cells];
		py = new int[cells];
		color = new int[cells];
		for (int i = 0; i < cells; i++) {
			px[i] = rand.nextInt(size);
			py[i] = rand.nextInt(size);
			color[i] = rand.nextInt(16777215);

		}
		for (int x = 0; x < size; x++) {
			for (int y = 0; y < size; y++) {
				n = 0;
				for (byte i = 0; i < cells; i++) {
					if (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {
						n = i;

					}
				}
				I.setRGB(x, y, color[n]);

			}
		}

		Graphics2D g = I.createGraphics();
		g.setColor(Color.BLACK);
		for (int i = 0; i < cells; i++) {
			g.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));
		}

		try {
			ImageIO.write(I, "png", new File("voronoi.png"));
		} catch (IOException e) {

		}

	}

	public void paint(Graphics g) {
		g.drawImage(I, 0, 0, this);
	}

	static double distance(int x1, int x2, int y1, int y2) {
		double d;
	    d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); // Euclidian
	//  d = Math.abs(x1 - x2) + Math.abs(y1 - y2); // Manhattan
	//  d = Math.pow(Math.pow(Math.abs(x1 - x2), p) + Math.pow(Math.abs(y1 - y2), p), (1 / p)); // Minkovski
	  	return d;
	}

	public static void main(String[] args) {
		new Voronoi().setVisible(true);
	}
}


(ql:quickload :cl-fad)
(defun mapc-directory-tree (fn directory &key (depth-first-p t))
  (dolist (entry (cl-fad:list-directory directory))
    (unless depth-first-p
      (funcall fn entry))
    (when (cl-fad:directory-pathname-p entry)
      (mapc-directory-tree fn entry))
    (when depth-first-p
      (funcall fn entry))))


void main() {
    import std.stdio, std.file;

    // Recursive breadth-first scan (use SpanMode.depth for
    // a depth-first scan):
    dirEntries("", "*.d", SpanMode.breadth).writeln;
}


program Walk_a_directory;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.IOUtils;

var
  Files: TArray<string>;
  FileName, Directory: string;

begin
  Directory := TDirectory.GetCurrentDirectory;  // dir = '.', work to
  Files := TDirectory.GetFiles(Directory, '*.*', TSearchOption.soAllDirectories);

  for FileName in Files do
  begin
    Writeln(FileName);
  end;

  Readln;
end.


<title>Voronoi diagram</title>

  Please input number of sites:
  <input id="sites" value=100 type="number" min="10" max="150" size="3">
  Metric:
  <select id="mt">
    <option value=1 selected>Euclidean</option>
    <option value=2>Manhattan</option>
    <option value=3>Minkovski</option>
  </select>
  <input type="button" value="Plot it!" onclick="pVoronoiD();">

Voronoi diagram

  <canvas id="cvsId" width="640" height="640" style="border: 2px inset;"></canvas>


def walkTree(directory, pattern) {
  for name => file in directory {
    if (name =~ rx`.*$pattern.*`) {
      println(file.getPath())
    }
    if (file.isDirectory()) {
      walkTree(file, pattern)
    }
  }
}


defmodule Walk_directory do
  def recursive(dir \\ ".") do
    Enum.each(File.ls!(dir), fn file ->
      IO.puts fname = "#{dir}/#{file}"
      if File.dir?(fname), do: recursive(fname)
    end)
  end
end

Walk_directory.recursive


ELISP> (directory-files-recursively "/tmp/el" "\\.el$")
("/tmp/el/1/c.el" "/tmp/el/a.el" "/tmp/el/b.el")


walk_dir(Path, Pattern) ->
        filelib:fold_files(
                Path,
                Pattern,
                true, % Recurse
                fun(File, Accumulator) -> [File|Accumulator] end,
                []
        )


using Images
function voronoi(w, h, n_centroids)
    dist = (point,vector) -> sqrt.((point[1].-vector[:,1]).^2 .+ (point[2].-vector[:,2]).^2)
    dots = [rand(1:h, n_centroids) rand(1:w, n_centroids) rand(RGB{N0f8}, n_centroids)]
    img  = zeros(RGB{N0f8}, h, w)
    for x in 1:h, y in 1:w
        distances = dist([x,y],dots) # distance
        nn = findmin(distances)[2]
        img[x,y]  = dots[nn,:][3]
    end
    return img
end
img = voronoi(800, 600, 200)


// version 1.1.3

import java.awt.Color
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.geom.Ellipse2D
import java.awt.image.BufferedImage
import java.util.Random
import javax.swing.JFrame

fun distSq(x1: Int, x2: Int, y1: Int, y2: Int): Int {
    val x = x1 - x2
    val y = y1 - y2
    return x * x + y * y
}

class Voronoi(val cells: Int, val size: Int) : JFrame("Voronoi Diagram") {
    val bi: BufferedImage

    init {
        setBounds(0, 0, size, size)
        defaultCloseOperation = EXIT_ON_CLOSE
        val r = Random()
        bi = BufferedImage(size, size, BufferedImage.TYPE_INT_RGB)
        val px = IntArray(cells) { r.nextInt(size) }
        val py = IntArray(cells) { r.nextInt(size) }
        val cl = IntArray(cells) { r.nextInt(16777215) }
        for (x in 0 until size) {
            for (y in 0 until size) {
                var n = 0
                for (i in 0 until cells) {
                    if (distSq(px[i], x, py[i], y) < distSq(px[n], x, py[n], y)) n = i
                }
                bi.setRGB(x, y, cl[n])
            }
        }
        val g = bi.createGraphics()
        g.color = Color.BLACK
        for (i in 0 until cells) {
            g.fill(Ellipse2D.Double(px[i] - 2.5, py[i] - 2.5, 5.0, 5.0))
        }
    }

    override fun paint(g: Graphics) {
        g.drawImage(bi, 0, 0, this)
    }
}

fun main(args: Array<String>) {
    Voronoi(70, 700).isVisible = true
}


open System.IO

let rec getAllFiles dir pattern =
    seq { yield! Directory.EnumerateFiles(dir, pattern)
          for d in Directory.EnumerateDirectories(dir) do
              yield! getAllFiles d pattern }

getAllFiles "c:\\temp" "*.xml"
|> Seq.iter (printfn "%s")


USE: io.directories.search

"." t [
    dup ".factor" tail? [ print ] [ drop ] if
] each-file


require unix/filestat.fs
require unix/libc.fs

: $append ( from len to -- )   2DUP >R >R  COUNT + SWAP MOVE  R> [email protected] [email protected] + R> C! ;

defer ls-filter

: dots? ( name len -- ? )   drop [email protected] [char] . = ;

file-stat buffer: statbuf

: isdir ( addr u -- flag )
    statbuf lstat ?ior  statbuf st_mode [email protected] S_IFMT and S_IFDIR = ;

: (ls-r) ( dir len -- )
  pad [email protected] >r  pad $append  s" /" pad $append
  pad count open-dir if  drop  r> pad c!  exit  then  ( dirid)
  begin
    dup pad count + 256 rot read-dir throw
  while
    pad count + over dots? 0= if   \ ignore all hidden names
      dup pad count rot + 2dup ls-filter if
        cr 2dup type
      then
      isdir if
        pad count + swap recurse
      else drop then
    else drop then
  repeat
  drop  r> pad c!
  close-dir throw
;

: ls-r ( dir len -- )  0 pad c!  (ls-r) ;

: c-files ( str len -- ? )
  dup 3 < if 2drop false exit then
  + 1- dup [email protected] 32 or
   dup [char] c <> swap [char] h <> and if drop false exit then
  1- dup [email protected] [char] . <> if drop false exit then
  drop true ;
' c-files is ls-filter

: all-files ( str len -- ? )   2drop true ;
' all-files is ls-filter

s" ." ls-r cr


#include "dir.bi"

Sub listFiles(Byref filespec As String, Byval attrib As Integer)
    Dim As Integer count = 0
    Dim As String filename = Dir(filespec, attrib)
    Do While Len(filename) > 0
        count += 1
        Print filename
        filename = Dir()
    Loop
    Print !"\nArchives count:"; count
End Sub

Dim As String mylist = "C:\FreeBASIC\""
Print "Directories:"
listFiles(mylist & "*", fbDirectory)
Print
Print "Archive files:"
listFiles(mylist & "*", fbArchive)
Sleep


WindowWidth  =600
WindowHeight =600

sites = 100
xEdge = 400
yEdge = 400
graphicbox #w.gb1, 10, 10, xEdge, yEdge

open "Voronoi neighbourhoods" for window as #w

#w     "trapclose quit"
#w.gb1 "down ; fill black ; size 4"
#w.gb1 "font courier_new 12"

dim townX( sites), townY( sites), col$( sites)

for i =1 to sites
    townX( i) =int( xEdge *rnd( 1))
    townY( i) =int( yEdge *rnd( 1))
    col$( i) = int( 256 *rnd( 1)); " "; int( 256 *rnd( 1)); " "; int( 256 *rnd( 1))
    #w.gb1 "color "; col$( i)
    #w.gb1 "set "; townX( i); " "; townY( i)
next i

#w.gb1 "size 1"

dim nearestIndex(xEdge, yEdge)
dim dist(xEdge, yEdge)

start = time$("ms")

'fill distance table with distances from the first site
for x = 0 to xEdge - 1
    for y = 0 to yEdge - 1
        dist(x, y) = (townX(1) - x) ^ 2 + (townY(1) - y) ^ 2
        nearestIndex(x, y) = 1
    next y
next x

#w.gb1 "color darkblue"
'for other towns
for i = 2 to sites
    'display some progress
    #w.gb1 "place 0 20"
    #w.gb1 "\computing: "; using("###.#", i / sites * 100); "%"
    'look left
    for x = townX(i) to 0 step -1
        if not(checkRow(i, x,0, yEdge - 1)) then exit for
    next x
    'look right
    for x = townX(i) + 1 to xEdge - 1
        if not(checkRow(i, x, 0, yEdge - 1)) then exit for
    next x
    scan
next i

for x = 0 to xEdge - 1
    for y =0 to yEdge - 1
        #w.gb1 "color "; col$(nearestIndex(x, y))
        startY = y
        nearest = nearestIndex(x, y)
        for y = y + 1 to yEdge
            if nearestIndex(x, y) <> nearest then y = y - 1 : exit for
        next y
        #w.gb1 "line "; x; " "; startY; " "; x; " "; y + 1
    next y
next x

#w.gb1 "color black; size 4"
for i =1 to sites
    #w.gb1 "set "; townX( i); " "; townY( i)
next i
print time$("ms") - start
wait

sub quit w$
    close #w$
    end
end sub

function checkRow(site, x, startY, endY)
    dxSquared = (townX(site) - x) ^ 2
    for y = startY to endY
         dSquared = (townY(site) - y) ^ 2 + dxSquared
         if dSquared <= dist(x, y) then
             dist(x, y) = dSquared
             nearestIndex(x, y) = site
             checkRow = 1
         end if
    next y
end function


Public Sub Main()
Dim sTemp As String

For Each sTemp In RDir("/etc", "*.d")
  Print sTemp
Next

End


Walk := function(name, op)
	local dir, file, e;
	dir := Directory(name);
	for e in SortedList(DirectoryContents(name)) do
		file := Filename(dir, e);
		if IsDirectoryPath(file) then
			if not (e in [".", ".."]) then
				Walk(file, op);
			fi;
		else
			op(file);
		fi;
	od;
end;

# This will print filenames
Walk(".", Display);


package main

import (
    "fmt"
    "os"
    "path/filepath"
)

func VisitFile(fp string, fi os.FileInfo, err error) error {
    if err != nil {
        fmt.Println(err) // can't walk here,
        return nil       // but continue walking elsewhere
    }
    if fi.IsDir() {
        return nil // not a file.  ignore.
    }
    matched, err := filepath.Match("*.mp3", fi.Name())
    if err != nil {
        fmt.Println(err) // malformed pattern
        return err       // this is fatal.
    }
    if matched {
        fmt.Println(fp)
    }
    return nil
}

func main() {
    filepath.Walk("/", VisitFile)
}


function love.load( )
	love.math.setRandomSeed( os.time( ) ) --set the random seed
	keys = { } --an empty table where we will store key presses
	number_cells = 50 --the number of cells we want in our diagram
	--draw the voronoi diagram to a canvas
	voronoiDiagram = generateVoronoi( love.graphics.getWidth( ), love.graphics.getHeight( ), number_cells )
end

function hypot( x, y )
	return math.sqrt( x*x + y*y )
end

function generateVoronoi( width, height, num_cells )
	canvas = love.graphics.newCanvas( width, height )
	local imgx = canvas:getWidth( )
	local imgy = canvas:getHeight( )
	local nx = { }
	local ny = { }
	local nr = { }
	local ng = { }
	local nb = { }
	for a = 1, num_cells do
	table.insert( nx, love.math.random( 0, imgx ) )
	table.insert( ny, love.math.random( 0, imgy ) )
	table.insert( nr, love.math.random( 0, 1 ) )
	table.insert( ng, love.math.random( 0, 1 ) )
	table.insert( nb, love.math.random( 0, 1 ) )
	end
	love.graphics.setColor( { 1, 1, 1 } )
	love.graphics.setCanvas( canvas )
	for y = 1, imgy do
	for x = 1, imgx do
			dmin = hypot( imgx-1, imgy-1 )
		j = -1
		for i = 1, num_cells do
		d = hypot( nx[i]-x, ny[i]-y )
		if d < dmin then
	 	    dmin = d
			j = i
		end
		end
		love.graphics.setColor( { nr[j], ng[j], nb[j] } )
		love.graphics.points( x, y )
	end
	end
	--reset color
	love.graphics.setColor( { 1, 1, 1 } )
	--draw points
	for b = 1, num_cells do
	love.graphics.points( nx[b], ny[b] )
	end
	love.graphics.setCanvas( )
	return canvas
end

--RENDER
function love.draw( )
	--reset color
	love.graphics.setColor( { 1, 1, 1 } )
	--draw diagram
	love.graphics.draw( voronoiDiagram )
	--draw drop shadow text
	love.graphics.setColor( { 0, 0, 0 } )
	love.graphics.print( "space: regenerate\nesc: quit", 1, 1 )
	--draw text
	love.graphics.setColor( { 0.7, 0.7, 0 } )
	love.graphics.print( "space: regenerate\nesc: quit" )
end

--CONTROL
function love.keyreleased( key )
	if key == 'space' then
	voronoiDiagram = generateVoronoi( love.graphics.getWidth( ), love.graphics.getHeight( ), number_cells )
	elseif key == 'escape' then
	love.event.quit( )
	end
end


new File('.').eachFileRecurse {
  if (it.name =~ /.*\.txt/) println it;
}


Start,Find,Files and Folders,Dropdown: Look in>My Documents,
Inputbox: filename>m*.txt,Button:Search


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


###########################
#  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" ) & ( d := open(s) ) then {
      D := [s]
      while f := read(d) do
         if not ( ".." ? =f ) then          # skip . and ..
            D |||:= getdirs(s || "/" ||f)
      close(d)
      return D
      }
end

#########################
#  A threaded solution  #
#########################

import threads

global n,           # number of the concurrently running threads
       maxT,        # Max number of concurrent threads ("soft limit")
       tot_threads  # the total number of threads created in the program

procedure main(argv)
   target := argv[1] | stop("Usage: tdir [dir name] [#threads]. #threads default to 2* the number of cores in the machine.")
   tot_threads := n := 1
   maxT := ( integer(argv[2])|
	    (&features? if ="CPU cores " then cores := integer(tab(0)) * 2) | # available cores * 2
   	    4) # default to 4 threads
   t := milliseconds()
   L := getdirs(target)  # writes out all directories from the current directory down
   write((*\L)| 0, " directories in ", milliseconds() - t,
	           " ms using ", maxT, "-concurrent/", tot_threads, "-total threads" )
end

procedure getdirs(s)  # return a list of directories beneath the directory 's'
local D,d,f, thrd

if ( stat(s).mode ? ="d" ) & ( d := open(s) ) then {
      D := [s]
      while f := read(d) do
         if not ( ".." ? =f ) then          # skip . and ..
            if n>=maxT then # max thread count reached
               D |||:= getdirs(s || "/" ||f)
            else # spawn a new thread for this directory
	       {/thrd:=[]; n +:= 1; put(thrd, thread getdirs(s || "/" ||f))}

      close(d)

      if \thrd then{  # If I have threads, collect their results
         tot_threads +:= *thrd
         n -:= 1      # allow new threads to be spawned while I'm waiting/collecting results
	 every wait(th := !thrd) do { # wait for the thread to finish
	    n -:= 1
	    D |||:= <@th   # If the thread produced a result, it is going to be
	                   # stored in its "outbox", <@th in this case serves as
	                   # a deferred return since the thread was created by
			   # thread getdirs(s || "/" ||f)
	                   # this is similar to co-expression activation semantics
            }
         n +:= 1
         }
      return D
      }
end


from sequtils import newSeqWith
from random import rand, randomize
from times import now
import libgd

const
  img_width  = 400
  img_height = 300
  nSites = 20

proc dot(x, y: int): int = x * x + y * y

proc generateVoronoi(img: gdImagePtr) =

  randomize(cast[int64](now()))

  # random sites
  let sx = newSeqWith(nSites, rand(img_width))
  let sy = newSeqWith(nSites, rand(img_height))

  # generate a random color for each site
  let sc = newSeqWith(nSites, img.setColor(rand(255), rand(255), rand(255)))

  # generate diagram by coloring each pixel with color of nearest site
  for x in 0 ..< img_width:
    for y in 0 ..< img_height:
      var dMin = dot(img_width, img_height)
      var sMin: int
      for s in 0 ..< nSites:
        if (let d = dot(sx[s] - x, sy[s] - y); d) < dMin:
          (sMin, dMin) = (s, d)

      img.setPixel(point=[x, y], color=sc[sMin])

  # mark each site with a black box
  let black = img.setColor(0x000000)
  for s in 0 ..< nSites:
    img.drawRectangle(
      startCorner=[sx[s] - 2, sy[s] - 2],
      endCorner=[sx[s] + 2, sy[s] + 2],
      color=black,
      fill=true)

proc main() =

  withGd imageCreate(img_width, img_height, trueColor=true) as img:
    img.generateVoronoi()

    let png_out = open("outputs/voronoi_diagram.png", fmWrite)
    img.writePng(png_out)
    png_out.close()

main()


let n_sites = 220

let size_x = 640
let size_y = 480

let sq2 ~x ~y =
  (x * x + y * y)

let rand_int_range a b =
  a + Random.int (b - a + 1)

let nearest_site ~site ~x ~y =
  let ret = ref 0 in
  let dist = ref 0 in
  Array.iteri (fun k (sx, sy) ->
    let d = sq2 (x - sx) (y - sy) in
    if k = 0 || d < !dist then begin
      dist := d;
      ret := k;
    end
  ) site;
  !ret

let gen_map ~site ~rgb =
  let nearest = Array.make (size_x * size_y) 0 in
  let buf = Bytes.create (3 * size_x * size_y) in

  for y = 0 to pred size_y do
    for x = 0 to pred size_x do
      nearest.(y * size_x + x) <-
        nearest_site ~site ~x ~y;
    done;
  done;

  for i = 0 to pred (size_y * size_x) do
    let j = i * 3 in
    let r, g, b = rgb.(nearest.(i)) in
    Bytes.set buf (j+0) (char_of_int r);
    Bytes.set buf (j+1) (char_of_int g);
    Bytes.set buf (j+2) (char_of_int b);
  done;

  Printf.printf "P6\n%d %d\n255\n" size_x size_y;
  print_bytes buf;
;;

let () =
  Random.self_init ();
  let site =
    Array.init n_sites (fun i ->
      (Random.int size_x,
       Random.int size_y))
  in
  let rgb =
    Array.init n_sites (fun i ->
      (rand_int_range 160 255,
       rand_int_range  40 160,
       rand_int_range  20 140))
  in
  gen_map ~site ~rgb


result = file_search( directory, '*.txt', count=cc )


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 A file object defining the top directory
     **/
    public static void walkin(File dir) {
        String pattern = ".mp3";

        File listFile[] = dir.listFiles();
        if (listFile != null) {
            for (int i=0; i<listFile.length; i++) {
                if (listFile[i].isDirectory()) {
                    walkin(listFile[i]);
                } else {
                    if (listFile[i].getName().endsWith(pattern)) {
                        System.out.println(listFile[i].getPath());
                    }
                }
            }
        }
    }
}


F water_collected(tower)
   V l = tower.len
   V highest_left = [0] [+] (1 .< l).map(n -> max(@tower[0 .< n]))
   V highest_right = (1 .< l).map(n -> max(@tower[n .< @l])) [+] [0]
   V water_level = (0 .< l).map(n -> max(min(@highest_left[n], @highest_right[n]) - @tower[n], 0))
   print(‘highest_left:   ’highest_left)
   print(‘highest_right:  ’highest_right)
   print(‘water_level:    ’water_level)
   print(‘tower_level:    ’tower)
   print(‘total_water:    ’sum(water_level))
   print(‘’)
   R sum(water_level)

V towers = [
   [1, 5, 3, 7, 2],
   [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
   [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
   [5, 5, 5, 5],
   [5, 6, 7, 8],
   [8, 7, 7, 6],
   [6, 7, 10, 7, 6]]

print(towers.map(tower -> water_collected(tower)))


use strict;
use warnings;
use Imager;

my %type = (
     Taxicab   => sub { my($px, $py, $x, $y) = @_; abs($px - $x)    + abs($py - $y)    },
     Euclidean => sub { my($px, $py, $x, $y) = @_;    ($px - $x)**2 +    ($py - $y)**2 },
     Minkowski => sub { my($px, $py, $x, $y) = @_; abs($px - $x)**3 + abs($py - $y)**3 },
);

my($xmax, $ymax) = (400, 400);
my @domains;
for (1..30) {
    push @domains, {
        x   => int 5 + rand $xmax-10,
        y   => int 5 + rand $ymax-10,
        rgb => [int rand 255, int rand 255, int rand 255]
    }
}

for my $type (keys %type) {
    our $img = Imager->new(xsize => $xmax, ysize => $ymax, channels => 3);
    voronoi($type, $xmax, $ymax, @domains);
    dot(1,@domains);
    $img->write(file => "voronoi-$type.png");

    sub voronoi {
        my($type, $xmax, $ymax, @d) = @_;
        for my $x (0..$xmax) {
            for my $y (0..$ymax) {
                my $i = 0;
                my $d = 10e6;
                for (0..$#d) {
                    my $dd = &{$type{$type}}($d[$_]{'x'}, $d[$_]{'y'}, $x, $y);
                    if ($dd < $d) { $d = $dd; $i = $_ }
                }
                $img->setpixel(x => $x, y => $y, color => $d[$i]{rgb} );
            }
        }
    }

    sub dot {
        my($radius, @d) = @_;
        for (0..$#d) {
            my $dx = $d[$_]{'x'};
            my $dy = $d[$_]{'y'};
            for my $x ($dx-$radius .. $dx+$radius) {
                for my $y ($dy-$radius .. $dy+$radius) {
                    $img->setpixel(x => $x, y => $y, color => [0,0,0]);
                }
            }
        }
    }
}


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("Folders in " + folder_name + " matching '" + re_pattern + "':");
    walkDirectoryFilter(subfolders, re_pattern);

    WScript.Echo();
    var en = new Enumerator(subfolders);
    while (! en.atEnd()) {
        var subfolder = en.item();
        walkDirectoryTree(subfolder, folder_name + "/" + subfolder.name, re_pattern);
        en.moveNext();
    }
}

function walkDirectoryFilter(items, re_pattern) {
    var e = new Enumerator(items);
    while (! e.atEnd()) {
        var item = e.item();
        if (item.name.match(re_pattern))
            WScript.Echo(item.name);
        e.moveNext();
    }
}

walkDirectoryTree(dir, dir.name, '\\.txt$');


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


	org	100h
	jmp	demo
	;;;	Calculate the amount of water a row of towers will hold
	;;;	Note: this will destroy the input array.
	;;;	Input: DE = tower array, BC = length of array
	;;;	Output: A = amount of water
water:	xra	a	; Start with no water
	sta	w_out+1
wscanr:	mov	h,d	; HL = right edge
	mov	l,e
	dad	b
wscrlp:	dcx	h
	call	cmp16	; Reached beginning?
	jnc	w_out	; Then stop
	mov	a,m	; Otherwise, if current tower is zero
	ora	a
	jz	wscrlp	; Then keep scanning
	push	b	; Keep length
	push	d	; Keep array begin
	mvi	b,0	; No blocks yet
	xchg		; HL = left scanning edge, DE = right
wscanl:	mov	a,m	; Get current column
	ora	a	; Is zero?
	jz	wunit	; Then see if an unit of water must be added
	dcr	m	; Otherwise, decrease column
	inr	b	; Increase blocks
	jmp	wnext
wunit:	mov	a,b	; Any blocks?
	ora	a
	jz	wnext
	lda	w_out+1	; If so, add water
	inr	a
	sta	w_out+1
wnext:	inx	h	; Next column
	call	cmp16
	jnc	wscanl	; Until right edge reached
	mov	a,b
	cmc		; Check if more than 1 block left
	rar
	ora	a
	pop 	d	; Restore array begin
	pop	b	; and length
	jnz	wscanr	; If more than 1 block, keep scanning
w_out:	mvi	a,0	; Load water into A
	ret
	;;;	16-bit compare DE to HL
cmp16:	mov	a,d
	cmp	h
	rnz
	mov	a,e
	cmp 	l
	ret
	;;;	Calculate and print the amount of water for each input
demo:	lxi	h,series
load:	mov	e,m	; Load pointer
	inx	h
	mov	d,m
	inx	h
	mov	c,m	; Load length
	inx	h
	mov	b,m
	inx	h
	mov	a,d	; If pointer is zero,
	ora	e
	rz		; stop.
	push 	h	; Otherwise, save the series pointer
	call	water	; Calculate amount of water
	call	printa	; Output amount of water
	pop	h	; Restore series pointer
	jmp	load	; Load next example
	;;;	Print A as integer value
printa:	lxi	d,num	; Pointer to number string
	mvi	c,10	; Divisor
digit:	mvi	b,-1	; Quotient
dloop:	inr	b	; Divide (by trial subtraction)
	sub	c
	jnc	dloop
	adi	'0'+10	; ASCII digit from remainder
	dcx	d	; Store ASCII digit
	stax	d
	mov	a,b	; Continue with quotient
	ana	a	; If not zero
	jnz	digit
	mvi	c,9	; 9 = CP/M print string syscall
	jmp	5	; Print number string
	db	'***'	; Output number placeholder
num:	db	' $'
	;;;	Series
t1:	db	1,5,3,7,2
t2:	db	5,3,7,2,6,4,5,9,1,2
t3:	db	2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1
t4:    	db	5,5,5,5
t5:	db	5,6,7,8
t6:    	db	8,7,7,6
t7:	db    	6,7,10,7,6
t_end:	equ	$
	;;;	Lengths and pointers
series:	dw	t1,t2-t1
	dw	t2,t3-t2
	dw	t3,t4-t3
	dw	t4,t5-t4
	dw	t5,t6-t5
	dw	t6,t7-t6
	dw	t7,t_end-t7
	dw	0


	cpu	8086
	org	100h
section	.text
	jmp	demo
	;;;	Calculate the amount of water a row of towers will hold
	;;;	Note: this will destroy the input array.
	;;;	Input: DX = tower array, CX = length of array
	;;;	Output: AX = amount of water
water:	xor	ax,ax		; Amount of water starts at zero
	xor	bx,bx		; BH = zero, BL = block count
.scanr:	mov	di,dx		; DI = right edge of towers
	add	di,cx
.rloop:	dec	di
	cmp	di,dx		; Reached beginning?
	jl	.out		; Then calculation is done.
	cmp	bh,[di]		; Otherwise, if the tower is zero,
	je	.rloop		; Keep scanning
	xor	bl,bl		; Set block count to zero
	mov	si,dx		; SI = left scanning edge
.scanl:	cmp	bh,[si]		; Is the column empty?
	je	.unit		; Then see whether to add an unit of water
	dec	byte [si]	; Otherwise, remove block from tower
	inc	bx		; And count it
	jmp	.next
.unit:	test	bl,bl		; Any blocks?
	jz	.next
	inc	ax		; If so, add unit of water
.next:	inc	si		; Scan rightward
	cmp	si,di		; Reached the right edge?
	jbe	.scanl		; If not, keep going
	shr	bl,1		; If more than 1 block,
	jnz	.scanr		; Keep going
.out:	ret
	;;;	Calculate and print the amount of water for each input
demo:	mov	si,series
.loop:	lodsw			; Load pointer
	test	ax,ax		; If 0,
	jz	.done		; we're done.
	xchg	ax,dx
	lodsw			; Load length
	xchg	ax,cx
	push	si		; Keep array pointer
	call	water		; Calculate amount of water
	call	prax		; Print AX
	pop	si		; Restore array pointer
	jmp 	.loop
.done:	ret
	;;;	Print AX as number
prax:	mov	bx,num		; Pointer to end of number string
	mov	cx,10 		; Divisor
.dgt:	xor	dx,dx		; Divide by 10
	div	cx
	add	dl,'0'		; Add ASCII 0 to remainder
	dec	bx		; Store digit
	mov	[bx],dl
	test	ax,ax		; If number not zero yet
	jnz	.dgt		; Find rest of digits
	mov	dx,bx		; Print number string
	mov	ah,9
	int	21h
	ret
section	.data
	db	'*****'		; Output number placeholder
num:	db	' $'
	;;;	Series
t1:	db	1,5,3,7,2
t2:	db	5,3,7,2,6,4,5,9,1,2
t3:	db	2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1
t4:    	db	5,5,5,5
t5:	db	5,6,7,8
t6:    	db	8,7,7,6
t7:	db    	6,7,10,7,6
t_end:	equ	$
	;;;	Lengths and pointers
series:	dw	t1,t2-t1
	dw	t2,t3-t2
	dw	t3,t4-t3
	dw	t4,t5-t4
	dw	t5,t6-t5
	dw	t6,t7-t6
	dw	t7,t_end-t7
	dw	0


--
-- demo\rosetta\VoronoiDiagram.exw
-- ===============================
--
-- Can resize, double or halve the number of sites (press +/-), and toggle
--  between Euclid, Manhattan, and Minkowski (press e/m/w).
--
with javascript_semantics
include pGUI.e

Ihandle dlg, canvas, timer
cdCanvas cddbuffer, cdcanvas

-- Stop any current drawing process before starting a new one:
-- Without this it /is/ going to crash, if it tries to finish
-- drawing all 100 sites, when there are now only 50, for eg.
integer timer_active = 0

integer nsites = 200
integer last_width = -1, last_height
sequence siteX, siteY, siteC

enum EUCLID, MANHATTAN, MINKOWSKI

constant dmodes = {"Euclid", "Manhattan", "Minkowski"}

integer dmode = EUCLID,
        drawn = 0       -- (last dmode actually shown)

function distance(integer x1, integer y1, integer x2, integer y2)
    atom d
    x1 -= x2
    y1 -= y2
    switch dmode do
        case EUCLID:    d = x1*x1+y1*y1                       -- (no need for sqrt)
        case MANHATTAN: d = abs(x1)+abs(y1)
        case MINKOWSKI: d = power(abs(x1),3)+power(abs(y1),3) -- ("" power(d,1/3))
    end switch
    return d
end function

sequence nearestIndex, dist

function checkRow(integer site, integer x, integer height)
    bool res = false
    atom dxSquared
    integer x1 = siteX[site]-x
    switch dmode do
        case EUCLID:    dxSquared = x1*x1
        case MANHATTAN: dxSquared = abs(x1)
        case MINKOWSKI: dxSquared = power(abs(x1),3)
    end switch
    for y=1 to height do
--      atom dSquared = distance(siteX[site],siteY[site],x,y)   -- (sub-optimal..)
        atom dSquared
        integer y1 = siteY[site]-y
        switch dmode do
            case EUCLID:    dSquared = dxSquared+y1*y1
            case MANHATTAN: dSquared = dxSquared+abs(y1)
            case MINKOWSKI: dSquared = dxSquared+power(abs(y1),3)
        end switch
        if dSquared<=dist[x,y] then
            dist[x,y] = dSquared
            nearestIndex[x,y] = site
            res = true
        end if
    end for
    return res
end function

function redraw_cb(Ihandle /*ih*/)
    integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE")
    if width!=last_width
    or height!=last_height
    or nsites!=length(siteX) then
        if nsites<1 then nsites = 1 end if
        siteX = sq_rand(repeat(width,nsites))
        siteY = sq_rand(repeat(height,nsites))
        siteC = sq_rand(repeat(#FFFFFF,nsites))
        last_width = width
        last_height = height
        drawn = 0
    end if
    if drawn!=dmode             -- (prevent double-draw, and)
    and not timer_active then   -- (drawing when rug moved..)
        drawn = dmode
        cdCanvasActivate(cddbuffer)
        cdCanvasClear(cddbuffer)
        atom t0 = time(), t1
        t1 = time()+0.25
        nearestIndex = repeat(repeat(1,height),width)
        dist = repeat(repeat(0,height),width)
        -- fill distance table with distances from the first site
        integer x1 = siteX[1], y1 = siteY[1]
        for x=1 to width do
            for y=1 to height do
                dist[x,y] = distance(x1,y1,x,y)
            end for
            if timer_active then exit end if
        end for
        --for other towns
        for i=2 to nsites do
            -- look left
            for x=siteX[i] to 1 by -1 do
                if not checkRow(i, x, height) then exit end if
            end for
            -- look right
            for x=siteX[i]+1 to width do
                if not checkRow(i, x, height) then exit end if
            end for
            if timer_active then exit end if
            if time()>t1 then
                IupSetStrAttribute(dlg, "TITLE", "Voronoi diagram (generating - %3.2f%%)",{100*i/nsites})
                IupFlush()
                t1 = time()+0.25
            end if
        end for
        t1 = time()
        for y=1 to height do
            integer nearest = nearestIndex[1,y]
            integer s = 1
            for x=2 to width do
                if nearestIndex[x,y]<>nearest then
                    cdCanvasSetForeground(cddbuffer, siteC[nearest])
                    cdCanvasLine(cddbuffer, s-1, y-1, x-2, y-1)
                    nearest = nearestIndex[x,y]
                    s = x
                end if
            end for
            if timer_active then exit end if
            cdCanvasSetForeground(cddbuffer, siteC[nearest])
            cdCanvasLine(cddbuffer, s-1, y-1, width-1, y-1)
        end for
        if not timer_active then
            cdCanvasSetForeground(cddbuffer, CD_BLACK)
            for i=1 to nsites do
                cdCanvasSector(cddbuffer, siteX[i], siteY[i], 2, 2, 0, 360)
            end for
            cdCanvasFlush(cddbuffer)
            IupSetStrAttribute(dlg, "TITLE", "Voronoi diagram - %s, %dx%d, %d sites, %3.2fs",
                                    {dmodes[dmode],width,height,nsites,time()-t0})
        end if
    end if
    return IUP_DEFAULT
end function

function map_cb(Ihandle ih)
    cdcanvas = cdCreateCanvas(CD_IUP, ih)
    cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
    cdCanvasSetBackground(cddbuffer, CD_WHITE)
    cdCanvasSetForeground(cddbuffer, CD_BLACK)
    return IUP_DEFAULT
end function

function key_cb(Ihandle /*ih*/, atom c)
    if c=K_ESC then return IUP_CLOSE end if
    integer wasdmode = dmode
    switch c do
        case '+': nsites *= 2
        case '-': nsites = max(floor(nsites/2),1)
        case 'E','e': dmode = EUCLID
        case 'M','m': dmode = MANHATTAN
        case 'W','w': dmode = MINKOWSKI
    end switch
    if dmode!=wasdmode
    or nsites!=length(siteX) then
        -- give any current drawing process 0.1s to abandon:
        timer_active = 1
        IupStoreAttribute(timer, "RUN", "YES")
--      IupUpdate(canvas)
    end if
    return IUP_CONTINUE
end function

function timer_cb(Ihandle /*ih*/)
    timer_active = 0
    IupStoreAttribute(timer, "RUN", "NO")
    IupUpdate(canvas)
    return IUP_IGNORE
end function

procedure main()
    IupOpen()

    canvas = IupCanvas("RASTERSIZE=600x400")
    IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"),
                             "ACTION", Icallback("redraw_cb")})

    timer = IupTimer(Icallback("timer_cb"), 100, 0) -- (inactive)

    dlg = IupDialog(canvas,`TITLE="Voronoi diagram"`)
    IupSetCallback(dlg, "KEY_CB", Icallback("key_cb"))
    IupShow(dlg)
    IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation
    if platform()!=JS then
        IupMainLoop()
        IupClose()
    end if
end procedure

main()


// 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>) {
    val r = Regex("""^v(a|f).*\.h$""")  // get all C header files beginning with 'va' or 'vf'
    val files = walkDirectoryRecursively("/usr/include", r)
    for (file in files) println(file)
}


// care only about visible files and filter out any directories
define dir -> eachVisibleFilePath() => {
	return with name in self -> eachEntry where #name -> second != io_dir_dt_dir where not(#name -> first  ->  beginswith('.')) select .makeFullPath(#name -> first)
}

// care only about visible directories and filter out any files
define dir -> eachVisibleDir() => {
	return with name in self -> eachEntry where #name -> second == io_dir_dt_dir where not(#name -> first -> beginswith('.')) select dir(.makeFullPath(#name -> first + '/'))
}

// Recursively walk the directory tree and find all files and directories
// return only paths to files
define dir -> eachVisibleFilePathRecursive(-dirFilter = void) => {
	local(files = .eachVisibleFilePath)
	with dir in .eachVisibleDir
	where !#dirFilter || #dirFilter(#dir -> realPath)
	do {
		#files = tie(#files, #dir -> eachVisibleFilePathRecursive(-dirFilter = #dirFilter))
	}
	return #files
}

local(matchingfilenames = array)

with filepath in dir('/') -> eachVisibleFilePathRecursive
where #filepath -> endswith('.lasso')
let filename = #filepath -> split('/') -> last
do #matchingfilenames -> insert(#filename)

#matchingfilenames


function pathsForDirectoryAndWildcardPattern pDirectory, pWildcardPattern
   -- returns a return-delimited list of long file names
   -- the last character in the list is a return, unless the list is empty

   filter files(pDirectory) with pWildcardPattern
   repeat for each line tFile in it
      put pDirectory & slash & tFile & cr after tPaths
   end repeat

   filter folders(pDirectory) without ".."
   repeat for each line tFolder in it
      put pathsForDirectoryAndWildcardPattern(pDirectory & slash & tFolder, pWildcardPattern) after tPaths
   end repeat

   return tPaths
end pathsForDirectoryAndWildcardPattern


V 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]]
V demand = [‘A’ = 30, ‘B’ = 20, ‘C’ = 70, ‘D’ = 30, ‘E’ = 60]
V cols = sorted(demand.keys())
V supply = [‘W’ = 50, ‘X’ = 60, ‘Y’ = 50, ‘Z’ = 50]
V res = Dict(costs.keys().map(k -> (k, DefaultDict[Char, Int]())))
[Char = [Char]] g
L(x) supply.keys()
   g[x] = sorted(costs[x].keys(), key' g -> :costs[@x][g])
L(x) demand.keys()
   g[x] = sorted(costs.keys(), key' g -> :costs[g][@x])

L !g.empty
   [Char = Int] d
   L(x) demand.keys()
      d[x] = I g[x].len > 1 {(costs[g[x][1]][x] - costs[g[x][0]][x])} E costs[g[x][0]][x]
   [Char = Int] s
   L(x) supply.keys()
      s[x] = I g[x].len > 1 {(costs[x][g[x][1]] - costs[x][g[x][0]])} E costs[x][g[x][0]]
   V f = max(d.keys(), key' n -> @d[n])
   V t = max(s.keys(), key' n -> @s[n])
   (t, f) = I d[f] > s[t] {(f, g[f][0])} E (g[t][0], t)
   V v = min(supply[f], demand[t])
   res[f][t] += v
   demand[t] -= v
   I demand[t] == 0
      L(k, n) supply
         I n != 0
            g[k].remove(t)
      g.pop(t)
      demand.pop(t)
   supply[f] -= v
   I supply[f] == 0
      L(k, n) demand
         I n != 0
            g[k].remove(f)
      g.pop(f)
      supply.pop(f)

L(n) cols
   print("\t "n, end' ‘ ’)
print()
V cost = 0
L(g) sorted(costs.keys())
   print(g" \t", end' ‘ ’)
   L(n) cols
      V y = res[g][n]
      I y != 0
         print(y, end' ‘ ’)
      cost += y * costs[g][n]
      print("\t", end' ‘ ’)
   print()
print("\n\nTotal Cost =  "cost)


PROC PrintArray(BYTE ARRAY a BYTE len)
  BYTE i

  Put('[)
  FOR i=0 TO len-1
  DO
    IF i>0 THEN
      Put(32)
    FI
    PrintB(a(i))
  OD
  Put('])
RETURN

BYTE FUNC Max(BYTE ARRAY a BYTE start,stop)
  BYTE i,res

  res=0
  FOR i=start TO stop
  DO
    IF a(i)>res THEN
      res=a(i)
    FI
  OD
RETURN (res)

BYTE FUNC CalcWater(BYTE ARRAY a BYTE len)
  BYTE water,i,maxL,maxR,lev

  IF len<3 THEN
    RETURN (0)
  FI
  water=0
  FOR i=1 TO len-2
  DO
    maxL=Max(a,0,i-1)
    maxR=Max(a,i+1,len-1)
    IF maxL<maxR THEN
      lev=maxL
    ELSE
      lev=maxR
    FI
    IF a(i)<lev THEN
      water==+lev-a(i)
    FI
  OD
RETURN (water)

PROC Test(BYTE ARRAY a BYTE len)
  BYTE water

  water=CalcWater(a,len)
  PrintArray(a,len)
  PrintF(" holds %B water units%E%E",water)
RETURN

PROC Main()
  DEFINE COUNT="7"
  BYTE ARRAY
    a1=[1 5 3 7 2],
    a2=[5 3 7 2 6 4 5 9 1 2],
    a3=[2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1],
    a4=[5 5 5 5],
    a5=[5 6 7 8],
    a6=[8 7 7 6],
    a7=[6 7 10 7 6]

  Test(a1,5)
  Test(a2,10)
  Test(a3,16)
  Test(a4,4)
  Test(a5,4)
  Test(a6,4)
  Test(a7,5)
RETURN


with Ada.Text_IO;

procedure Water_Collected is

   type Bar_Index     is new Positive;
   type Natural_Array is array (Bar_Index range <>) of Natural;

   subtype Bar_Array   is Natural_Array;
   subtype Water_Array is Natural_Array;

   function Flood (Bars : Bar_Array; Forward : Boolean) return Water_Array is
      R : Water_Array (Bars'Range);
      H : Natural := 0;
   begin
      if Forward then
         for A in R'Range loop
            H     := Natural'Max (H, Bars (A));
            R (A) := H - Bars (A);
         end loop;
      else
         for A in reverse R'Range loop
            H     := Natural'Max (H, Bars (A));
            R (A) := H - Bars (A);
         end loop;
      end if;
      return R;
   end Flood;

   function Fold (Left, Right : Water_Array) return Water_Array is
      R : Water_Array (Left'Range);
   begin
      for A in R'Range loop
         R (A) := Natural'Min (Left (A), Right (A));
      end loop;
      return R;
   end Fold;

   function Fill (Bars : Bar_Array) return Water_Array
   is (Fold (Flood (Bars, Forward => True),
             Flood (Bars, Forward => False)));

   function Sum_Of (Bars : Natural_Array) return Natural is
      Sum : Natural := 0;
   begin
      for Bar of Bars loop
         Sum := Sum + Bar;
      end loop;
      return Sum;
   end Sum_Of;

   procedure Show (Bars : Bar_Array) is
      use Ada.Text_IO;
      Water : constant Water_Array := Fill (Bars);
   begin
      Put ("The series: [");
      for Bar of Bars loop
         Put (Bar'Image);
         Put (" ");
      end loop;
      Put ("] holds ");
      Put (Sum_Of (Water)'Image);
      Put (" units of water.");
      New_Line;
   end Show;

begin
   Show ((1, 5, 3, 7, 2));
   Show ((5, 3, 7, 2, 6, 4, 5, 9, 1, 2));
   Show ((2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1));
   Show ((5, 5, 5, 5));
   Show ((5, 6, 7, 8));
   Show ((8, 7, 7, 6));
   Show ((6, 7, 10, 7, 6));
end Water_Collected;


void setup() {
  size(500, 500);
  generateVoronoiDiagram(width, height, 25);
  saveFrame("VoronoiDiagram.png");
}

void generateVoronoiDiagram(int w, int h, int num_cells) {
  int nx[] = new int[num_cells];
  int ny[] = new int[num_cells];
  int nr[] = new int[num_cells];
  int ng[] = new int[num_cells];
  int nb[] = new int[num_cells];
  for (int n=0; n < num_cells; n++) {
    nx[n]=int(random(w));
    ny[n]=int(random(h));
    nr[n]=int(random(256));
    ng[n]=int(random(256));
    nb[n]=int(random(256));
    for (int y = 0; y < h; y++) {
      for (int x = 0; x < w; x++) {
        float dmin = dist(0, 0, w - 1, h - 1);
        int j = -1;
        for (int i=0; i < num_cells; i++) {
          float d = dist(0, 0, nx[i] - x, ny[i] - y);
          if (d < dmin) {
            dmin = d;
            j = i;
          }
        }
        set(x, y, color(nr[j], ng[j], nb[j]));
      }
    }
  }
}


local lfs = require("lfs")

-- This function takes two arguments:
-- - the directory to walk recursively;
-- - an optional function that takes a file name as argument, and returns a boolean.
function find(self, fn)
  return coroutine.wrap(function()
    for f in lfs.dir(self) do
      if f ~= "." and f ~= ".." then
        local _f = self .. "/" .. f
        if not fn or fn(_f) then
          coroutine.yield(_f)
        end
        if lfs.attributes(_f, "mode") == "directory" then
          for n in find(_f, fn) do
            coroutine.yield(n)
          end
        end
      end
    end
  end)
end

-- Examples
-- List all files and directories
for f in find("directory") do
  print(f)
end

-- List lua files
for f in find("directory", function(self) return self:match("%.lua$") end) do
  print(f)
end

-- List directories
for f in find("directory", function(self) return "directory" == lfs.attributes(self, "mode") end) do
  print(f)
end


FileNames["*"]
FileNames["*.png", $RootDirectory]
FileNames["*", {"*"}, Infinity]


function walk_a_directory_recursively(d, pattern)
	f = dir(fullfile(d,pattern));
	for k = 1:length(f)
		fprintf('%s\n',fullfile(d,f(k).name));
	end;

	f = dir(d);
	n = find([f.isdir]);
	for k=n(:)'
		if any(f(k).name~='.')
			walk_a_directory_recursively(fullfile(d,f(k).name), pattern);
		end;
	end;
end;


#include <stdio.h>
#include <limits.h>

#define TRUE 1
#define FALSE 0
#define N_ROWS 4
#define N_COLS 5

typedef int bool;

int supply[N_ROWS] = { 50, 60, 50, 50 };
int demand[N_COLS] = { 30, 20, 70, 30, 60 };

int costs[N_ROWS][N_COLS] = {
    { 16, 16, 13, 22, 17 },
    { 14, 14, 13, 19, 15 },
    { 19, 19, 20, 23, 50 },
    { 50, 12, 50, 15, 11 }
};

bool row_done[N_ROWS] = { FALSE };
bool col_done[N_COLS] = { FALSE };

void diff(int j, int len, bool is_row, int res[3]) {
    int i, c, min1 = INT_MAX, min2 = min1, min_p = -1;
    for (i = 0; i < len; ++i) {
        if((is_row) ? col_done[i] : row_done[i]) continue;
        c = (is_row) ? costs[j][i] : costs[i][j];
        if (c < min1) {
            min2 = min1;
            min1 = c;
            min_p = i;
        }
        else if (c < min2) min2 = c;
    }
    res[0] = min2 - min1; res[1] = min1; res[2] = min_p;
}

void max_penalty(int len1, int len2, bool is_row, int res[4]) {
    int i, pc = -1, pm = -1, mc = -1, md = INT_MIN;
    int res2[3];

    for (i = 0; i < len1; ++i) {
        if((is_row) ? row_done[i] : col_done[i]) continue;
        diff(i, len2, is_row, res2);
        if (res2[0] > md) {
            md = res2[0];  /* max diff */
            pm = i;        /* pos of max diff */
            mc = res2[1];  /* min cost */
            pc = res2[2];  /* pos of min cost */
        }
    }

    if (is_row) {
        res[0] = pm; res[1] = pc;
    }
    else {
        res[0] = pc; res[1] = pm;
    }
    res[2] = mc; res[3] = md;
}

void next_cell(int res[4]) {
    int i, res1[4], res2[4];
    max_penalty(N_ROWS, N_COLS, TRUE, res1);
    max_penalty(N_COLS, N_ROWS, FALSE, res2);

    if (res1[3] == res2[3]) {
        if (res1[2] < res2[2])
            for (i = 0; i < 4; ++i) res[i] = res1[i];
        else
            for (i = 0; i < 4; ++i) res[i] = res2[i];
        return;
    }
    if (res1[3] > res2[3])
        for (i = 0; i < 4; ++i) res[i] = res2[i];
    else
        for (i = 0; i < 4; ++i) res[i] = res1[i];
}

int main() {
    int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4];
    int results[N_ROWS][N_COLS] = { 0 };

    for (i = 0; i < N_ROWS; ++i) supply_left += supply[i];
    while (supply_left > 0) {
        next_cell(cell);
        r = cell[0];
        c = cell[1];
        q = (demand[c] <= supply[r]) ? demand[c] : supply[r];
        demand[c] -= q;
        if (!demand[c]) col_done[c] = TRUE;
        supply[r] -= q;
        if (!supply[r]) row_done[r] = TRUE;
        results[r][c] = q;
        supply_left -= q;
        total_cost += q * costs[r][c];
    }

    printf("    A   B   C   D   E\n");
    for (i = 0; i < N_ROWS; ++i) {
        printf("%c", 'W' + i);
        for (j = 0; j < N_COLS; ++j) printf("  %2d", results[i][j]);
        printf("\n");
    }
    printf("\nTotal cost = %d\n", total_cost);
    return 0;
}


--------------- WATER COLLECTED BETWEEN TOWERS -------------

-- waterCollected :: [Int] -> Int
on waterCollected(xs)
    set leftWalls to scanl1(my max, xs)
    set rightWalls to scanr1(my max, xs)

    set waterLevels to zipWith(my min, leftWalls, rightWalls)

    -- positive :: Num a => a -> Bool
    script positive
        on |λ|(x)
            x > 0
        end |λ|
    end script

    -- minus :: Num a => a -> a -> a
    script minus
        on |λ|(a, b)
            a - b
        end |λ|
    end script

    sum(filter(positive, zipWith(minus, waterLevels, xs)))
end waterCollected

---------------------------- TEST --------------------------
on run
    map(waterCollected, ¬
        [[1, 5, 3, 7, 2], ¬
            [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], ¬
            [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], ¬
            [5, 5, 5, 5], ¬
            [5, 6, 7, 8], ¬
            [8, 7, 7, 6], ¬
            [6, 7, 10, 7, 6]])

    --> {2, 14, 35, 0, 0, 0, 0}
end run

--------------------- GENERIC FUNCTIONS --------------------

-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
    tell mReturn(f)
        set lst to {}
        set lng to length of xs
        repeat with i from 1 to lng
            set v to item i of xs
            if |λ|(v, i, xs) then set end of lst to v
        end repeat
        return lst
    end tell
end filter

-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from 1 to lng
            set v to |λ|(v, item i of xs, i, xs)
        end repeat
        return v
    end tell
end foldl

-- init :: [a] -> [a]
on init(xs)
    if length of xs > 1 then
        items 1 thru -2 of xs
    else
        {}
    end if
end init

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- max :: Ord a => a -> a -> a
on max(x, y)
    if x > y then
        x
    else
        y
    end if
end max

-- min :: Ord a => a -> a -> a
on min(x, y)
    if y < x then
        y
    else
        x
    end if
end min

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn

-- scanl :: (b -> a -> b) -> b -> [a] -> [b]
on scanl(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        set lst to {startValue}
        repeat with i from 1 to lng
            set v to |λ|(v, item i of xs, i, xs)
            set end of lst to v
        end repeat
        return lst
    end tell
end scanl

-- scanl1 :: (a -> a -> a) -> [a] -> [a]
on scanl1(f, xs)
    if length of xs > 0 then
        scanl(f, item 1 of xs, items 2 thru -1 of xs)
    else
        {}
    end if
end scanl1

-- scanr :: (b -> a -> b) -> b -> [a] -> [b]
on scanr(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        set lst to {startValue}
        repeat with i from lng to 1 by -1
            set v to |λ|(v, item i of xs, i, xs)
            set end of lst to v
        end repeat
        return reverse of lst
    end tell
end scanr

-- scanr1 :: (a -> a -> a) -> [a] -> [a]
on scanr1(f, xs)
    if length of xs > 0 then
        scanr(f, item -1 of xs, items 1 thru -2 of xs)
    else
        {}
    end if
end scanr1

-- sum :: Num a => [a] -> a
on sum(xs)
    script add
        on |λ|(a, b)
            a + b
        end |λ|
    end script

    foldl(add, 0, xs)
end sum

-- tail :: [a] -> [a]
on tail(xs)
    if length of xs > 1 then
        items 2 thru -1 of xs
    else
        {}
    end if
end tail

-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
    set lng to min(length of xs, length of ys)
    set lst to {}
    tell mReturn(f)
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, item i of ys)
        end repeat
        return lst
    end tell
end zipWith


:- 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, V),
	voronoi(minkowski_3, V).

voronoi(Distance, V) :-
	sformat(A, 'Voronoi 400X400 ~w ~w', [V, Distance]),
	new(D, window(A)),
	send(D, size, size(400,400)),
	new(Img, image(@nil, width := 400, height := 400 , kind := pixmap)),

        % get the list of the sites
	bagof((N, X, Y), R^G^B^pt(N, X, Y, R, G, B), L),

	forall(between(0,399, I),
	       forall(between(0,399, J),
		   (  get_nearest_site(V, Distance, I, J, L, S),
		      pt(S, _, _, R, G, B),
		      send(Img, pixel(I, J, colour(@default, R, G, B)))))),

	new(Bmp, bitmap(Img)),
	send(D, display, Bmp, point(0,0)),
	send(D, open).

% define predicatea foldl (functionnal spirit)
foldl([], _Pred, R, R).

foldl([H | T], Pred, Acc, R) :-
	call(Pred, H, Acc, R1),
	foldl(T, Pred, R1, R).

% predicate for foldl
compare(Distance, XP, YP, (N, X, Y), (D, S), R) :-
	call(Distance, XP, YP, X, Y, DT),
	(   DT < D -> R = (DT, N) ; R = (D, S)).

% use of a fake site for the init of foldl
get_nearest_site(Distance, I, J, L, S) :-
	foldl(L, compare(Distance, I, J),  (65535, nil), (_, S)).

manhattan(X1, Y1, X2, Y2, D) :-
	D is abs(X2 - X1) + abs(Y2-Y1).

euclide(X1, Y1, X2, Y2, D) :-
	D is sqrt((X2 - X1)**2 + (Y2-Y1)**2).

minkowski_3(X1, Y1, X2, Y2, D) :-
	D is (abs(X2 - X1)**3 + abs(Y2-Y1)**3)**0.33.


fn walkDir dir pattern =
(
    dirArr = GetDirectories (dir + "\\*")

    for d in dirArr do
    (
        join dirArr (getDirectories (d + "\\*"))
    )

    append dirArr (dir + "\\") -- Need to include the original top level directory

    for f in dirArr do
    (
        print (getFiles (f + pattern))
    )
)

walkDir "C:" "*.txt"


lfs = require "lfs"

-- This function takes two arguments:
-- - the directory to walk recursively;
-- - an optional function that takes a file name as argument, and returns a boolean.
find = (fn) => coroutine.wrap ->
  for f in lfs.dir @
    if f ~= "." and f ~= ".."
      _f = @.."/"..f
      coroutine.yield _f if not fn or fn _f
      if lfs.attributes(_f, "mode") == "directory"
        coroutine.yield n for n in find _f, fn

-- Examples
-- List all files
print f for f in find "templates"

-- List moonscript files
print f for f in find "templates", => @\match "%.moon$"

-- List directories
print f for f in find "templates", => "directory" == lfs.attributes @, "mode"


import Nanoquery.IO

def get_files(dirname)
	local_filenames = new(File).listDir(dirname)

	filenames = {}

	for i in range(0, len(local_filenames) - 1)
		if len(local_filenames) > 0
			if not new(File, local_filenames[i]).isDir()
				filenames.append(local_filenames[i])
			else
				filenames += get_files(local_filenames[i])
			end
		end
	end

	return filenames
end

f = new(File)
for file in get_files("/")
	if lower(f.getExtension(file)) = ".mp3"
		println file
	end
end


import os, re

for file in walkDirRec "/":
  if file.match re".*\.mp3":
    echo file


use System.IO.File;

class Test {
  function : Main(args : String[]) ~ Nil {
    if(args->Size() = 2) {
      DescendDir(args[0], args[1]);
    };
  }

  function : DescendDir(path : String, pattern : String) ~ Nil {
    files := Directory->List(path);
    each(i : files) {
      file := files[i];
      if(<>file->StartsWith('.')) {
        dir_path := String->New(path);
        dir_path += '/';
        dir_path += file;

        if(Directory->Exists(dir_path)) {
          DescendDir(dir_path, pattern);
        }
        else if(File->Exists(dir_path) & dir_path->EndsWith(pattern)) {
          dir_path->PrintLine();
        };
      };
    };
  }
}


T Node
   String value
   Node? left
   Node? right

   F (value, Node? left = N, Node? right = N)
      .value = String(value)
      .left = left
      .right = right

   F tree_indent() -> [String]
      V tr = I .right != N {.right.tree_indent()} E [‘-- (null)’]
      R [‘--’(.value)] [+] (I .left != N {.left.tree_indent()} E [‘-- (null)’]).map(a -> ‘  |’a)
                       [+] [‘  `’tr[0]] + tr[1..].map(a -> ‘   ’a)

V tree = Node(1, Node(2, Node(4, Node(7)), Node(5)), Node(3, Node(6, Node(8), Node(9))))
print(tree.tree_indent().join("\n"))


#include <iostream>
#include <numeric>
#include <vector>

template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
    auto it = v.cbegin();
    auto end = v.cend();

    os << '[';
    if (it != end) {
        os << *it;
        it = std::next(it);
    }
    while (it != end) {
        os << ", " << *it;
        it = std::next(it);
    }

    return os << ']';
}

std::vector<int> demand = { 30, 20, 70, 30, 60 };
std::vector<int> supply = { 50, 60, 50, 50 };
std::vector<std::vector<int>> costs = {
    {16, 16, 13, 22, 17},
    {14, 14, 13, 19, 15},
    {19, 19, 20, 23, 50},
    {50, 12, 50, 15, 11}
};

int nRows = supply.size();
int nCols = demand.size();

std::vector<bool> rowDone(nRows, false);
std::vector<bool> colDone(nCols, false);
std::vector<std::vector<int>> result(nRows, std::vector<int>(nCols, 0));

std::vector<int> diff(int j, int len, bool isRow) {
    int min1 = INT_MAX;
    int min2 = INT_MAX;
    int minP = -1;
    for (int i = 0; i < len; i++) {
        if (isRow ? colDone[i] : rowDone[i]) {
            continue;
        }
        int c = isRow
            ? costs[j][i]
            : costs[i][j];
        if (c < min1) {
            min2 = min1;
            min1 = c;
            minP = i;
        } else if (c < min2) {
            min2 = c;
        }
    }
    return { min2 - min1, min1, minP };
}

std::vector<int> maxPenalty(int len1, int len2, bool isRow) {
    int md = INT_MIN;
    int pc = -1;
    int pm = -1;
    int mc = -1;
    for (int i = 0; i < len1; i++) {
        if (isRow ? rowDone[i] : colDone[i]) {
            continue;
        }
        std::vector<int> res = diff(i, len2, isRow);
        if (res[0] > md) {
            md = res[0];    // max diff
            pm = i;         // pos of max diff
            mc = res[1];    // min cost
            pc = res[2];    // pos of min cost
        }
    }
    return isRow
        ? std::vector<int> { pm, pc, mc, md }
    : std::vector<int>{ pc, pm, mc, md };
}

std::vector<int> nextCell() {
    auto res1 = maxPenalty(nRows, nCols, true);
    auto res2 = maxPenalty(nCols, nRows, false);

    if (res1[3] == res2[3]) {
        return res1[2] < res2[2]
            ? res1
            : res2;
    }
    return res1[3] > res2[3]
        ? res2
        : res1;
}

int main() {
    int supplyLeft = std::accumulate(supply.cbegin(), supply.cend(), 0, [](int a, int b) { return a + b; });
    int totalCost = 0;

    while (supplyLeft > 0) {
        auto cell = nextCell();
        int r = cell[0];
        int c = cell[1];

        int quantity = std::min(demand[c], supply[r]);

        demand[c] -= quantity;
        if (demand[c] == 0) {
            colDone[c] = true;
        }

        supply[r] -= quantity;
        if (supply[r] == 0) {
            rowDone[r] = true;
        }

        result[r][c] = quantity;
        supplyLeft -= quantity;

        totalCost += quantity * costs[r][c];
    }

    for (auto &a : result) {
        std::cout << a << '\n';
    }

    std::cout << "Total cost: " << totalCost;

    return 0;
}


WCBT(oTwr){
	topL := Max(oTwr*), l := num := 0, barCh := lbarCh := "", oLvl := []
	while (++l <= topL)
		for t, h in oTwr
			oLvl[l,t] := h ? "██" : "≈≈" , oTwr[t] := oTwr[t]>0 ? oTwr[t]-1 : 0
	for l, obj in oLvl{
		while (oLvl[l, A_Index] = "≈≈")
			oLvl[l, A_Index] := "  "
		while (oLvl[l, obj.Count() +1 - A_Index] = "≈≈")
			oLvl[l, obj.Count() +1 - A_Index] := "  "
		for t, v in obj
			lbarCh .= StrReplace(v, "≈≈", "≈≈", n), num += n
		barCh := lbarCh "`n" barCh, lbarCh := ""
	}
	return [num, barCh]
}


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
    a(i)\x = RandInt(xMax): a(i)\y = RandInt(yMax)
    j = RandInt(255): k = RandInt(255): l = RandInt(255)
    a(i)\Colour = RGBA(j, k, l, 255)
    a(i)\FillColour = RGBA(255-j, 255-k, 255-l, 255)
  Next i
  ProcedureReturn #True
EndProcedure

Procedure MakeVoronoiDiagram(Array a.VCoo(1),xMax, yMax) ; Euclidean
  Protected i, x, y, img, dist.d, dt.d
  img = CreateImage(#PB_Any, xMax+1, yMax+1)
  If StartDrawing(ImageOutput(img))
    For y=0 To yMax
      For x=0 To xMax
        dist = Infinity()
        For i=0 To ArraySize(a())
          dt = SQ2(x-a(i)\x, y-a(i)\y)
          If dt > dist
            Continue
          ElseIf dt < dist
            dist = dt
            Plot(x,y,a(i)\FillColour)
          Else ; 'Owner ship' is unclear, set pixel to transparent.
            Plot(x,y,RGBA(0, 0, 0, 0))
          EndIf
        Next
      Next
    Next
    For i=0 To ArraySize(a())
      Circle(a(i)\x, a(i)\y, 1, a(i)\Colour)
    Next
    StopDrawing()
  EndIf
  ProcedureReturn img
EndProcedure

; Main code
Define img, x, y, file$
Dim V.VCoo(0)
x = 640: y = 480
If Not GenRandomPoints(V(), x, y, 150): End: EndIf
img = MakeVoronoiDiagram(V(), x, y)
If img And OpenWindow(0, 0, 0, x, y, "Voronoi Diagram in PureBasic", #PB_Window_SystemMenu)
  ImageGadget(0, 0, 0, x, y, ImageID(img))
  Repeat: Until WaitWindowEvent() = #PB_Event_CloseWindow
EndIf

UsePNGImageEncoder()
file$ = SaveFileRequester("Save Image?", "Voronoi_Diagram_in_PureBasic.png", "PNG|*.png", 0)
If file$ <> ""
  SaveImage(img, file$, #PB_ImagePlugin_PNG)
EndIf


NSString *dir = NSHomeDirectory();
NSDirectoryEnumerator *de = [[NSFileManager defaultManager] enumeratorAtPath:dir];

for (NSString *file in de)
  if ([[file pathExtension] isEqualToString:@"mp3"])
    NSLog(@"%@", file);


#!/usr/bin/env ocaml
#load "unix.cma"
#load "str.cma"
open Unix

let walk_directory_tree dir pattern =
  let re = Str.regexp pattern in (* pre-compile the regexp *)
  let select str = Str.string_match re str 0 in
  let rec walk acc = function
  | [] -> (acc)
  | dir::tail ->
      let contents = Array.to_list (Sys.readdir dir) in
      let contents = List.rev_map (Filename.concat dir) contents in
      let dirs, files =
        List.fold_left (fun (dirs,files) f ->
             match (stat f).st_kind with
             | S_REG -> (dirs, f::files)  (* Regular file *)
             | S_DIR -> (f::dirs, files)  (* Directory *)
             | _ -> (dirs, files)
          ) ([],[]) contents
      in
      let matched = List.filter (select) files in
      walk (matched @ acc) (dirs @ tail)
  in
  walk [] [dir]
;;

let () =
  let results = walk_directory_tree "/usr/local/lib/ocaml"  ".*\\.cma" in
  List.iter print_endline results;
;;


with Ada.Text_IO, Ada.Directories;

procedure Directory_Tree is

   procedure Print_Tree(Current: String; Indention: Natural := 0) is

      function Spaces(N: Natural) return String is
	 (if N= 0 then "" else " " & Spaces(N-1));

      use Ada.Directories;
      Search: Search_Type;
      Found: Directory_Entry_Type;

   begin
      Start_Search(Search, Current, "");
      while More_Entries(Search) loop
	 Get_Next_Entry(Search, Found);
	 declare
	    Name: String := Simple_Name(Found);
	    Dir: Boolean := Kind(Found) = Directory;
	 begin
	    if Name(Name'First) /= '.' then
               -- skip all files who's names start with ".", namely "." and ".."
	       Ada.Text_IO.Put_Line(Spaces(2*Indention) & Simple_Name(Found)
		  & (if Dir then " (dir)" else ""));
	       if Dir then
		  Print_Tree(Full_Name(Found), Indention + 1);
	       end if;
	    end if;
	 end;
     end loop;
   end Print_Tree;

begin
   Print_Tree(Ada.Directories.Current_Directory);
end Directory_Tree;


# 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 = "
"
     , elbat = "
"
     , tr    = "
"
     , rt    = "
"
     , td    = "<td style=""text-align: center; vertical-align: top; """
     , dt    = "	"
     , nbsp  = " "
     ;
CHAR   nl    = REPR 10;

# returns the number of child elements of tree #
OP CHILDCOUNT = ( REF NODE tree )INT:
    BEGIN
        INT      result := 0;
        REF NODE child  := child OF tree;
        WHILE REF NODE( child ) ISNT nil node
        DO
            result +:= 1;
            child   := sibling OF child
        OD;
        result
    END # CHILDCOUNT # ;

# generates nested HTML tables from the tree #
OP  TOHTML = ( REF NODE tree )STRING:
    IF tree IS nil node
    THEN
        # no node #
        ""
    ELSE
        # hae at least one node #
        STRING result     := "";
        INT    child count = CHILDCOUNT tree;
        result +:= table + nl
                 +   tr  + nl
                 +     td + " colspan="""
                          + whole( IF child count < 1 THEN 1 ELSE child count FI, 0 )
                          + """>" + nbsp + value OF tree + nbsp
                 +     dt + nl
                 +   rt  + nl
                 ;
        IF child count > 0
        THEN
            # the node has branches #
            REF NODE  child  := child OF tree;
            INT child number := 1;
            INT mid child     = ( child count + 1 ) OVER 2;
            child   := child OF tree;
            result +:= tr + nl;
            WHILE child ISNT nil node
            DO
                result +:= td + ">" + nl
                         + IF CHILDCOUNT child < 1 THEN nbsp + value OF child + nbsp ELSE TOHTML child FI
                         + dt + nl;
                child := sibling OF child
            OD;
            result +:= rt + nl
        FI;
        result +:= elbat + nl
    FI # TOHTML # ;

# test the tree visualisation #

# returns a new node with the specified value and no child or siblings #
PROC new node = ( STRING value )REF NODE: HEAP NODE := NODE( value, nil node, nil node );
# appends a sibling node to the node n, returns the sibling #
OP +:= = ( REF NODE n, REF NODE sibling node )REF NODE:
    BEGIN
        REF NODE sibling := n;
        WHILE REF NODE( sibling OF sibling ) ISNT nil node
        DO
            sibling := sibling OF sibling
        OD;
        sibling OF sibling := sibling node
    END # +:= # ;
# appends a new sibling node to the node n, returns the sibling #
OP +:= = ( REF NODE n, STRING   sibling value )REF NODE: n +:= new node( sibling value );
# adds a child node to the node n, returns the child #
OP /:= = ( REF NODE n, REF NODE child node    )REF NODE: child OF n := child node;
# adda a new child node to the node n, returns the child #
OP /:= = ( REF NODE n, STRING   child value   )REF NODE: n /:= new node( child value );

NODE animals  := new node( "animals"  );
NODE fish     := new node( "fish"     );
NODE reptiles := new node( "reptiles" );
NODE mammals  := new node( "mammals"  );
NODE primates := new node( "primates" );
NODE sharks   := new node( "sharks"   );
sharks   /:= "great-white" +:= "hammer-head";
fish     /:= "cod"         +:= sharks           +:= "piranha";
reptiles /:= "iguana"      +:= "brontosaurus";
primates /:= "gorilla"     +:= "lemur";
mammals  /:= "sloth"       +:= "horse"          +:= "bison" +:= primates;
animals  /:= fish          +:= reptiles         +:= mammals;

print( ( TOHTML animals ) )


void main() {
    import std.stdio, std.string, std.algorithm, std.range;

    enum K { A, B, C, D, E,  X, Y, Z, W }
    immutable int[K][K] costs = cast() //**
        [K.W: [K.A: 16, K.B: 16, K.C: 13, K.D: 22, K.E: 17],
         K.X: [K.A: 14, K.B: 14, K.C: 13, K.D: 19, K.E: 15],
         K.Y: [K.A: 19, K.B: 19, K.C: 20, K.D: 23, K.E: 50],
         K.Z: [K.A: 50, K.B: 12, K.C: 50, K.D: 15, K.E: 11]];
    int[K] demand, supply;
    with (K)
        demand = [A: 30, B: 20, C: 70, D: 30, E: 60],
        supply = [W: 50, X: 60, Y: 50, Z: 50];

    auto cols = demand.keys.sort().release;
    auto res = costs.byKey.zip((int[K]).init.repeat).assocArray;
    K[][K] g;
    foreach (immutable x; supply.byKey)
        g[x] = costs[x].keys.schwartzSort!(k => cast()costs[x][k]) //**
               .release;
    foreach (immutable x; demand.byKey)
        g[x] = costs.keys.schwartzSort!(k=> cast()costs[k][x]).release;

    while (g.length) {
        int[K] d, s;
        foreach (immutable x; demand.byKey)
            d[x] = g[x].length > 1 ?
                   costs[g[x][1]][x] - costs[g[x][0]][x] :
                   costs[g[x][0]][x];
        foreach (immutable x; supply.byKey)
            s[x] = g[x].length > 1 ?
                   costs[x][g[x][1]] - costs[x][g[x][0]] :
                   costs[x][g[x][0]];
        auto f = d.keys.minPos!((a,b) => d[a] > d[b])[0];
        auto t = s.keys.minPos!((a,b) => s[a] > s[b])[0];
        if (d[f] > s[t]) {
            t = f;
            f = g[f][0];
        } else {
            f = t;
            t = g[t][0];
        }
        immutable v = min(supply[f], demand[t]);
        res[f][t] += v;
        demand[t] -= v;
        if (demand[t] == 0) {
            foreach (immutable k, immutable n; supply)
                if (n != 0)
                    g[k] = g[k].remove!(c => c == t);
            g.remove(t);
            demand.remove(t);
        }
        supply[f] -= v;
        if (supply[f] == 0) {
            foreach (immutable k, immutable n; demand)
                if (n != 0)
                    g[k] = g[k].remove!(c => c == f);
            g.remove(f);
            supply.remove(f);
        }
    }

    writefln("%-(\t%s%)", cols);
    auto cost = 0;
    foreach (immutable c; costs.keys.sort().release) {
        write(c, '\t');
        foreach (immutable n; cols) {
            if (n in res[c]) {
                immutable y = res[c][n];
                if (y != 0) {
                    y.write;
                    cost += y * costs[c][n];
                }
            }
            '\t'.write;
        }
        writeln;
    }
    writeln("\nTotal Cost = ", cost);
}


# syntax: GAWK -f WATER_COLLECTED_BETWEEN_TOWERS.AWK [-v debug={0|1}]
BEGIN {
    wcbt("1,5,3,7,2")
    wcbt("5,3,7,2,6,4,5,9,1,2")
    wcbt("2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1")
    wcbt("5,5,5,5")
    wcbt("5,6,7,8")
    wcbt("8,7,7,6")
    wcbt("6,7,10,7,6")
    exit(0)
}
function wcbt(str,  ans,hl,hr,i,n,tower) {
    n = split(str,tower,",")
    for (i=n; i>=0; i--) { # scan right to left
      hr[i] = max(tower[i],(i<n)?hr[i+1]:0)
    }
    for (i=0; i<=n; i++) { # scan left to right
      hl[i] = max(tower[i],(i!=0)?hl[i-1]:0)
      ans += min(hl[i],hr[i]) - tower[i]
    }
    printf("%4d : %s\n",ans,str)
    if (debug == 1) {
      for (i=1; i<=n; i++) { printf("%-4s",tower[i]) } ; print("tower")
      for (i=1; i<=n; i++) { printf("%-4s",hl[i]) } ; print("l-r")
      for (i=1; i<=n; i++) { printf("%-4s",hr[i]) } ; print("r-l")
      for (i=1; i<=n; i++) { printf("%-4s",min(hl[i],hr[i])) } ; print("min")
      for (i=1; i<=n; i++) { printf("%-4s",min(hl[i],hr[i])-tower[i]) } ; print("sum\n")
    }
}
function max(x,y) { return((x > y) ? x : y) }
function min(x,y) { return((x < y) ? x : y) }


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.append(random.randrange(imgy))
		nr.append(random.randrange(256))
		ng.append(random.randrange(256))
		nb.append(random.randrange(256))
	for y in range(imgy):
		for x in range(imgx):
			dmin = math.hypot(imgx-1, imgy-1)
			j = -1
			for i in range(num_cells):
				d = math.hypot(nx[i]-x, ny[i]-y)
				if d < dmin:
					dmin = d
					j = i
			putpixel((x, y), (nr[j], ng[j], nb[j]))
	image.save("VoronoiDiagram.png", "PNG")
        image.show()

generate_voronoi_diagram(500, 500, 25)


declare
  [Path] = {Module.link ['x-oz://system/os/Path.ozf']}
  [Regex] = {Module.link ['x-oz://contrib/regex']}

  proc {WalkDirTree Root Pattern Proc}
     proc {Walk R}
        Entries = {Path.readdir R}
        Files = {Filter Entries Path.isFile}
        MatchingFiles = {Filter Files fun {$ File} {Regex.search Pattern File} \= false end}
        Subdirs = {Filter Entries Path.isDir}
     in
        {ForAll MatchingFiles Proc}
        {ForAll Subdirs Walk}
     end
  in
     {Walk Root}
  end
in
  {WalkDirTree "." ".*\\.oz$" System.showInfo}


use File::Find qw(find);
my $dir      = '.';
my $pattern  = 'foo';
my $callback = sub { print $File::Find::name, "\n" if /$pattern/ };
find $callback, $dir;