-- Vertically centered textual tree using UTF8 monospaced
-- box-drawing characters, with options for compacting
-- and pruning.

--               ┌── Gamma
--       ┌─ Beta ┼── Delta
--       │       └ Epsilon
-- Alpha ┼─ Zeta ───── Eta
--       │       ┌─── Iota
--       └ Theta ┼── Kappa
--               └─ Lambda

-- TESTS --------------------------------------------------
on run
    set tree to Node(1, ¬
        {Node(2, ¬
            {Node(4, {Node(7, {})}), ¬
                Node(5, {})}), ¬
            Node(3, ¬
                {Node(6, ¬
                    {Node(8, {}), Node(9, {})})})})

    set tree2 to Node("Alpha", ¬
        {Node("Beta", ¬
            {Node("Gamma", {}), ¬
                Node("Delta", {}), ¬
                Node("Epsilon", {})}), ¬
            Node("Zeta", {Node("Eta", {})}), ¬
            Node("Theta", ¬
                {Node("Iota", {}), Node("Kappa", {}), ¬
                    Node("Lambda", {})})})

    set strTrees to unlines({"(NB – view in mono-spaced font)\n\n", ¬
        "Compacted (not all parents vertically centered):\n", ¬
        drawTree2(true, false, tree), ¬
        "\nFully expanded and vertically centered:\n", ¬
        drawTree2(false, false, tree2), ¬
        "\nVertically centered, with nodeless lines pruned out:\n", ¬
        drawTree2(false, true, tree2)})
    set the clipboard to strTrees
    strTrees
end run

-- drawTree2 :: Bool -> Bool -> Tree String -> String
on drawTree2(blnCompressed, blnPruned, tree)
    -- Tree design and algorithm inspired by the Haskell snippet at:
    -- https://doisinkidney.com/snippets/drawing-trees.html
    script measured
        on |λ|(t)
            script go
                on |λ|(x)
                    set s to " " & x & " "
                    Tuple(length of s, s)
                end |λ|
            end script
            fmapTree(go, t)
        end |λ|
    end script
    set measuredTree to |λ|(tree) of measured

    script levelMax
        on |λ|(a, level)
            a & maximum(map(my fst, level))
        end |λ|
    end script
    set levelWidths to foldl(levelMax, {}, ¬
        init(levels(measuredTree)))

    -- Lefts, Mid, Rights
    script lmrFromStrings
        on |λ|(xs)
            set {ls, rs} to items 2 thru -2 of ¬
                (splitAt((length of xs) div 2, xs) as list)
            Tuple3(ls, item 1 of rs, rest of rs)
        end |λ|
    end script

    script stringsFromLMR
        on |λ|(lmr)
            script add
                on |λ|(a, x)
                    a & x
                end |λ|
            end script
            foldl(add, {}, items 2 thru -2 of (lmr as list))
        end |λ|
    end script

    script fghOverLMR
        on |λ|(f, g, h)
            script
                property mg : mReturn(g)
                on |λ|(lmr)
                    set {ls, m, rs} to items 2 thru -2 of (lmr as list)
                    Tuple3(map(f, ls), |λ|(m) of mg, map(h, rs))
                end |λ|
            end script
        end |λ|
    end script

    script lmrBuild
        on leftPad(n)
            script
                on |λ|(s)
                    replicateString(n, space) & s
                end |λ|
            end script
        end leftPad

        -- lmrBuild main
        on |λ|(w, f)
            script
                property mf : mReturn(f)
                on |λ|(wsTree)
                    set xs to nest of wsTree
                    set lng to length of xs
                    set {nChars, x} to items 2 thru -2 of ¬
                        ((root of wsTree) as list)
                    set _x to replicateString(w - nChars, "─") & x

                    -- LEAF NODE ------------------------------------
                    if 0 = lng then
                        Tuple3({}, _x, {})

                    else if 1 = lng then
                        -- NODE WITH SINGLE CHILD ---------------------
                        set indented to leftPad(1 + w)
                        script lineLinked
                            on |λ|(z)
                                _x & "─" & z
                            end |λ|
                        end script
                        |λ|(|λ|(item 1 of xs) of mf) of ¬
                            (|λ|(indented, lineLinked, indented) of ¬
                                fghOverLMR)
                    else
                        -- NODE WITH CHILDREN -------------------------
                        script treeFix
                            on cFix(x)
                                script
                                    on |λ|(xs)
                                        x & xs
                                    end |λ|
                                end script
                            end cFix

                            on |λ|(l, m, r)
                                compose(stringsFromLMR, ¬
                                    |λ|(cFix(l), cFix(m), cFix(r)) of ¬
                                    fghOverLMR)
                            end |λ|
                        end script

                        script linked
                            on |λ|(s)
                                set c to text 1 of s
                                set t to tail(s)
                                if "┌" = c then
                                    _x & "┬" & t
                                else if "│" = c then
                                    _x & "┤" & t
                                else if "├" = c then
                                    _x & "┼" & t
                                else
                                    _x & "┴" & t
                                end if
                            end |λ|
                        end script

                        set indented to leftPad(w)
                        set lmrs to map(f, xs)
                        if blnCompressed then
                            set sep to {}
                        else
                            set sep to {"│"}
                        end if

                        tell lmrFromStrings
                            set tupleLMR to |λ|(intercalate(sep, ¬
                                {|λ|(item 1 of lmrs) of ¬
                                    (|λ|(" ", "┌", "│") of treeFix)} & ¬
                                map(|λ|("│", "├", "│") of treeFix, ¬
                                    init(tail(lmrs))) & ¬
                                {|λ|(item -1 of lmrs) of ¬
                                    (|λ|("│", "└", " ") of treeFix)}))
                        end tell

                        |λ|(tupleLMR) of ¬
                            (|λ|(indented, linked, indented) of fghOverLMR)
                    end if
                end |λ|
            end script
        end |λ|
    end script

    set treeLines to |λ|(|λ|(measuredTree) of ¬
        foldr(lmrBuild, 0, levelWidths)) of stringsFromLMR
    if blnPruned then
        script notEmpty
            on |λ|(s)
                script isData
                    on |λ|(c)
                        "│ " does not contain c
                    end |λ|
                end script
                any(isData, characters of s)
            end |λ|
        end script
        set xs to filter(notEmpty, treeLines)
    else
        set xs to treeLines
    end if
    unlines(xs)
end drawTree2

-- GENERIC ------------------------------------------------

-- Node :: a -> [Tree a] -> Tree a
on Node(v, xs)
    {type:"Node", root:v, nest:xs}
end Node

-- Tuple (,) :: a -> b -> (a, b)
on Tuple(a, b)
    -- Constructor for a pair of values, possibly of two different types.
    {type:"Tuple", |1|:a, |2|:b, length:2}
end Tuple

-- Tuple3 (,,) :: a -> b -> c -> (a, b, c)
on Tuple3(x, y, z)
    {type:"Tuple3", |1|:x, |2|:y, |3|:z, length:3}
end Tuple3

-- Applied to a predicate and a list,
-- |any| returns true if at least one element of the
-- list satisfies the predicate.
-- any :: (a -> Bool) -> [a] -> Bool
on any(f, xs)
    tell mReturn(f)
        set lng to length of xs
        repeat with i from 1 to lng
            if |λ|(item i of xs) then return true
        end repeat
        false
    end tell
end any

-- compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
on compose(f, g)
    script
        property mf : mReturn(f)
        property mg : mReturn(g)
        on |λ|(x)
            |λ|(|λ|(x) of mg) of mf
        end |λ|
    end script
end compose

-- concat :: [[a]] -> [a]
-- concat :: [String] -> String
on concat(xs)
    set lng to length of xs
    if 0 < lng and string is class of (item 1 of xs) then
        set acc to ""
    else
        set acc to {}
    end if
    repeat with i from 1 to lng
        set acc to acc & item i of xs
    end repeat
    acc
end concat

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

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

-- fmapTree :: (a -> b) -> Tree a -> Tree b
on fmapTree(f, tree)
    script go
        property g : |λ| of mReturn(f)
        on |λ|(x)
            set xs to nest of x
            if xs ≠ {} then
                set ys to map(go, xs)
            else
                set ys to xs
            end if
            Node(g(root of x), ys)
        end |λ|
    end script
    |λ|(tree) of go
end fmapTree

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

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

-- fst :: (a, b) -> a
on fst(tpl)
    if class of tpl is record then
        |1| of tpl
    else
        item 1 of tpl
    end if
end fst

-- identity :: a -> a
on identity(x)
    -- The argument unchanged.
    x
end identity

-- init :: [a] -> [a]
-- init :: [String] -> [String]
on init(xs)
    set blnString to class of xs = string
    set lng to length of xs

    if lng > 1 then
        if blnString then
            text 1 thru -2 of xs
        else
            items 1 thru -2 of xs
        end if
    else if lng > 0 then
        if blnString then
            ""
        else
            {}
        end if
    else
        missing value
    end if
end init

-- intercalate :: [a] -> [[a]] -> [a]
-- intercalate :: String -> [String] -> String
on intercalate(sep, xs)
    concat(intersperse(sep, xs))
end intercalate

-- intersperse(0, [1,2,3]) -> [1, 0, 2, 0, 3]
-- intersperse :: a -> [a] -> [a]
-- intersperse :: Char -> String -> String
on intersperse(sep, xs)
    set lng to length of xs
    if lng > 1 then
        set acc to {item 1 of xs}
        repeat with i from 2 to lng
            set acc to acc & {sep, item i of xs}
        end repeat
        if class of xs is string then
            concat(acc)
        else
            acc
        end if
    else
        xs
    end if
end intersperse

-- isNull :: [a] -> Bool
-- isNull :: String -> Bool
on isNull(xs)
    if class of xs is string then
        "" = xs
    else
        {} = xs
    end if
end isNull

-- iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]
on iterateUntil(p, f, x)
    script
        property mp : mReturn(p)'s |λ|
        property mf : mReturn(f)'s |λ|
        property lst : {x}
        on |λ|(v)
            repeat until mp(v)
                set v to mf(v)
                set end of lst to v
            end repeat
            return lst
        end |λ|
    end script
    |λ|(x) of result
end iterateUntil

-- levels :: Tree a -> [[a]]
on levels(tree)
    script nextLayer
        on |λ|(xs)
            script
                on |λ|(x)
                    nest of x
                end |λ|
            end script
            concatMap(result, xs)
        end |λ|
    end script

    script roots
        on |λ|(xs)
            script
                on |λ|(x)
                    root of x
                end |λ|
            end script
            map(result, xs)
        end |λ|
    end script

    map(roots, iterateUntil(my isNull, nextLayer, {tree}))
end levels

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

-- maximum :: Ord a => [a] -> a
on maximum(xs)
    script
        on |λ|(a, b)
            if a is missing value or b > a then
                b
            else
                a
            end if
        end |λ|
    end script
    foldl(result, missing value, xs)
end maximum

-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
    -- 2nd class handler function lifted into 1st class script wrapper.
    if script is class of f then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn

-- replicateString :: Int -> String -> String
on replicateString(n, s)
    set out to ""
    if n < 1 then return out
    set dbl to s

    repeat while (n > 1)
        if (n mod 2) > 0 then set out to out & dbl
        set n to (n div 2)
        set dbl to (dbl & dbl)
    end repeat
    return out & dbl
end replicateString

-- snd :: (a, b) -> b
on snd(tpl)
    if class of tpl is record then
        |2| of tpl
    else
        item 2 of tpl
    end if
end snd

-- splitAt :: Int -> [a] -> ([a], [a])
on splitAt(n, xs)
    if n > 0 and n < length of xs then
        if class of xs is text then
            Tuple(items 1 thru n of xs as text, items (n + 1) thru -1 of xs as text)
        else
            Tuple(items 1 thru n of xs, items (n + 1) thru -1 of xs)
        end if
    else
        if n < 1 then
            Tuple({}, xs)
        else
            Tuple(xs, {})
        end if
    end if
end splitAt

-- tail :: [a] -> [a]
on tail(xs)
    set blnText to text is class of xs
    if blnText then
        set unit to ""
    else
        set unit to {}
    end if
    set lng to length of xs
    if 1 > lng then
        missing value
    else if 2 > lng then
        unit
    else
        if blnText then
            text 2 thru -1 of xs
        else
            rest of xs
        end if
    end if
end tail

-- unlines :: [String] -> String
on unlines(xs)
    -- A single string formed by the intercalation
    -- of a list of strings with the newline character.
    set {dlm, my text item delimiters} to ¬
        {my text item delimiters, linefeed}
    set str to xs as text
    set my text item delimiters to dlm
    str
end unlines


package main

import (
    "fmt"
    "math"
)

var supply = []int{50, 60, 50, 50}
var demand = []int{30, 20, 70, 30, 60}

var costs = make([][]int, 4)

var nRows = len(supply)
var nCols = len(demand)

var rowDone = make([]bool, nRows)
var colDone = make([]bool, nCols)
var results = make([][]int, nRows)

func init() {
    costs[0] = []int{16, 16, 13, 22, 17}
    costs[1] = []int{14, 14, 13, 19, 15}
    costs[2] = []int{19, 19, 20, 23, 50}
    costs[3] = []int{50, 12, 50, 15, 11}

    for i := 0; i < len(results); i++ {
        results[i] = make([]int, nCols)
    }
}

func nextCell() []int {
    res1 := maxPenalty(nRows, nCols, true)
    res2 := maxPenalty(nCols, nRows, false)
    switch {
    case res1[3] == res2[3]:
        if res1[2] < res2[2] {
            return res1
        } else {
            return res2
        }
    case res1[3] > res2[3]:
        return res2
    default:
        return res1
    }
}

func diff(j, l int, isRow bool) []int {
    min1 := math.MaxInt32
    min2 := min1
    minP := -1
    for i := 0; i < l; i++ {
        var done bool
        if isRow {
            done = colDone[i]
        } else {
            done = rowDone[i]
        }
        if done {
            continue
        }
        var c int
        if isRow {
            c = costs[j][i]
        } else {
            c = costs[i][j]
        }
        if c < min1 {
            min2, min1, minP = min1, c, i
        } else if c < min2 {
            min2 = c
        }
    }
    return []int{min2 - min1, min1, minP}
}

func maxPenalty(len1, len2 int, isRow bool) []int {
    md := math.MinInt32
    pc, pm, mc := -1, -1, -1
    for i := 0; i < len1; i++ {
        var done bool
        if isRow {
            done = rowDone[i]
        } else {
            done = colDone[i]
        }
        if done {
            continue
        }
        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
        }
    }
    if isRow {
        return []int{pm, pc, mc, md}
    }
    return []int{pc, pm, mc, md}
}

func main() {
    supplyLeft := 0
    for i := 0; i < len(supply); i++ {
        supplyLeft += supply[i]
    }
    totalCost := 0
    for supplyLeft > 0 {
        cell := nextCell()
        r, c := cell[0], cell[1]
        q := demand[c]
        if q > supply[r] {
            q = supply[r]
        }
        demand[c] -= q
        if demand[c] == 0 {
            colDone[c] = true
        }
        supply[r] -= q
        if supply[r] == 0 {
            rowDone[r] = true
        }
        results[r][c] = q
        supplyLeft -= q
        totalCost += q * costs[r][c]
    }

    fmt.Println("    A   B   C   D   E")
    for i, result := range results {
        fmt.Printf("%c", 'W' + i)
        for _, item := range result {
            fmt.Printf("  %2d", item)
        }
        fmt.Println()
    }
    fmt.Println("\nTotal cost =", totalCost)
}


#include<stdlib.h>
#include<stdio.h>

int getWater(int* arr,int start,int end,int cutoff){
	int i, sum = 0;

	for(i=start;i<=end;i++)
		sum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);

	return sum;
}

int netWater(int* arr,int size){
	int i, j, ref1, ref2, marker, markerSet = 0,sum = 0;

	if(size<3)
		return 0;

	for(i=0;i<size-1;i++){
		start:if(i!=size-2 && arr[i]>arr[i+1]){
				ref1 = i;

				for(j=ref1+1;j<size;j++){
					if(arr[j]>=arr[ref1]){
						ref2 = j;

						sum += getWater(arr,ref1+1,ref2-1,ref1);

						i = ref2;

						goto start;
					}

					else if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){
						marker = j+1;
						markerSet = 1;
					}
				}

				if(markerSet==1){
					sum += getWater(arr,ref1+1,marker-1,marker);

					i = marker;

					markerSet = 0;

					goto start;
				}
			}
		}

	return sum;
}

int main(int argC,char* argV[])
{
	int *arr,i;

	if(argC==1)
		printf("Usage : %s <followed by space separated series of integers>");
	else{
		arr = (int*)malloc((argC-1)*sizeof(int));

		for(i=1;i<argC;i++)
			arr[i-1] = atoi(argV[i]);

		printf("Water collected : %d",netWater(arr,argC-1));
	}

	return 0;
}


_Title "Voronoi Diagram"

Dim As Integer pnt, px, py, i, x, y, adjct, sy, ly
Dim As Double st

'=====================================================================
' Changes number of points and screen size here
'=====================================================================
pnt = 100
px = 512
py = 512
'=====================================================================
Screen _NewImage(px, py, 32)
Randomize Timer

Dim Shared As Integer pax(pnt), pay(pnt), indx(px, py)
Dim Shared As Long dSqr(px, py)
Dim As Long col(pnt)

For i = 1 To pnt
    pax(i) = Int(Rnd * px)
    pay(i) = Int(Rnd * py)
    col(i) = _RGB(Rnd * 256, Rnd * 256, Rnd * 256)
Next
st = Timer
For x = 0 To px - 1
    For y = 0 To py - 1
        dSqr(x, y) = (pax(1) - x) * (pax(1) - x) + (pay(1) - y) * (pay(1) - y)
        indx(x, y) = 1
    Next
Next

For i = 2 To pnt
    ly = py - 1
    For x = pax(i) To 0 Step -1
        If (scan(i, x, ly)) = 0 Then Exit For
    Next x
    For x = pax(i) + 1 To px - 1
        If (scan(i, x, ly)) = 0 Then Exit For
    Next
Next

For x = 0 To px - 1
    For y = 0 To py - 1
        sy = y
        adjct = indx(x, y)
        For y = y + 1 To py
            If indx(x, y) <> adjct Then y = y - 1: Exit For
        Next
        Line (x, sy)-(x, y + 1), col(adjct)
    Next
Next

Sleep
System

Function scan (site As Integer, x As Integer, ly As Integer)
    Dim As Integer ty
    Dim As Long delt2, dsq
    delt2 = (pax(site) - x) * (pax(site) - x)
    For ty = 0 To ly
        dsq = (pay(site) - ty) * (pay(site) - ty) + delt2
        If dsq <= dSqr(x, ty) Then
            dSqr(x, ty) = dsq
            indx(x, ty) = site
            scan = 1
        End If
    Next
End Function


## HF#1 Random Hex color
randHclr <- function() {
  m=255;r=g=b=0;
  r <- sample(0:m, 1, replace=TRUE);
  g <- sample(0:m, 1, replace=TRUE);
  b <- sample(0:m, 1, replace=TRUE);
  return(rgb(r,g,b,maxColorValue=m));
}
## HF#2 Metrics: Euclidean, Manhattan and Minkovski
Metric <- function(x, y, mt) {
  if(mt==1) {return(sqrt(x*x + y*y))}
  if(mt==2) {return(abs(x) + abs(y))}
  if(mt==3) {return((abs(x)^3 + abs(y)^3)^0.33333)}
}

## Plotting Voronoi diagram. aev 3/12/17
## ns - number of sites, fn - file name, ttl - plot title.
## mt - type of metric: 1 - Euclidean, 2 - Manhattan, 3 - Minkovski.
pVoronoiD <- function(ns, fn="", ttl="",mt=1) {
  cat(" *** START VD:", date(), "\n");
  if(mt<1||mt>3) {mt=1}; mts=""; if(mt>1) {mts=paste0(", mt - ",mt)};
  m=640; i=j=k=m1=m-2; x=y=d=dm=0;
  if(fn=="") {pf=paste0("VDR", mt, ns, ".png")} else {pf=paste0(fn, ".png")};
  if(ttl=="") {ttl=paste0("Voronoi diagram, sites - ", ns, mts)};
  cat(" *** Plot file -", pf, "title:", ttl, "\n");
  plot(NA, xlim=c(0,m), ylim=c(0,m), xlab="", ylab="", main=ttl);
  X=numeric(ns); Y=numeric(ns); C=numeric(ns);
  for(i in 1:ns) {
    X[i]=sample(0:m1, 1, replace=TRUE);
    Y[i]=sample(0:m1, 1, replace=TRUE);
    C[i]=randHclr();
  }
  for(i in 0:m1) {
    for(j in 0:m1) {
      dm=Metric(m1,m1,mt); k=-1;
      for(n in 1:ns) {
        d=Metric(X[n]-j,Y[n]-i, mt);
        if(d<dm) {dm=d; k=n;}
      }
      clr=C[k]; segments(j, i, j, i, col=clr);
    }
  }
  points(X, Y, pch = 19, col = "black", bg = "white")
  dev.copy(png, filename=pf, width=m, height=m);
  dev.off(); graphics.off();
  cat(" *** END VD:",date(),"\n");
}
## Executing:
pVoronoiD(150)          ## Euclidean metric
pVoronoiD(10,"","",2)   ## Manhattan metric
pVoronoiD(10,"","",3)   ## Minkovski metric


#lang racket

(require plot)

;; Performs clustering of points in a grid
;; using the nearest neigbour approach and shows
;; clusters in different colors
(define (plot-Voronoi-diagram point-list)
  (define pts
    (for*/list ([x (in-range 0 1 0.005)]
                [y (in-range 0 1 0.005)])
      (vector x y)))

  (define clusters (clusterize pts point-list))

  (plot
   (append
    (for/list ([r (in-list clusters)] [i (in-naturals)])
      (points (rest r) #:color i #:sym 'fullcircle1))
    (list (points point-list #:sym 'fullcircle5 #:fill-color 'white)))))

;; Divides the set of points into clusters
;; using given centroids
(define (clusterize data centroids)
  (for*/fold ([res (map list centroids)]) ([x (in-list data)])
    (define c (argmin (curryr (metric) x) centroids))
    (dict-set res c (cons x (dict-ref res c)))))


function find_pfile(string pathname, sequence dirent)
    if match("pfile.e",dirent[D_NAME]) then
--      return pathname&dirent[D_NAME] -- as below
        ?pathname&"\\"&dirent[D_NAME]
    end if
    return 0           -- non-zero terminates scan
end function

?walk_dir("C:\\Program Files (x86)\\Phix",find_pfile,1)


function findFiles($dir = '.', $pattern = '/./'){
  $prefix = $dir . '/';
  $dir = dir($dir);
  while (false !== ($file = $dir->read())){
    if ($file === '.' || $file === '..') continue;
    $file = $prefix . $file;
    if (is_dir($file)) findFiles($file, $pattern);
    if (preg_match($pattern, $file)){
      echo $file . "\n";
    }
  }
}
findFiles('./foo', '/\.bar$/');


(let Dir "."
   (recur (Dir)
      (for F (dir Dir)
         (let Path (pack Dir "/" F)
            (cond
               ((=T (car (info Path)))             # Is a subdirectory?
                  (recurse Path) )                 # Yes: Recurse
               ((match '`(chop "[email protected]") (chop F))   # Matches 's*.l'?
                  (println Path) ) ) ) ) ) )       # Yes: Print it


      INSTALL @lib$+"WINLIB5"
      ON ERROR SYS "MessageBox", @hwnd%, REPORT$, 0, 0 : QUIT

      REM!WC Windows constants:
      TVI_SORT = -65533
      TVIF_TEXT = 1
      TVM_INSERTITEM = 4352
      TVS_HASBUTTONS = 1
      TVS_HASLINES = 2
      TVS_LINESATROOT = 4

      REM. TV_INSERTSTRUCT
      DIM tvi{hParent%,       \
      \       hInsertAfter%,  \
      \       mask%,          \
      \       hItem%,         \
      \       state%,         \
      \       stateMask%,     \
      \       pszText%,       \
      \       cchTextMax%,    \
      \       iImage%,        \
      \       iSelectedImage%,\
      \       cChildren%,     \
      \       lParam%         \
      \      }

      SYS "InitCommonControls"
      hTree% = FN_createwindow("SysTreeView32", "", 0, 0, @vdu.tr%, @vdu.tb%, 0, \
      \                        TVS_HASLINES OR TVS_HASBUTTONS OR TVS_LINESATROOT, 0)
      hroot% = FNinsertnode(0, "Root")
      hchild1% = FNinsertnode(hroot%, "Child 1")
      hchild2% = FNinsertnode(hroot%, "Child 2")
      hchild11% = FNinsertnode(hchild1%, "Grandchild 1")
      hchild12% = FNinsertnode(hchild1%, "Grandchild 2")
      hchild21% = FNinsertnode(hchild2%, "Grandchild 3")
      hchild22% = FNinsertnode(hchild2%, "Grandchild 4")

      REPEAT
        WAIT 1
      UNTIL FALSE
      END

      DEF FNinsertnode(hparent%, text$)
      LOCAL hnode%
      text$ += CHR$0

      tvi.hParent% = hparent%
      tvi.hInsertAfter% = TVI_SORT
      tvi.mask% = TVIF_TEXT
      tvi.pszText% = !^text$

      SYS "SendMessage", hTree%, TVM_INSERTITEM, 0, tvi{} TO hnode%
      IF hnode% = 0 ERROR 100, "TVM_INSERTITEM failed"
      SYS "InvalidateRect", hTree%, 0, 0
      = hnode%


#include <stdio.h>
#include <stdlib.h>

typedef struct stem_t *stem;
struct stem_t { const char *str; stem next; };

void tree(int root, stem head)
{
	static const char *sdown = "  |", *slast = "  `", *snone = "   ";
	struct stem_t col = {0, 0}, *tail;

	for (tail = head; tail; tail = tail->next) {
		printf("%s", tail->str);
		if (!tail->next) break;
	}

	printf("--%d\n", root);

	if (root <= 1) return;

	if (tail && tail->str == slast)
		tail->str = snone;

	if (!tail)	tail = head = &col;
	else		tail->next = &col;

	while (root) { // make a tree by doing something random
		int r = 1 + (rand() % root);
		root -= r;
		col.str = root ? sdown : slast;

		tree(r, head);
	}

	tail->next = 0;
}

int main(int c, char**v)
{
	int n;
	if (c < 2 || (n = atoi(v[1])) < 0) n = 8;

	tree(n, 0);
	return 0;
}


vam=:1 :0
:
  exceeding=. 0 <. -&(+/)
  D=. x,y exceeding x NB. x: demands
  S=. y,x exceeding y NB. y: sources
  C=. (m,.0),0        NB. m: costs
  B=. 1+>./,C         NB. bigger than biggest cost
  mincost=. <./@-.&0  NB. smallest non-zero cost
  penalty=. |@(B * 2 -/@{. /:~ -. 0:)"1 - mincost"1
  R=. C*0
  while. 0 < +/D,S do.
    pS=. penalty C
    pD=. penalty |:C
    if. pS >&(>./) pD do.
      row=. (i. >./) pS
      col=. (i. mincost) row { C
    else.
      col=. (i. >./) pD
      row=. (i. mincost) col {"1 C
    end.
    n=. (row{S) <. col{D
    S=. (n-~row{S) row} S
    D=. (n-~col{D) col} D
    C=. C * S *&*/ D
    R=. n (<row,col)} R
  end.
  _1 _1 }. R
)


import java.util.Arrays;
import static java.util.Arrays.stream;
import java.util.concurrent.*;

public class VogelsApproximationMethod {

    final static int[] demand = {30, 20, 70, 30, 60};
    final static int[] supply = {50, 60, 50, 50};
    final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15},
    {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}};

    final static int nRows = supply.length;
    final static int nCols = demand.length;

    static boolean[] rowDone = new boolean[nRows];
    static boolean[] colDone = new boolean[nCols];
    static int[][] result = new int[nRows][nCols];

    static ExecutorService es = Executors.newFixedThreadPool(2);

    public static void main(String[] args) throws Exception {
        int supplyLeft = stream(supply).sum();
        int totalCost = 0;

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

            int quantity = Math.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];
        }

        stream(result).forEach(a -> System.out.println(Arrays.toString(a)));
        System.out.println("Total cost: " + totalCost);

        es.shutdown();
    }

    static int[] nextCell() throws Exception {
        Future<int[]> f1 = es.submit(() -> maxPenalty(nRows, nCols, true));
        Future<int[]> f2 = es.submit(() -> maxPenalty(nCols, nRows, false));

        int[] res1 = f1.get();
        int[] res2 = f2.get();

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

        return (res1[3] > res2[3]) ? res2 : res1;
    }

    static int[] diff(int j, int len, boolean isRow) {
        int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
        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 new int[]{min2 - min1, min1, minP};
    }

    static int[] maxPenalty(int len1, int len2, boolean isRow) {
        int md = Integer.MIN_VALUE;
        int pc = -1, pm = -1, mc = -1;
        for (int i = 0; i < len1; i++) {
            if (isRow ? rowDone[i] : colDone[i])
                continue;
            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 ? new int[]{pm, pc, mc, md} : new int[]{pc, pm, mc, md};
    }
}


class Program
{
    static void Main(string[] args)
    {
        int[][] wta = {
            new int[] {1, 5, 3, 7, 2},   new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },
            new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },
            new int[] { 5, 5, 5, 5 },    new int[] { 5, 6, 7, 8 },
            new int[] { 8, 7, 7, 6 },    new int[] { 6, 7, 10, 7, 6 }};
        string blk, lf = "\n", tb = "██", wr = "≈≈", mt = "  ";
        for (int i = 0; i < wta.Length; i++)
        {
            int bpf; blk = ""; do
            {
                string floor = ""; bpf = 0; for (int j = 0; j < wta[i].Length; j++)
                {
                    if (wta[i][j] > 0)
                    {    floor += tb; wta[i][j] -= 1; bpf += 1; }
                    else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);
                }
                if (bpf > 0) blk = floor + lf + blk;
            } while (bpf > 0);
            while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);
            while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);
            if (args.Length > 0) System.Console.Write("\n{0}", blk);
            System.Console.WriteLine("Block {0} retains {1,2} water units.",
                i + 1, (blk.Length - blk.Replace(wr, "").Length) / 2);
        }
    }
}


use Image::PNG::Portable;

my @bars = '▁▂▃▅▆▇▇▆▅▃▂▁'.comb;

my %type = ( # Voronoi diagram type distance calculation
    'Taxicab'   => sub ($px, $py, $x, $y) { ($px - $x).abs  + ($py - $y).abs  },
    'Euclidean' => sub ($px, $py, $x, $y) { ($px - $x)²     + ($py - $y)²     },
    'Minkowski' => sub ($px, $py, $x, $y) { ($px - $x)³.abs + ($py - $y)³.abs },
);

my $width  = 400;
my $height = 400;
my $dots   = 30;

my @domains = map { Hash.new(
    'x' => (5..$width-5).roll,
    'y' => (5..$height-5).roll,
    'rgb' => [(64..255).roll xx 3]
) }, ^$dots;

for %type.keys -> $type {
    print "\nGenerating $type diagram...    ", ' ' x @bars;
    my $img = voronoi(@domains, :w($width), :h($height), :$type);
    @domains.map: *.&dot($img);
    $img.write: "Voronoi-{$type}-perl6.png";
}

sub voronoi (@domains, :$w, :$h, :$type) {
    my $png = Image::PNG::Portable.new: :width($w), :height($h);
    (^$w).race.map: -> $x {
        print "\b" x 2+@bars, @bars.=rotate(1).join , '  ';
        for ^$h -> $y {
            my ($, $i) = min @domains.map: { %type{$type}(%($_)<x>, %($_)<y>, $x, $y), $++ };
            $png.set: $x, $y, |@domains[$i]<rgb>
        }
    }
    $png
}

sub dot (%h, $png, $radius = 3) {
    for (%h<x> X+ -$radius .. $radius) X (%h<y> X+ -$radius .. $radius) -> ($x, $y) {
            $png.set($x, $y, 0, 0, 0) if ( %h<x> - $x + (%h<y> - $y) * i ).abs <= $radius;
    }
}


lvars repp, fil;
;;; create path repeater
sys_file_match('.../*.p', '', false, 0) -> repp;
;;; iterate over paths
while (repp() ->> fil) /= termin do
     ;;; print the path
     printf(fil, '%s\n');
endwhile;


% submitted by Aykayayciti (Earl Lamont Montgomery)
% altered from fsaenzperez April 2019
% (swi-prolog.discourse-group)
test_run :-
        proc_dir('C:\\vvvv\\vvvv_beta_39_x64').

proc_dir(Directory) :-
    format('Directory: ~w~n',[Directory]),
    directory_files(Directory,Files),!,  %cut inserted
    proc_files(Directory,Files).

proc_files(Directory, [File|Files]) :-
    proc_file(Directory, File),!, %cut inserted
    proc_files(Directory, Files).
proc_files(_Directory, []).

proc_file(Directory, File) :-
    (
        File = '.',
        directory_file_path(Directory, File, Path),
        exists_directory(Path),!,%cut inserted
        format('Directory: ~w~n',[File])
    ;
        File = '..',
        directory_file_path(Directory, File, Path),
        exists_directory(Path),!,%cut inserted
        format('Directory: ~w~n',[File])
    ;
        directory_file_path(Directory, File, Path),
        exists_directory(Path),!,%cut inserted
        proc_dir(Path)
    ;
        directory_file_path(Directory, File, Path),
        exists_file(Path),!,%cut inserted
        format('File: ~w~n',[File])
    ;
        format('Unknown: ~w~n',[File])
    ).


#include <functional>
#include <iostream>
#include <random>

class BinarySearchTree {
private:
    struct Node {
        int key;
        Node *left, *right;

        Node(int k) : key(k), left(nullptr), right(nullptr) {
            //empty
        }
    } *root;

public:
    BinarySearchTree() : root(nullptr) {
        // empty
    }

    bool insert(int key) {
        if (root == nullptr) {
            root = new Node(key);
        } else {
            auto n = root;
            Node *parent;
            while (true) {
                if (n->key == key) {
                    return false;
                }

                parent = n;

                bool goLeft = key < n->key;
                n = goLeft ? n->left : n->right;

                if (n == nullptr) {
                    if (goLeft) {
                        parent->left = new Node(key);
                    } else {
                        parent->right = new Node(key);
                    }
                    break;
                }
            }
        }
        return true;
    }

    friend std::ostream &operator<<(std::ostream &, const BinarySearchTree &);
};

template<typename T>
void display(std::ostream &os, const T *n) {
    if (n != nullptr) {
        os << "Node(";

        display(os, n->left);

        os << ',' << n->key << ',';

        display(os, n->right);

        os << ")";
    } else {
        os << '-';
    }
}

std::ostream &operator<<(std::ostream &os, const BinarySearchTree &bst) {
    display(os, bst.root);
    return os;
}

int main() {
    std::default_random_engine generator;
    std::uniform_int_distribution<int> distribution(0, 200);
    auto rng = std::bind(distribution, generator);

    BinarySearchTree tree;

    tree.insert(100);
    for (size_t i = 0; i < 20; i++) {
        tree.insert(rng());
    }
    std::cout << tree << '\n';

    return 0;
}


immutable TProblem{T<:Integer,U<:String}
    sd::Array{Array{T,1},1}
    toc::Array{T,2}
    labels::Array{Array{U,1},1}
    tsort::Array{Array{T,2}, 1}
end

function TProblem{T<:Integer,U<:String}(s::Array{T,1},
                                        d::Array{T,1},
                                        toc::Array{T,2},
                                        slab::Array{U,1},
                                        dlab::Array{U,1})
    scnt = length(s)
    dcnt = length(d)
    size(toc) = (scnt,dcnt) || error("Supply, Demand, TOC Size Mismatch")
    length(slab) == scnt || error("Supply Label Size Labels")
    length(dlab) == dcnt || error("Demand Label Size Labels")
    0 <= minimum(s) || error("Negative Supply Value")
    0 <= minimum(d) || error("Negative Demand Value")
    sd = Array{T,1}[]
    push!(sd, s)
    push!(sd, d)
    labels = Array{U,1}[]
    push!(labels, slab)
    push!(labels, dlab)
    tsort = Array{T,2}[]
    push!(tsort, mapslices(sortperm, toc, 2))
    push!(tsort, mapslices(sortperm, toc, 1))
    TProblem(sd, toc, labels, tsort)
end
isbalanced(tp::TProblem) = sum(tp.sd[1]) == sum(tp.sd[2])

type Resource{T<:Integer}
    dim::T
    i::T
    quant::T
    l::T
    m::T
    p::T
    q::T
end
function Resource{T<:Integer}(dim::T, i::T, quant::T)
    zed = zero(T)
    Resource(dim, i, quant, zed, zed, zed, zed)
end

isavailable(r::Resource) = 0 < r.quant
Base.isless(a::Resource, b::Resource) = a.p < b.p || (a.p == b.p && b.q < a.q)


// version 1.1.3

val supply = intArrayOf(50, 60, 50, 50)
val demand = intArrayOf(30, 20, 70, 30, 60)

val costs = arrayOf(
    intArrayOf(16, 16, 13, 22, 17),
    intArrayOf(14, 14, 13, 19, 15),
    intArrayOf(19, 19, 20, 23, 50),
    intArrayOf(50, 12, 50, 15, 11)
)

val nRows = supply.size
val nCols = demand.size

val rowDone = BooleanArray(nRows)
val colDone = BooleanArray(nCols)
val results = Array(nRows) { IntArray(nCols) }

fun nextCell(): IntArray {
    val res1 = maxPenalty(nRows, nCols, true)
    val res2 = maxPenalty(nCols, nRows, false)
    if (res1[3] == res2[3])
        return if (res1[2] < res2[2]) res1 else res2
    return if (res1[3] > res2[3]) res2 else res1
}

fun diff(j: Int, len: Int, isRow: Boolean): IntArray {
    var min1 = Int.MAX_VALUE
    var min2 = min1
    var minP = -1
    for (i in 0 until len) {
        val done = if (isRow) colDone[i] else rowDone[i]
        if (done) continue
        val c = if (isRow) costs[j][i] else costs[i][j]
        if (c < min1) {
            min2 = min1
            min1 = c
            minP = i
        }
        else if (c < min2) min2 = c
    }
    return intArrayOf(min2 - min1, min1, minP)
}

fun maxPenalty(len1: Int, len2: Int, isRow: Boolean): IntArray {
    var md = Int.MIN_VALUE
    var pc = -1
    var pm = -1
    var mc = -1
    for (i in 0 until len1) {
        val done = if (isRow) rowDone[i] else colDone[i]
        if (done) continue
        val 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 if (isRow) intArrayOf(pm, pc, mc, md) else
                      intArrayOf(pc, pm, mc, md)
}

fun main(args: Array<String>) {
    var supplyLeft = supply.sum()
    var totalCost = 0
    while (supplyLeft > 0) {
        val cell = nextCell()
        val r = cell[0]
        val c = cell[1]
        val q = minOf(demand[c], supply[r])
        demand[c] -= q
        if (demand[c] == 0) colDone[c] = true
        supply[r] -= q
        if (supply[r] == 0) rowDone[r] = true
        results[r][c] = q
        supplyLeft -= q
        totalCost += q * costs[r][c]
    }

    println("    A   B   C   D   E")
    for ((i, result) in results.withIndex()) {
        print(('W'.toInt() + i).toChar())
        for (item in result) print("  %2d".format(item))
        println()
    }
    println("\nTotal Cost = $totalCost")
}


#include <iostream>
#include <vector>
#include <algorithm>

enum { EMPTY, WALL, WATER };

auto fill(const std::vector<int> b) {
  auto water = 0;
  const auto rows = *std::max_element(std::begin(b), std::end(b));
  const auto cols = std::size(b);
  std::vector<std::vector<int>> g(rows);
  for (auto& r : g) {
    for (auto i = 0; i < cols; ++i) {
      r.push_back(EMPTY);
    }
  }
  for (auto c = 0; c < cols; ++c) {
    for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) {
      g[r][c] = WALL;
    }
  }
  for (auto c = 0; c < cols - 1; ++c) {
    auto start_row = rows - b[c];
    while (start_row < rows) {
      if (g[start_row][c] == EMPTY) break;
      auto c2 = c + 1;
      bool hitWall = false;
      while (c2 < cols) {
        if (g[start_row][c2] == WALL) {
          hitWall = true;
          break;
        }
        ++c2;
      }
      if (hitWall) {
        for (auto i = c + 1; i < c2; ++i) {
          g[start_row][i] = WATER;
          ++water;
        }
      }
      ++start_row;
    }
  }
  return water;
}

int main() {
  std::vector<std::vector<int>> b = {
    { 1, 5, 3, 7, 2 },
    { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },
    { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },
    { 5, 5, 5, 5 },
    { 5, 6, 7, 8 },
    { 8, 7, 7, 6 },
    { 6, 7, 10, 7, 6 }
  };
  for (const auto v : b) {
    auto water = fill(v);
    std::cout << water << " water drops." << std::endl;
  }
  std::cin.ignore();
  std::cin.get();
  return 0;
}


Red [
	Source:     https://github.com/vazub/rosetta-red
	Tabs:       4
	Needs:       'View
]

comment {
	This is a naive and therefore inefficient approach. For production-related tasks,
	a proper full implementation of Fortune's algorithm should be preferred.
}

canvas: 500x500
num-points: 50
diagram-l1: make image! canvas
diagram-l2: make image! canvas

distance: function [
	"Find Taxicab (d1) and Euclidean (d2) distances between two points"
	pt1 [pair!]
	pt2 [pair!]
][
	d1: (absolute (pt1/x - pt2/x)) + absolute (pt1/y - pt2/y)
	d2: square-root ((pt1/x - pt2/x) ** 2 + ((pt1/y - pt2/y) ** 2))
	reduce [d1 d2]
]

;-- Generate random origin points with respective region colors
points: collect [
	random/seed now/time/precise
	loop num-points [
		keep random canvas
		keep random white
	]
]

;-- Color each pixel, based on region it belongs to
repeat y canvas/y [
	repeat x canvas/x [
		coord: as-pair x y
		min-dist: distance 1x1 canvas
		color-l1: color-l2: none
		foreach [point color] points [
			d: distance point coord
			if d/1 < min-dist/1 [min-dist/1: d/1 color-l1: color]
			if d/2 < min-dist/2 [min-dist/2: d/2 color-l2: color]
		]
		poke diagram-l1 coord color-l1
		poke diagram-l2 coord color-l2
	]
]

;-- Draw origin points for regions
foreach [point color] points [
	draw diagram-l1 compose [circle (point) 1]
	draw diagram-l2 compose [circle (point) 1]
]

;-- Put results on screen
view [
	title "Voronoi Diagram"
	image diagram-l1 image diagram-l2
]


let n_sites = 60

let size_x = 640
let size_y = 480

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

let dist_euclidean = (x, y) => { (x * x + y * y) }
let dist_minkowski = (x, y) => { (x * x * x + y * y * y) }
let dist_taxicab = (x, y) => { abs(x) + abs(y) }

let dist_f = dist_euclidean
let dist_f = dist_minkowski
let dist_f = dist_taxicab

let nearest_site = (site, x, y) => {
  let ret = ref(0)
  let dist = ref(0)
  Js.Array2.forEachi(site, ((sx, sy), k) => {
    let d = dist_f((x - sx), (y - sy))
    if (k == 0 || d < dist.contents) {
      dist.contents = d
      ret.contents = k
    }
  })
  ret.contents
}

let gen_map = (site, rgb) => {
  let nearest = Belt.Array.make((size_x * size_y), 0)
  let buf = Belt.Array.make((3 * size_x * size_y), 0)

  for y in 0 to size_y - 1 {
    for x in 0 to size_x - 1 {
      nearest[y * size_x + x] = nearest_site(site, x, y)
    }
  }

  for i in 0 to (size_y * size_x) - 1 {
    let j = i * 3
    let (r, g, b) = rgb[nearest[i]]
    buf[j+0] = r
    buf[j+1] = g
    buf[j+2] = b
  }

  Printf.printf("P3\n%d %d\n255\n", size_x, size_y)
  Js.Array2.forEach(buf, (d) => Printf.printf("%d\n", d))
}

{
  Random.self_init ();
  let site =
    Belt.Array.makeBy(n_sites, (i) => {
      (Random.int(size_x),
       Random.int(size_y))
     })

  let rgb =
    Belt.Array.makeBy(n_sites, (i) => {
      (rand_int_range( 50, 120),
       rand_int_range( 80, 180),
       rand_int_range(140, 240))
    })
  gen_map(site, rgb)
}


# Project : Voronoi diagram

load "guilib.ring"
load "stdlib.ring"
paint = null

new qapp
        {
        spots	= 100
        leftside = 400
        rightside = 400

        locx = list(spots)
        locy = list(spots)
        rgb = newlist(spots,3)
        seal = newlist(leftside, rightside)
        reach = newlist(leftside, rightside)

        win1 = new qwidget() {
                  setwindowtitle("Voronoi diagram")
                  setgeometry(100,100,800,600)
                  label1 = new qlabel(win1) {
                              setgeometry(10,10,800,600)
                              settext("")
                  }
                  new qpushbutton(win1) {
                          setgeometry(150,550,100,30)
                          settext("draw")
                          setclickevent("draw()")
                  }
                  show()
        }
        exec()
        }

func draw
        p1 = new qpicture()
               color = new qcolor() {
               setrgb(0,0,255,255)
        }
        pen = new qpen() {
                 setcolor(color)
                 setwidth(1)
        }
        paint = new qpainter() {
                  begin(p1)
                  setpen(pen)

        for i =1 to spots
             locx[i] = floor(leftside  * randomf())
             locy[i] = floor(rightside * randomf())
             rgb[i][1] = floor(256 * randomf())
             rgb[i][2] = floor(256 * randomf())
             rgb[i][3] = floor(256 * randomf())
        next
        for x = 1 to leftside
             for y = 1 to rightside
                 reach[x][y] = pow((locx[1] - x),2) + pow((locy[1] - y),2)
                 seal[x][y] = 1
             next
        next
        for i = 2 to spots
             for x = locx[i] to 0 step -1
                 if not (chkpos(i,x,1, rightside-1))
                   exit
                 ok
             next
             for x = locx[i] + 1 to leftside - 1
                  if not (chkpos(i, x, 1, rightside-1))
                     exit
                  ok
             next
        next
        for x = 1 to leftside
             for y = 1 to rightside
           	  c1 = rgb[seal[x][y]][1]
        	  c2 = rgb[seal[x][y]][2]
	          c3 = rgb[seal[x][y]][3]
                  color = new qcolor() { setrgb(c1,c2,c3,255) }
                  pen = new qpen()   { setcolor(color) setwidth(10) }
                  setpen(pen)
                  starty = y
                  nearest = seal[x][y]
                  for y = (y + 1)  to rightside
                       if seal[x][y] != nearest
                          y = y - 1
                          exit
                       ok
                  next
                  paint.drawline(x,starty,x,y + 1)
             next
        next
        endpaint()
        }
        label1 { setpicture(p1) show() }
        return

func chkpos(site,x,starty,endy)
        chkpos = 0
        dxsqr = 0
	dxsqr = pow((locx[site]- x),2)
	for y = starty to endy
	     dsqr = pow((locy[site] - y),2) + dxsqr
             if x <= leftside and y <= leftside and x > 0 and y > 0
	     if dsqr <= reach[x][y]
		reach[x][y]	= dsqr
		seal[x][y] = site
		chkpos = 1
             ok
	     ok
	next
        return chkpos

func randomf()
       decimals(10)
       str = "0."
       for i = 1 to 10
            nr = random(9)
            str = str + string(nr)
       next
       return number(str)


# frozen_string_literal: true

require_relative 'raster_graphics'

class ColourPixel < Pixel
  def initialize(x, y, colour)
    @colour = colour
    super x, y
  end
  attr_accessor :colour

  def distance_to(px, py)
    Math.hypot(px - x, py - y)
  end
end

width = 300
height = 200
npoints = 20
pixmap = Pixmap.new(width, height)

@bases = npoints.times.collect do |_i|
  ColourPixel.new(
    3 + rand(width - 6), 3 + rand(height - 6),  # provide a margin to draw a circle
    RGBColour.new(rand(256), rand(256), rand(256))
  )
end

pixmap.each_pixel do |x, y|
  nearest = @bases.min_by { |base| base.distance_to(x, y) }
  pixmap[x, y] = nearest.colour
end

@bases.each do |base|
  pixmap[base.x, base.y] = RGBColour::BLACK
  pixmap.draw_circle(base, 2, RGBColour::BLACK)
end

pixmap.save_as_png('voronoi_rb.png')


Procedure.s WalkRecursive(dir,path.s,Pattern.s="\.txt$")
  Static RegularExpression
  If Not RegularExpression
    RegularExpression=CreateRegularExpression(#PB_Any,Pattern)
  EndIf

  While NextDirectoryEntry(dir)
    If DirectoryEntryType(dir)=#PB_DirectoryEntry_Directory
      If DirectoryEntryName(dir)<>"." And DirectoryEntryName(dir)<>".."
        If ExamineDirectory(dir+1,path+DirectoryEntryName(dir),"")
          WalkRecursive(dir+1,path+DirectoryEntryName(dir)+"\",Pattern)
          FinishDirectory(dir+1)
        Else
          Debug "Error in "+path+DirectoryEntryName(dir)
        EndIf
      EndIf
    Else ; e.g. #PB_DirectoryEntry_File
      If MatchRegularExpression(RegularExpression,DirectoryEntryName(dir))
        Debug DirectoryEntryName(dir)
      EndIf
    EndIf
  Wend
EndProcedure


using System;

public static class VisualizeTree
{
    public static void Main() {
        "A".t(
            "B0".t(
                "C1",
                "C2".t(
                    "D".t("E1", "E2", "E3")),
                "C3".t(
                    "F1",
                    "F2",
                    "F3".t("G"),
                    "F4".t("H1", "H2"))),
            "B1".t(
                "K1",
                "K2".t(
                    "L1".t("M"),
                    "L2",
                    "L3"),
                "K3")
        ).Print();
    }

    private static Tree t(this string value, params Tree[] children) => new Tree(value, children);

    private static void Print(this Tree tree) => tree.Print(true, "");

    private static void Print(this Tree tree, bool last, string prefix) {
        (string current, string next) = last
            ? (prefix + "└─" + tree.Value, prefix + "  ")
            : (prefix + "├─" + tree.Value, prefix + "| ");
        Console.WriteLine(current[2..]);
        for (int c = 0; c < tree.Children.Length; c++) {
            tree.Children[c].Print(c == tree.Children.Length - 1, next);
        }
    }

    class Tree
    {
        public Tree(string value, params Tree[] children) => (Value, Children) = (value, children);
        public static implicit operator Tree(string value) => new Tree(value);
        public string Value { get; }
        public Tree[] Children { get; }
    }

}


function initArray(n,v)
    local tbl = {}
    for i=1,n do
        table.insert(tbl,v)
    end
    return tbl
end

function initArray2(m,n,v)
    local tbl = {}
    for i=1,m do
        table.insert(tbl,initArray(n,v))
    end
    return tbl
end

supply = {50, 60, 50, 50}
demand = {30, 20, 70, 30, 60}
costs = {
    {16, 16, 13, 22, 17},
    {14, 14, 13, 19, 15},
    {19, 19, 20, 23, 50},
    {50, 12, 50, 15, 11}
}

nRows = table.getn(supply)
nCols = table.getn(demand)

rowDone = initArray(nRows, false)
colDone = initArray(nCols, false)
results = initArray2(nRows, nCols, 0)

function diff(j,le,isRow)
    local min1 = 100000000
    local min2 = min1
    local minP = -1
    for i=1,le do
        local done = false
        if isRow then
            done = colDone[i]
        else
            done = rowDone[i]
        end
        if not done then
            local c = 0
            if isRow then
                c = costs[j][i]
            else
                c = costs[i][j]
            end
            if c < min1 then
                min2 = min1
                min1 = c
                minP = i
            elseif c < min2 then
                min2 = c
            end
        end
    end
    return {min2 - min1, min1, minP}
end

function maxPenalty(len1,len2,isRow)
    local md = -100000000
    local pc = -1
    local pm = -1
    local mc = -1

    for i=1,len1 do
        local done = false
        if isRow then
            done = rowDone[i]
        else
            done = colDone[i]
        end
        if not done then
            local res = diff(i, len2, isRow)
            if res[1] > md then
                md = res[1] -- max diff
                pm = i      -- pos of max diff
                mc = res[2] -- min cost
                pc = res[3] -- pos of min cost
            end
        end
    end

    if isRow then
        return {pm, pc, mc, md}
    else
        return {pc, pm, mc, md}
    end
end

function nextCell()
    local res1 = maxPenalty(nRows, nCols, true)
    local res2 = maxPenalty(nCols, nRows, false)
    if res1[4] == res2[4] then
        if res1[3] < res2[3] then
            return res1
        else
            return res2
        end
    else
        if res1[4] > res2[4] then
            return res2
        else
            return res1
        end
    end
end

function main()
    local supplyLeft = 0
    for i,v in pairs(supply) do
        supplyLeft = supplyLeft + v
    end
    local totalCost = 0
    while supplyLeft > 0 do
        local cell = nextCell()
        local r = cell[1]
        local c = cell[2]
        local q = math.min(demand[c], supply[r])
        demand[c] = demand[c] - q
        if demand[c] == 0 then
            colDone[c] = true
        end
        supply[r] = supply[r] - q
        if supply[r] == 0 then
            rowDone[r] = true
        end
        results[r][c] = q
        supplyLeft = supplyLeft - q
        totalCost = totalCost + q * costs[r][c]
    end

    print("    A   B   C   D   E")
    local labels = {'W','X','Y','Z'}
    for i,r in pairs(results) do
        io.write(labels[i])
        for j,c in pairs(r) do
            io.write(string.format("  %2d", c))
        end
        print()
    end
    print("Total Cost = " .. totalCost)
end

main()


(defn trapped-water [towers]
  (let [maxes #(reductions max %)                ; the seq of increasing max values found in the input seq
        maxl  (maxes towers)                     ; the seq of max heights to the left of each tower
        maxr  (reverse (maxes (reverse towers))) ; the seq of max heights to the right of each tower
        mins  (map min maxl maxr)]               ; minimum highest surrounding tower per position
    (reduce + (map - mins towers))))             ; sum up the trapped water per position


max = proc [T: type] (a,b: T) returns (T)
      where T has lt: proctype (T,T) returns (bool)
    if a<b then return(b)
    else return(a)
    end
end max

% based on: https://stackoverflow.com/a/42821623
water = proc (towers: sequence[int]) returns (int)
    si = sequence[int]

    w: int := 0
    left: int := 1
    right: int := si$size(towers)
    max_left: int := si$bottom(towers)
    max_right: int := si$top(towers)

    while left <= right do
        if towers[left] <= towers[right] then
            max_left := max[int](towers[left], max_left)
            w := w + max[int](max_left - towers[left], 0)
            left := left + 1
        else
            max_right := max[int](towers[right], max_right)
            w := w + max[int](max_right - towers[right], 0)
            right := right - 1
        end
    end
    return(w)
end water

start_up = proc ()
    si = sequence[int]
    ssi = sequence[si]

    po: stream := stream$primary_output()

    tests: ssi := ssi$[
        si$[1, 5, 3, 7, 2],
        si$[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
        si$[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
        si$[5, 5, 5, 5],
        si$[5, 6, 7, 8],
        si$[8, 7, 7, 6],
        si$[6, 7, 10, 7, 6]
    ]

    for test: si in ssi$elements(tests) do
        stream$puts(po, int$unparse(water(test)) || " ")
    end
end start_up


graphic #g, 400,400
#g flush()
spots		= 100
leftSide	= 400
rightSide	= 400

dim locX(spots)
dim locY(spots)
dim rgb(spots,3)
dim seal(leftSide, rightSide)
dim reach(leftSide, rightSide)

for i =1 to spots
    locX(i)	= int(leftSide  * rnd(1))
    locY(i)	= int(rightSide * rnd(1))
    rgb(i,1)	= int(256 * rnd(1))
    rgb(i,2)	= int(256 * rnd(1))
    rgb(i,3)	= int(256 * rnd(1))
    #g color(rgb(i,1),rgb(i,2),rgb(i,3))
    #g set(locX(i),locY(i))
next i
#g size(1)
' find reach to the first site
for x = 0 to leftSide - 1
    for y = 0 to rightSide - 1
        reach(x, y) = (locX(1) - x) ^ 2 + (locY(1) - y) ^ 2
        seal(x, y) = 1
    next y
next x
#g color("darkblue")

' spots other than 1st spot
for i = 2 to spots
    for x = locX(i) to 0 step -1		' looking left
        if not(chkPos(i,x,0, rightSide - 1)) then exit for
    next x
    for x = locX(i) + 1 to leftSide - 1		' looking right
        if not(chkPos(i, x, 0, rightSide - 1)) then exit for
    next x
next i

for x = 0 to leftSide - 1
    for y = 0 to rightSide - 1
	c1	= rgb(seal(x, y),1)
	c2	= rgb(seal(x, y),2)
	c3	= rgb(seal(x, y),3)
        #g color(c1,c2,c3)
        startY	= y
        nearest	= seal(x, y)
        for y = y + 1 to rightSide
            if seal(x, y) <> nearest then y = y - 1 : exit for
        next y
        #g line(x,startY,x,y + 1)
    next y
next x

#g color("black")
#g size(4)
for i =1 to spots
    #g set(locX(i),locY(i))
next i
render #g
end

function chkPos(site, x, startY, endY)
	dxSqr = (locX(site) - x) ^ 2
	for y = startY to endY
		dSqr = (locY(site) - y) ^ 2 + dxSqr
		if dSqr <= reach(x, y) then
			reach(x,y)	= dSqr
			seal(x,y)	= site
			chkPos		= 1
		end if
	next y
end function


extern crate piston;
extern crate opengl_graphics;
extern crate graphics;
extern crate touch_visualizer;

#[cfg(feature = "include_sdl2")]
extern crate sdl2_window;

extern crate getopts;
extern crate voronoi;
extern crate rand;

use touch_visualizer::TouchVisualizer;
use opengl_graphics::{ GlGraphics, OpenGL };
use graphics::{ Context, Graphics };
use piston::window::{ Window, WindowSettings };
use piston::input::*;
use piston::event_loop::*;
#[cfg(feature = "include_sdl2")]
use sdl2_window::Sdl2Window as AppWindow;
use voronoi::{voronoi, Point, make_polygons};
use rand::Rng;

static DEFAULT_WINDOW_HEIGHT: u32 = 600;
static DEFAULT_WINDOW_WIDTH:  u32 = 600;

struct Settings {
    lines_only: bool,
    random_count: usize
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    let mut opts = getopts::Options::new();
    opts.optflag("l", "lines_only", "Don't color polygons, just outline them");
    opts.optopt("r", "random_count", "On keypress \"R\", put this many random points on-screen", "RANDOMCOUNT");
    let matches = opts.parse(&args[1..]).expect("Failed to parse args");

    let settings = Settings{
        lines_only: matches.opt_present("l"),
        random_count: match matches.opt_str("r") {
            None => { 50 },
            Some(s) => { s.parse().expect("Random count of bad format") }
        }
    };

    event_loop(&settings);

}

fn random_point() -> [f64; 2] {
    [rand::thread_rng().gen_range(0., DEFAULT_WINDOW_HEIGHT as f64), rand::thread_rng().gen_range(0., DEFAULT_WINDOW_WIDTH as f64)]
}

fn random_color() -> [f32; 4] {
    [rand::random::<f32>(), rand::random::<f32>(), rand::random::<f32>(), 1.0]
}

fn random_voronoi(dots: &mut Vec<[f64;2]>, colors: &mut Vec<[f32;4]>, num: usize) {
    dots.clear();
    colors.clear();

    for _ in 0..num {
        dots.push(random_point());
        colors.push(random_color());
    }
}

fn event_loop(settings: &Settings) {
    let opengl = OpenGL::V3_2;
    let mut window: AppWindow = WindowSettings::new("Interactive Voronoi", [DEFAULT_WINDOW_HEIGHT, DEFAULT_WINDOW_WIDTH])
        .exit_on_esc(true).opengl(opengl).build().unwrap();

    let ref mut gl = GlGraphics::new(opengl);
    let mut touch_visualizer = TouchVisualizer::new();
    let mut events = Events::new(EventSettings::new().lazy(true));
    let mut dots = Vec::new();
    let mut colors = Vec::new();

    let mut mx = 0.0;
    let mut my = 0.0;

    while let Some(e) = events.next(&mut window) {
        touch_visualizer.event(window.size(), &e);
        if let Some(button) = e.release_args() {
            match button {
                Button::Keyboard(key) => {
                    if key == piston::input::keyboard::Key::N { dots.clear(); colors.clear(); }
                    if key == piston::input::keyboard::Key::R { random_voronoi(&mut dots, &mut colors, settings.random_count); }
                }
                Button::Mouse(_) => {
                    dots.push([mx, my]);
                    colors.push(random_color());
                },
                _ => ()
            }
        };
        e.mouse_cursor(|x, y| {
            mx = x;
            my = y;
        });
        if let Some(args) = e.render_args() {
            gl.draw(args.viewport(), |c, g| {
                graphics::clear([1.0; 4], g);
                let mut vor_pts = Vec::new();
                for d in &dots {
                    vor_pts.push(Point::new(d[0], d[1]));
                }
                if vor_pts.len() > 0 {
                    let vor_diagram = voronoi(vor_pts, DEFAULT_WINDOW_WIDTH as f64);
                    let vor_polys = make_polygons(&vor_diagram);
                    for (i, poly) in vor_polys.iter().enumerate() {
                        if settings.lines_only {
                            draw_lines_in_polygon(poly, &c, g);
                        } else {
                            draw_polygon(poly, &c, g, colors[i]);
                        }
                    }
                }
                for d in &dots {
                    draw_ellipse(&d, &c, g);
                }
            });
        }
    }

}

fn draw_lines_in_polygon<G: Graphics>(
    poly: &Vec<Point>,
    c: &Context,
    g: &mut G,
)
{
    let color = [0.0, 0.0, 1.0, 1.0];

    for i in 0..poly.len()-1 {
        graphics::line(
            color,
            2.0,
            [poly[i].x.into(), poly[i].y.into(), poly[i+1].x.into(), poly[i+1].y.into()],
            c.transform,
            g
        )
    }
}

fn draw_polygon<G: Graphics>(
    poly: &Vec<Point>,
    c: &Context,
    g: &mut G,
    color: [f32; 4]
) {
    let mut polygon_points: Vec<[f64; 2]> = Vec::new();

    for p in poly {
        polygon_points.push([p.x.into(), p.y.into()]);
    }

    graphics::polygon(
        color,
        polygon_points.as_slice(),
        c.transform,
        g
    )
}

fn draw_ellipse<G: Graphics>(
    cursor: &[f64; 2],
    c: &Context,
    g: &mut G,
) {
    let color = [0.0, 0.0, 0.0, 1.0];
    graphics::ellipse(
        color,
        graphics::ellipse::circle(cursor[0], cursor[1], 4.0),
        c.transform,
        g
    );
}


import java.awt.geom.Ellipse2D
import java.awt.image.BufferedImage
import java.awt.{Color, Graphics, Graphics2D}

import scala.math.sqrt

object Voronoi extends App {
  private val (cells, dim) = (100, 1000)
  private val rand = new scala.util.Random
  private val color = Vector.fill(cells)(rand.nextInt(0x1000000))
  private val image = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_RGB)
  private val g: Graphics2D = image.createGraphics()
  private val px = Vector.fill(cells)(rand.nextInt(dim))
  private val py = Vector.fill(cells)(rand.nextInt(dim))

  for (x <- 0 until dim;
       y <- 0 until dim) {
    var n = 0

    def distance(x1: Int, x2: Int, y1: Int, y2: Int) =
      sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2).toDouble) // Euclidian

    for (i <- px.indices
         if distance(px(i), x, py(i), y) < distance(px(n), x, py(n), y))
      n = i
    image.setRGB(x, y, color(n))
  }

  g.setColor(Color.BLACK)
  for (i <- px.indices) g.fill(new Ellipse2D.Double(px(i) - 2.5, py(i) - 2.5, 5, 5))

  new javax.swing.JFrame("Voronoi Diagram") {
    override def paint(g: Graphics): Unit = {g.drawImage(image, 0, 0, this); ()}

    setBounds(0, 0, dim, dim)
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE)
    setLocationRelativeTo(null)
    setResizable(false)
    setVisible(true)
  }

}


from pathlib import Path

for path in Path('.').rglob('*.*'):
    print(path)


-> (for ([f (in-directory "/tmp")] #:when (regexp-match? "\\.rkt$" f))
     (displayln f))
... *.rkt files including in nested directories ...


use File::Find;

.say for find dir => '.', name => /'.txt' $/;


//usage example: To list just Rascal source files,    Walk(|home:///workspace/|, ".rsc");
module Walk
import String;
import IO;
public void Walk(loc a, str pattern){
	for (entry <- listEntries(a))
		if (endsWith(entry, pattern))
		 	println(entry);
		elseif (isDirectory(a+entry))
			Walk(a+entry, pattern);
}


(defun visualize (tree)
  (labels
      ((rprint (list)
         (mapc #'princ (reverse list)))
       (vis-h (tree branches)
         (let ((len (length tree)))
           (loop
              for item in tree
              for idx from 1 to len do
                (cond
                  ((listp item)
                   (rprint (cdr branches))
                   (princ "+---+")
                   (let ((next (cons "|   "
                                     (if (= idx len)
                                         (cons "    " (cdr branches))
                                         branches))))
                     (terpri)
                     (rprint (if (null item)
                                 (cdr next)
                                 next))
                     (terpri)
                     (vis-h item next)))
                  (t
                   (rprint (cdr branches))
                   (princ item)
                   (terpri)
                   (rprint (if (= idx len)
                               (cdr branches)
                               branches))
                   (terpri)))))))
    (vis-h tree '("|   "))))


import math, sequtils, strutils

var
  supply = [50, 60, 50, 50]
  demand = [30, 20, 70, 30, 60]

let
  costs = [[16, 16, 13, 22, 17],
           [14, 14, 13, 19, 15],
           [19, 19, 20, 23, 50],
           [50, 12, 50, 15, 11]]

  nRows = supply.len
  nCols = demand.len

var
  rowDone = newSeq[bool](nRows)
  colDone = newSeq[bool](nCols)
  results = newSeqWith(nRows, newSeq[int](nCols))

proc diff(j, len: int; isRow: bool): array[3, int] =
  var min1, min2 = int.high
  var minP = -1
  for i in 0..<len:
    let done = if isRow: colDone[i] else: rowDone[i]
    if done: continue
    let c = if isRow: costs[j][i] else: costs[i][j]
    if c < min1:
      min2 = min1
      min1 = c
      minP = i
    elif c < min2:
      min2 = c
  result = [min2 - min1, min1, minP]

proc maxPenalty(len1, len2: int; isRow: bool): array[4, int] =
  var md = int.low
  var pc, pm, mc = -1
  for i in 0..<len1:
    let done = if isRow: rowDone[i] else: colDone[i]
    if done: continue
    let 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
  result = if isRow: [pm, pc, mc, md] else: [pc, pm, mc, md]

proc nextCell(): array[4, int] =
  let res1 = maxPenalty(nRows, nCols, true)
  let res2 = maxPenalty(nCols, nRows, false)
  if res1[3] == res2[3]:
    return if res1[2] < res2[2]: res1 else: res2
  result = if res1[3] > res2[3]: res2 else: res1

when isMainModule:

  var supplyLeft = sum(supply)
  var totalCost = 0

  while supplyLeft > 0:
    let cell = nextCell()
    let r = cell[0]
    let c = cell[1]
    let q = min(demand[c], supply[r])
    dec demand[c], q
    if demand[c] == 0: colDone[c] = true
    dec supply[r], q
    if supply[r] == 0: rowDone[r] = true
    results[r][c] = q
    dec supplyLeft, q
    inc totalCost, q * costs[r][c]

  echo "    A   B   C   D   E"
  for i, result in results:
    stdout.write chr(i + ord('W'))
    for item in result:
      stdout.write "  ", ($item).align(2)
    echo()
  echo "\nTotal cost = ", totalCost


include "cowgol.coh";
include "argv.coh";

# Count the amount of water in a given array
sub water(towers: [uint8], length: intptr): (units: uint8) is
    units := 0;
    loop
        var right := towers + length;
        loop
            right := @prev right;
            if right < towers or [right] != 0 then
                break;
            end if;
        end loop;
        if right < towers then break; end if;

        var blocks: uint8 := 0;
        var col := towers;
        while col <= right loop
            if [col] != 0 then
                [col] := [col] - 1;
                blocks := blocks + 1;
            elseif blocks != 0 then
                units := units + 1;
            end if;
            col := @next col;
        end loop;
        if blocks < 2 then
            break;
        end if;
    end loop;
end sub;

# Read list from the command line and print the answer
ArgvInit();
var towers: uint8[256];
var count: @indexof towers := 0;
var n32: int32;
loop
    var argmt := ArgvNext();
    if argmt == 0 as [uint8] then
        break;
    end if;
    (n32, argmt) := AToI(argmt);
    towers[count] := n32 as uint8;
    count := count + 1;
end loop;

if count == 0 then
    print("enter towers on command line\n");
    ExitWithError();
end if;

print_i8(water(&towers[0], count as intptr));
print_nl();


$ include "seed7_05.s7i";
  include "draw.s7i";
  include "keybd.s7i";

const type: point is new struct
    var integer: xPos is 0;
    var integer: yPos is 0;
    var color: col is black;
  end struct;

const proc: generateVoronoiDiagram (in integer: width, in integer: height, in integer: numCells) is func
  local
    var array point: points is 0 times point.value;
    var integer: index is 0;
    var integer: x is 0;
    var integer: y is 0;
    var integer: distSquare is 0;
    var integer: minDistSquare is 0;
    var integer: indexOfNearest is 0;
  begin
    screen(width, height);
    points := numCells times point.value;
    for index range 1 to numCells do
      points[index].xPos := rand(0, width);
      points[index].yPos := rand(0, height);
      points[index].col := color(rand(0, 65535), rand(0, 65535), rand(0, 65535));
    end for;
    for y range 0 to height do
      for x range 0 to width do
        minDistSquare := width ** 2 + height ** 2;
        for index range 1 to numCells do
          distSquare := (points[index].xPos - x) ** 2 + (points[index].yPos - y) ** 2;
          if distSquare < minDistSquare then
            minDistSquare := distSquare;
            indexOfNearest := index;
          end if;
        end for;
        point(x, y, points[indexOfNearest].col);
      end for;
    end for;
    for index range 1 to numCells do
      line(points[index].xPos - 2, points[index].yPos, 4, 0, black);
      line(points[index].xPos, points[index].yPos - 2, 0, 4, black);
    end for;
  end func;

const proc: main is func
  begin
    generateVoronoiDiagram(500, 500, 25);
    KEYBOARD := GRAPH_KEYBOARD;
    readln(KEYBOARD);
  end func;


require('Imager')

func generate_voronoi_diagram(width, height, num_cells) {
    var img = %O<Imager>.new(xsize => width, ysize => height)
    var (nx,ny,nr,ng,nb) = 5.of { [] }...

    for i in (^num_cells) {
        nx << rand(^width)
        ny << rand(^height)
        nr << rand(^256)
        ng << rand(^256)
        nb << rand(^256)
    }

    for y=(^height), x=(^width) {
        var j = (^num_cells -> min_by {|i| hypot(nx[i]-x, ny[i]-y) })
        img.setpixel(x => x, y => y, color => [nr[j], ng[j], nb[j]])
    }
    return img
}

var img = generate_voronoi_diagram(500, 500, 25)
img.write(file => 'VoronoiDiagram.png')


Sub printFiles(parentDir As FolderItem, pattern As String)
  For i As Integer = 1 To parentDir.Count
    If parentDir.Item(i).Directory Then
      printFiles(parentDir.Item(i), pattern)
    Else
      Dim rg as New RegEx
      Dim myMatch as RegExMatch
      rg.SearchPattern = pattern
      myMatch = rg.search(parentDir.Item(i).Name)
      If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)
    End If
  Next
End Sub


Red []

walk: func [
    "Walk a directory tree recursively, setting WORD to each file and evaluating BODY."

    'word              "For each file, set with the absolute file path."
    directory [file!]  "Starting directory."
    body      [block!] "Block to evaluate for each file, during which WORD is set."
    /where
    rules [block!]     "Parse rules defining file names to include."
][
    foreach file read directory [
        if where [if not parse file rules [continue]]
        either dir? file: rejoin [directory file] [walk item file body] [
            set 'word file
            do body
        ]
    ]
]

rules: compose [
    any (charset [#"A" - #"Z"])
    ".TXT"
]

walk/where file %/home/user/ [print file] rules


/*REXX program shows all files in a  directory tree  that match a given search criteria.*/
parse arg xdir;  if xdir=''  then xdir='\'       /*Any DIR specified?  Then use default.*/
@.=0                                             /*default result in case ADDRESS fails.*/
dirCmd= 'DIR /b /s'                              /*the DOS command to do heavy lifting. */
trace off                                        /*suppress REXX error message for fails*/
address system  dirCmd xdir  with output stem @. /*issue the DOS DIR command with option*/
if rc\==0  then do                               /*did the DOS DIR command get an error?*/
                say '***error!*** from DIR' xDIR /*error message that shows "que pasa". */
                say 'return code='  rc           /*show the  return code  from  DOS DIR.*/
                exit rc                          /*exit with    "     "     "    "   "  */
                end                              /* [↑]  bad ADDRESS cmd  (from DOS DIR)*/
#[email protected].rc                                           /*the number of  @.  entries generated.*/
if #==0  then #='   no   '                       /*use a better word choice for 0 (zero)*/
say center('directory '      xdir      " has "      #       ' matching entries.', 79, "─")

                do j=1  for #;       say @.j     /*show all the files that met criteria.*/
                end   /*j*/
exit @.0+rc                                      /*stick a fork in it,  we're all done. */


see "Testing DIR() " + nl
mylist = dir("C:\Ring")
for x in mylist
    if x[2]
       see "Directory : " + x[1] + nl
    else
       see "File : " + x[1] + nl
    ok
next
see "Files count : " + len(mylist)


import std.stdio, std.conv, std.algorithm, std.array;

struct Node(T) { T value; Node* left, right; }

string[] treeIndent(T)(in Node!T* t) pure nothrow @safe {
    if (!t) return ["-- (null)"];
    const tr = t.right.treeIndent;
    return "--" ~ t.value.text ~
           t.left.treeIndent.map!q{"  |" ~ a}.array ~
           ("  `" ~ tr[0]) ~ tr[1 .. $].map!q{"   " ~ a}.array;
}

void main () {
    static N(T)(T v, Node!T* l=null, Node!T* r=null) {
        return new Node!T(v, l, r);
    }

    const tree = N(1, N(2, N(4, N(7)), N(5)), N(3, N(6, N(8), N(9))));
    writefln("%-(%s\n%)", tree.treeIndent);
}


with javascript_semantics
sequence supply = {50,60,50,50},
         demand = {30,20,70,30,60},
         costs = {{16,16,13,22,17},
                  {14,14,13,19,15},
                  {19,19,20,23,50},
                  {50,12,50,15,11}}

sequence row_done = repeat(false,length(supply)),
         col_done = repeat(false,length(demand))

function diff(integer j, leng, bool is_row)
integer min1 = #3FFFFFFF, min2 = min1, min_p = -1
    for i=1 to leng do
        if not iff(is_row?col_done:row_done)[i] then
            integer c = iff(is_row?costs[j,i]:costs[i,j])
            if c<min1 then
                min2 = min1
                min1 = c
                min_p = i
            elsif c<min2 then
                min2 = c
            end if
        end if
    end for
    return {min2-min1,min1,min_p,j}
end function

function max_penalty(integer len1, len2, bool is_row)
integer pc = -1, pm = -1, mc = -1, md = -#3FFFFFFF
    for i=1 to len1 do
        if not iff(is_row?row_done:col_done)[i] then
            sequence res2 = diff(i, len2, is_row)
            if res2[1]>md then
                {md,mc,pc,pm} = res2
            end if
        end if
    end for
    return {md,mc}&iff(is_row?{pm,pc}:{pc,pm})
end function

integer supply_left = sum(supply),
        total_cost = 0

sequence results = repeat(repeat(0,length(demand)),length(supply))

while supply_left>0 do
    sequence cell = min(max_penalty(length(supply), length(demand), true),
                        max_penalty(length(demand), length(supply), false))
    integer {{},{},r,c} = cell,
            q = min(demand[c], supply[r])
    demand[c] -= q
    col_done[c] = (demand[c]==0)
    supply[r] -= q
    row_done[r] = (supply[r]==0)
    results[r, c] = q
    supply_left -= q
    total_cost += q * costs[r, c]
end while

printf(1,"     A   B   C   D   E\n")
for i=1 to length(supply) do
    printf(1,"%c ",'Z'-length(supply)+i)
    for j=1 to length(demand) do
        printf(1,"%4d",results[i,j])
    end for
    printf(1,"\n")
end for
printf(1,"\nTotal cost = %d\n", total_cost)


package require Tk
proc r to {expr {int(rand()*$to)}};   # Simple helper

proc voronoi {photo pointCount} {
    for {set i 0} {$i < $pointCount} {incr i} {
	lappend points [r [image width $photo]] [r [image height $photo]]
    }
    foreach {x y} $points {
	lappend colors [format "#%02x%02x%02x" [r 256] [r 256] [r 256]]
    }
    set initd [expr {[image width $photo] + [image height $photo]}]
    for {set i 0} {$i < [image width $photo]} {incr i} {
	for {set j 0} {$j < [image height $photo]} {incr j} {
	    set color black
	    set d $initd
	    foreach {x y} $points c $colors {
		set h [expr {hypot($x-$i,$y-$j)}]
		### Other interesting metrics
		#set h [expr {abs($x-$i)+abs($y-$j)}]
		#set h [expr {(abs($x-$i)**3+abs($y-$j)**3)**0.3}]
		if {$d > $h} {set d $h;set color $c}
	    }
	    $photo put $color -to $i $j
	}
	# To display while generating, uncomment this line and the other one so commented
	#if {$i%4==0} {update idletasks}
    }
}

# Generate a 600x400 Voronoi diagram with 60 random points
image create photo demo -width 600 -height 400
pack [label .l -image demo]
# To display while generating, uncomment this line and the other one so commented
#update
voronoi demo 60


require 'find'

Find.find('/your/path') do |f|
   # print file and path to screen if filename ends in ".mp3"
   puts f if f.match(/\.mp3\Z/)
end


#![feature(fs_walk)]

use std::fs;
use std::path::Path;

fn main() {
    for f in fs::walk_dir(&Path::new("/home/pavel/Music")).unwrap() {
        let p = f.unwrap().path();
        if p.extension().unwrap_or("".as_ref()) == "mp3" {
            println!("{:?}", p);
        }
    }
}


import java.io.File

object `package` {
  def walkTree(file: File): Iterable[File] = {
    val children = new Iterable[File] {
      def iterator = if (file.isDirectory) file.listFiles.iterator else Iterator.empty
    }
    Seq(file) ++: children.flatMap(walkTree(_))
  }
}

object Test extends App {
  val dir = new File("/home/user")
  for(f <- walkTree(dir)) println(f)
  for(f <- walkTree(dir) if f.getName.endsWith(".mp3")) println(f)
}


program Visualize_a_tree;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

type
  TNode = record
    _label: string;
    children: TArray<Integer>;
  end;

  TTree = TArray<TNode>;

  TTreeHelper = record helper for TTree
    procedure AddNode(lb: string; chl: TArray<Integer> = []);
  end;

procedure Vis(t: TTree);

  procedure f(n: Integer; pre: string);
  begin
    var ch := t[n].children;
    if Length(ch) = 0 then
    begin
      Writeln('-', t[n]._label);
      exit;
    end;

    writeln('+', t[n]._label);
    var last := Length(ch) - 1;
    for var c in copy(ch, 0, last) do
    begin
      write(pre, '+-');
      f(c, pre + '¦ ');
    end;
    write(pre, '+-');
    f(ch[last], pre + '  ');
  end;

begin
  if Length(t) = 0 then
  begin
    writeln('<empty>');
    exit;
  end;

  f(0, '');
end;

{ TTreeHelper }

procedure TTreeHelper.AddNode(lb: string; chl: TArray<Integer> = []);
begin
  SetLength(self, Length(self) + 1);
  with self[High(self)] do
  begin
    _label := lb;
    if Length(chl) > 0 then
      children := copy(chl, 0, length(chl));
  end;
end;

var
  Tree: TTree;

begin
  Tree.AddNode('root', [1, 2, 3]);
  Tree.AddNode('ei', [4, 5]);
  Tree.AddNode('bee');
  Tree.AddNode('si');
  Tree.AddNode('dee');
  Tree.AddNode('y', [6]);
  Tree.AddNode('eff');

  Vis(Tree);

  {$IFNDEF UNIX} readln; {$ENDIF}
end.


from collections import defaultdict

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}}
demand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60}
cols = sorted(demand.iterkeys())
supply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50}
res = dict((k, defaultdict(int)) for k in costs)
g = {}
for x in supply:
    g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g])
for x in demand:
    g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x])

while g:
    d = {}
    for x in demand:
        d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x]
    s = {}
    for x in supply:
        s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]]
    f = max(d, key=lambda n: d[n])
    t = max(s, key=lambda n: s[n])
    t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t)
    v = min(supply[f], demand[t])
    res[f][t] += v
    demand[t] -= v
    if demand[t] == 0:
        for k, n in supply.iteritems():
            if n != 0:
                g[k].remove(t)
        del g[t]
        del demand[t]
    supply[f] -= v
    if supply[f] == 0:
        for k, n in demand.iteritems():
            if n != 0:
                g[k].remove(f)
        del g[f]
        del supply[f]

for n in cols:
    print "\t", n,
print
cost = 0
for g in sorted(costs):
    print g, "\t",
    for n in cols:
        y = res[g][n]
        if y != 0:
            print y,
        cost += y * costs[g][n]
        print "\t",
    print
print "\n\nTotal Cost = ", cost


(*
A solution I'd show to Euclid !!!!.
Nigel Galloway May 4th., 2017
*)
let solve n =
  let (n,_)::(i,e)::g = n|>List.sortBy(fun n->(-(snd n)))
  let rec fn i g e l =
    match e with
    | (n,e)::t when n < i -> fn n g t (l+(i-n-1)*e)
    | (n,e)::t when n > g -> fn i n t (l+(n-g-1)*e)
    | (n,t)::e            -> fn i g e (l-t)
    | _                   -> l
  fn (min n i) (max n i) g (e*(abs(n-i)-1))


USING: formatting kernel math.statistics math.vectors sequences ;

: area ( seq -- n )
    [ cum-max ] [ <reversed> cum-max reverse vmin ] [ v- sum ] tri ;

{
    { 1 5 3 7 2 }
    { 5 3 7 2 6 4 5 9 1 2 }
    { 2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1 }
    { 5 5 5 5 }
    { 5 6 7 8 }
    { 8 7 7 6 }
    { 6 7 10 7 6 }
} [ dup area "%[%d, %] -> %d\n" printf ] each


import "graphics" for Canvas, Color
import "dome" for Window
import "random" for Random

class Game {
    static init() {
        Window.title = "Voronoi diagram"
        var cells = 70
        var size = 700
        Window.resize(size, size)
        Canvas.resize(size, size)
        voronoi(cells, size)
    }

    static update() {}

    static draw(alpha) {}

    static distSq(x1, x2, y1, y2) { (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) }

    static voronoi(cells, size) {
        var r = Random.new()
        var px = List.filled(cells, 0)
        var py = List.filled(cells, 0)
        var cl = List.filled(cells, 0)
        for (i in 0...cells) {
            px[i] = r.int(size)
            py[i] = r.int(size)
            cl[i] = Color.rgb(r.int(256), r.int(256), r.int(256))
        }
        for (x in 0...size) {
            for (y in 0...size) {
                var n = 0
                for (i in 0...cells) {
                     if (distSq(px[i], x, py[i], y) < distSq(px[n], x, py[n], y)) n = i
                }
                Canvas.pset(x, y, cl[n])
            }
        }
        for (i in 0...cells) {
            Canvas.circlefill(px[i], py[i], 2, Color.black)
        }
    }
}


(use posix)
(use files)
(use srfi-13)

(define (walk FN PATH)
  (for-each (lambda (ENTRY)
    (cond ((not (null? ENTRY))

	   (let ((MYPATH (make-pathname PATH ENTRY)))

	     (cond ((directory-exists? MYPATH)
		    (walk FN MYPATH) ))

	     (FN MYPATH) )))) (directory PATH #t) ))

(walk (lambda (X) (cond ((string-suffix? ".scm" X) (display X)(newline) ))) "/home/user/")


$ include "seed7_05.s7i";
  include "osfiles.s7i";

const proc: walkDir (in string: dirName, in string: extension) is func
  local
    var string: fileName is "";
    var string: path is "";
  begin
    for fileName range readDir(dirName) do
      path := dirName & "/" & fileName;
      if endsWith(path, extension) then
        writeln(path);
      end if;
      if fileType(path) = FILE_DIR then
        walkDir(path, extension);
      end if;
    end for;
  end func;

const proc: main is func
  begin
    walkDir(".", ".sd7");
  end func;


func traverse(Block callback, Dir dir) {
    dir.open(\var dir_h) || return nil

    dir_h.entries.each { |entry|
        if (entry.is_a(Dir)) {
            traverse(callback, entry)
        } else {
            callback(entry)
        }
    }
}

var dir = Dir.cwd
var pattern = /foo/   # display files that contain 'foo'

traverse(
    { |file|
        if (file.basename ~~ pattern) {
            say file
        }
    } => dir
)


import system'routines;
import extensions;

class Node
{
    string theValue;
    Node[] theChildren;

    constructor new(string value, Node[] children)
    {
        theValue := value;

        theChildren := children;
    }

    constructor new(string value)
        <= new(value, new Node[](0));

    constructor new(Node[] children)
        <= new(emptyString, children);

    get() = theValue;

    Children = theChildren;
}

extension treeOp
{
    writeTree(node, prefix)
    {
        var children := node.Children;
        var length := children.Length;

        children.zipForEach(new Range(1, length), (child,index)
        {
            self.printLine(prefix,"|");
            self.printLine(prefix,"+---",child.get());

            var nodeLine := prefix + (index==length).iif("    ","|   ");

            self.writeTree(child,nodeLine);
        });

        ^ self
    }

    writeTree(node)
        = self.writeTree(node,"");
}

public program()
{
    var tree := Node.new(
                 new Node[]{
                    Node.new("a", new Node[]
                    {
                        Node.new("b", new Node[]{Node.new("c")}),
                        Node.new("d")
                    }),
                    Node.new("e")
                 });

    console.writeTree(tree).readChar()
}


type tree =
    | T of string * tree list

let prefMid = seq { yield "├─"; while true do yield "│ " }
let prefEnd = seq { yield "└─"; while true do yield "  " }
let prefNone = seq { while true do yield "" }

let c2 x y = Seq.map2 (fun u v -> String.concat "" [u; v]) x y

let rec visualize (T(label, children)) pre =
    seq {
        yield (Seq.head pre) + label
        if children <> [] then
            let preRest = Seq.skip 1 pre
            let last = Seq.last (List.toSeq children)
            for e in children do
                if e = last then yield! visualize e (c2 preRest prefEnd)
                else yield! visualize e (c2 preRest prefMid)
    }

let example =
    T ("root",
            [T ("a",
                    [T ("a1",
                            [T ("a11", []);
                            T ("a12", []) ]) ]);
            T ("b",
                    [T ("b1", []) ]) ])

visualize example prefNone
|> Seq.iter (printfn "%s")


#lang racket
(define-values (1st 2nd 3rd) (values first second third))

(define-syntax-rule (?: x t f) (if (zero? x) f t))

(define (hash-ref2
         hsh# key-1 key-2
         #:fail-2 (fail-2 (λ () (error 'hash-ref2 "key-2:~a is not found in hash" key-2)))
         #:fail-1 (fail-1 (λ () (error 'hash-ref2 "key-1:~a is not found in hash" key-1))))
  (hash-ref (hash-ref hsh# key-1 fail-1) key-2 fail-2))

(define (VAM costs all-supply all-demand)
  (define (reduce-g/x g/x x#-- x x-v y y-v)
    (for/fold ((rv (?: x-v g/x (hash-remove g/x x))))
      (#:when (zero? y-v) ((k n) (in-hash x#--)) #:unless (zero? n))
      (hash-update rv k (curry remove y))))

  (define (cheapest-candidate/tie-break candidates)
    (define cand-max3 (3rd (argmax 3rd candidates)))
    (argmin 2nd (for/list ((cand candidates) #:when (= (3rd cand) cand-max3)) cand)))

  (let vam-loop
    ((res (hash))
     (supply all-supply)
     (g/supply
      (for/hash ((x (in-hash-keys all-supply)))
        (define costs#x (hash-ref costs x))
        (define key-fn (λ (g) (hash-ref costs#x g)))
        (values x (sort (hash-keys costs#x) < #:key key-fn #:cache-keys? #t))))
     (demand all-demand)
     (g/demand
      (for/hash ((x (in-hash-keys all-demand)))
        (define key-fn (λ (g) (hash-ref2 costs g x)))
        (values x (sort (hash-keys costs) < #:key key-fn #:cache-keys? #t)))))
    (cond
      [(and (hash-empty? supply) (hash-empty? demand)) res]
      [(or (hash-empty? supply) (hash-empty? demand)) (error 'VAM "Unbalanced supply / demand")]
      [else
       (define D
         (let ((candidates
                (for/list ((x (in-hash-keys demand)))
                  (match-define (hash-table ((== x) (and g#x (list g#x.0 _ ...))) _ ...) g/demand)
                  (define z (hash-ref2 costs g#x.0 x))
                  (match g#x
                    [(list _ g#x.1 _ ...) (list x z (- (hash-ref2 costs g#x.1 x) z))]
                    [(list _) (list x z z)]))))
           (cheapest-candidate/tie-break candidates)))

       (define S
         (let ((candidates
                (for/list ((x (in-hash-keys supply)))
                  (match-define (hash-table ((== x) (and g#x (list g#x.0 _ ...))) _ ...) g/supply)
                  (define z (hash-ref2 costs x g#x.0))
                  (match g#x
                    [(list _ g#x.1 _ ...) (list x z (- (hash-ref2 costs x g#x.1) z))]
                    [(list _) (list x z z)]))))
           (cheapest-candidate/tie-break candidates)))

       (define-values (d s)
         (let ((t>f? (if (= (3rd D) (3rd S)) (> (2nd S) (2nd D)) (> (3rd D) (3rd S)))))
           (if t>f? (values (1st D) (1st (hash-ref g/demand (1st D))))
               (values (1st (hash-ref g/supply (1st S))) (1st S)))))

       (define v (min (hash-ref supply s) (hash-ref demand d)))

       (define d-v (- (hash-ref demand d) v))
       (define s-v (- (hash-ref supply s) v))

       (define demand-- (?: d-v (hash-set demand d d-v) (hash-remove demand d)))
       (define supply-- (?: s-v (hash-set supply s s-v) (hash-remove supply s)))

       (vam-loop
        (hash-update res s (λ (h) (hash-update h d (λ (x) (+ v x)) 0)) hash)
        supply-- (reduce-g/x g/supply supply-- s s-v d d-v)
        demand-- (reduce-g/x g/demand demand-- d d-v s s-v))])))

(define (vam-solution-cost costs demand?cols solution)
  (match demand?cols
    [(? list? demand-cols)
     (for*/sum ((g (in-hash-keys costs)) (n (in-list demand-cols)))
       (* (hash-ref2 solution g n #:fail-2 0) (hash-ref2 costs g n)))]
    [(hash-table (ks _) ...) (vam-solution-cost costs (sort ks symbol<? solution))]))

(define (describe-VAM-solution costs demand sltn)
  (define demand-cols (sort (hash-keys demand) symbol<?))
  (string-join
   (map
    (curryr string-join "\t")
    `(,(map ~a (cons "" demand-cols))
      ,@(for/list ((g (in-hash-keys costs)))
          (cons (~a g) (for/list ((c demand-cols)) (~a (hash-ref2 sltn g c #:fail-2 "-")))))
      ()
      ("Total Cost:" ,(~a (vam-solution-cost costs demand-cols sltn)))))
   "\n"))

;; --------------------------------------------------------------------------------------------------
(let ((COSTS (hash 'W (hash 'A 16 'B 16 'C 13 'D 22 'E 17)
                   'X (hash 'A 14 'B 14 'C 13 'D 19 'E 15)
                   'Y (hash 'A 19 'B 19 'C 20 'D 23 'E 50)
                   'Z (hash 'A 50 'B 12 'C 50 'D 15 'E 11)))
      (DEMAND (hash 'A 30 'B 20 'C 70 'D 30 'E 60))
      (SUPPLY (hash 'W 50 'X 60 'Y 50 'Z 50)))
  (displayln (describe-VAM-solution COSTS DEMAND (VAM COSTS SUPPLY DEMAND))))


type tower
    hght as uinteger
    posi as uinteger
end type

sub shellsort( a() as tower )
    'quick and dirty shellsort, not the focus of this exercise
    dim as uinteger gap = ubound(a), i, j, n=ubound(a)
    dim as tower temp
    do
        gap = int(gap / 2.2)
        if gap=0 then gap=1
        for i=gap to n
            temp = a(i)
            j=i
            while j>=gap andalso a(j-gap).hght < temp.hght
                a(j) = a(j - gap)
                j -= gap
            wend
            a(j) = temp
        next i
    loop until gap = 1
end sub

'heights of towers in each city prefixed by the number of towers
data 5, 1, 5, 3, 7, 2
data 10, 5, 3, 7, 2, 6, 4, 5, 9, 1, 2
data 16, 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1
data 4, 5, 5, 5, 5
data 4, 5, 6, 7, 8
data 4, 8, 7, 7, 6
data 5, 6, 7, 10, 7, 6

dim as uinteger i, n, j, first, last, water
dim as tower manhattan(0 to 1)
for i = 1 to 7
    read n
    redim manhattan( 0 to n-1 )
    for j = 0 to n-1
        read manhattan(j).hght
        manhattan(j).posi = j
    next j
    shellsort( manhattan() )
    if manhattan(0).posi < manhattan(1).posi then
        first = manhattan(0).posi
        last  = manhattan(1).posi
    else
        first = manhattan(1).posi
        last  = manhattan(0).posi
    end if
    water = manhattan(1).hght * (last-first-1)
    for j = 2 to n-1
        if first<manhattan(j).posi and manhattan(j).posi<last then water -= manhattan(j).hght
        if manhattan(j).posi < first then
             water += manhattan(j).hght * (first-manhattan(j).posi-1)
             first = manhattan(j).posi
        end if
        if manhattan(j).posi > last then
             water += manhattan(j).hght * (manhattan(j).posi-last-1)
             last = manhattan(j).posi
        end if
    next j
    print using "City configuration ## collected #### units of water."; i; water
next i


include c:\cxpl\codes;          \intrinsic 'code' declarations

def     N = 15;                 \number of sites
int     SiteX(N), SiteY(N),     \coordinates of sites
        Dist2, MinDist2, MinI,  \distance squared, and minimums
        X, Y, I;
[SetVid($13);                   \set 320x200x8 graphics
for I:= 0 to N-1 do             \create a number of randomly placed sites
        [SiteX(I):= Ran(160);  SiteY(I):= Ran(100)];
for Y:= 0 to 100-1 do           \generate Voronoi diagram
    for X:= 0 to 160-1 do       \for all points...
        [MinDist2:= -1>>1;      \find closest site
        for I:= 0 to N-1 do
                [Dist2:= sq(X-SiteX(I)) + sq(Y-SiteY(I));
                if Dist2 < MinDist2 then
                        [MinDist2:= Dist2;  MinI:= I];
                ];
        if MinDist2 then Point(X, Y, MinI+1);   \leave center black
        ];
I:= ChIn(1);                    \wait for keystroke
SetVid($03);                    \restore normal text screen
]


clear screen

sites = 200
xEdge = 600
yEdge = 400

open window xEdge, yEdge

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

for i =1 to sites
    townX(i) =int(xEdge *ran(1))
    townY(i) =int(yEdge *ran(1))
    col$(i) = str$(int(256 * ran(1))) + ", " + str$(int(256 * ran(1))) + ", " + str$(int(256 * ran(1)))
    color col$(i)
    fill circle townX(i), townY(i), 2
next i

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

//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

color 0,0,255
//for other towns
for i = 2 to sites
    //display some progress
    //print at(0,20) "computing: ", (i/sites*100) using "###.#", " %"

    //look left
    for x = townX(i) to 0 step -1
        if not(checkRow(i, x,0, yEdge - 1)) break
    next x
    //look right
    for x = townX(i) + 1 to xEdge - 1
        if not(checkRow(i, x, 0, yEdge - 1)) break
    next x
next i

for x = 0 to xEdge - 1
    for y =0 to yEdge - 1
    	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 : break : end if
        next y
        line x, startY, x, y + 1
    next y
next x

color 0,0,0
for i =1 to sites
    fill circle townX( i), townY( i), 2
next i
print peek("millisrunning"), " ms"

sub checkRow(site, x, startY, endY)
    local dxSquared, y, check

    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
             check = 1
         end if
    next y
    return check
end sub


fcn generate_voronoi_diagram(width,height,num_cells){
   image,imgx,imgy:=PPM(width,height),width,height;
   nx:=num_cells.pump(List,(0).random.fp(imgx));
   ny:=num_cells.pump(List,(0).random.fp(imgy));
   nr:=num_cells.pump(List,(0).random.fp(256));  // red
   ng:=num_cells.pump(List,(0).random.fp(256));  // blue
   nb:=num_cells.pump(List,(0).random.fp(256));  // green

   foreach y,x in (imgy,imgx){
      dmin:=(imgx-1).toFloat().hypot(imgy-1);
      j:=-1;
      foreach i in (num_cells){
         d:=(nx[i] - x).toFloat().hypot(ny[i] - y);
	 if(d<dmin) dmin,j = d,i
      }
      image[x,y]=(nr[j]*0xff00 + ng[j])*0xff00 + nb[j];
   }
   image
}


Directory extend [
  wholeContent: aPattern do: twoBlock [
    self wholeContent: aPattern withLevel: 0 do: twoBlock.
  ]
  wholeContent: aPattern withLevel: l do: twoBlock [
    |cont|
    cont := (self contents) asSortedCollection.
    cont remove: '.'; remove: '..'.
    cont
    do: [ :n | |fn ps|
      ps := (Directory pathSeparator) asString.
      fn := (self name), ps, n.
      ((File name: fn) isDirectory)
      ifTrue: [
        twoBlock value: (n, ps) value: l.
	(Directory name: fn) wholeContent: aPattern withLevel: (l+1) do: twoBlock.
      ]
      ifFalse: [
        ( n =~ aPattern )
        ifMatched: [ :m |
          twoBlock value: n value: l
        ]
      ]
    ]
  ]
].