import Foundation

let fileSystem = FileManager.default
let rootPath = "/"

// Enumerate the directory tree (which likely recurses internally)...

if let fsTree = fileSystem.enumerator(atPath: rootPath) {

    while let fsNodeName = fsTree.nextObject() as? NSString {

        let fullPath = "\(rootPath)/\(fsNodeName)"

        var isDir: ObjCBool = false
        fileSystem.fileExists(atPath: fullPath, isDirectory: &isDir)

        if !isDir.boolValue && fsNodeName.pathExtension == "txt" {
            print(fsNodeName)
        }
    }
}


package require fileutil
proc walkin {path cmd} {
    set normalized [::fileutil::fullnormalize $path]
    set myname [lindex [info level 0] 0]
    set children [glob -nocomplain -directory $path -types hidden *]
    lappend children {*}[glob -nocomplain -directory $path *]
    foreach child $children[set children {}] {
        if {[file tail $child] in {. ..}} {
            continue
        }
        if {[file isdirectory $child]} {
            if {[file type $child] eq "link"} {
                set normalizedchild [fileutil::fullnormalize $child]
                if {[string first $normalized/ $normalizedchild] == 0} {
                    #symlink to a directory in $path.  Avoid cyclic traversal.
                    #Don't descend.
                } else {
                    $myname $child $cmd
                }
            }
        }
        {*}$cmd $child
    }
}

walkin /home/usr {apply {fname {
    set tail [file tail $fname]
    if {[string match *.mp3 $tail]} {
        puts $fname
    }
}}}


USE: literals

CONSTANT: mammals { "mammals" { "deer" "gorilla" "dolphin" } }
CONSTANT: reptiles { "reptiles" { "turtle" "lizard" "snake" } }

{ "animals" ${ mammals reptiles } } dup . 10 margin set .


Dim Shared As Ubyte colores(4) => {7,13,14,3,2}

Sub showTree(n As Integer, A As String)
    Dim As Integer i, co = 0, b = 1, col
    Dim As String cs = Left(A, 1)

    If cs = "" Then Exit Sub

    Select Case cs
    Case "["
        co += 1 : showTree(n + 1, Right(A, Len(A) - 1))
        Exit Select
    Case "]"
        co -= 1 : showTree(n - 1, Right(A, Len(A) - 1))
        Exit Select
    Case Else
        For i = 2 To n
            Print "  ";
            co = n
        Next i
        Color colores(co) : Print !"\&hc0-"; cs
        showTree(n, Right(A, Len(A) - 1))
        Exit Select
    End Select
End Sub

Cls
showTree(0, "[1[2[3][4[5][6]][7]][8[9]]]")
Print !"\n\n\n"
showTree(0, "[1[2[3[4]]][5[6][7[8][9]]]]")
Sleep


F dice5()
   R random:(1..5)

F distcheck(func, repeats, delta)
   V bin = DefaultDict[Int, Int]()
   L 1..repeats
      bin[func()]++
   V target = repeats I/ bin.len
   V deltacount = Int(delta / 100.0 * target)
   assert(all(bin.values().map(count -> abs(@target - count) < @deltacount)), ‘Bin distribution skewed from #. +/- #.: #.’.format(target, deltacount, sorted(bin.items()).map((key, count) -> (key, @target - count))))
   print(bin)

distcheck(dice5, 1000000, 1)


/* REXX ***************************************************************
* Solve the Transportation Problem using Vogel's Approximation
Default Input
2 3        # of sources / # of demands
25 35      sources
20 30 10   demands
3 5 7      cost matrix    <
3 2 5
* 20201210 support no input file -courtesy GS
*          Note: correctness of input is not checked
* 20210102 restored Vogel's Approximation and added Optimization
* 20210103 eliminated debug code
**********************************************************************/
Signal On Halt
Signal On Novalue
Signal On Syntax

Parse Arg fid
If fid='' Then
  fid='input1.txt'
Call init
m.=0
Do Forever
  dmax.=0
  dmax=0
  Do r=1 To rr
    dr.r=''
    Do c=1 To cc
      If cost.r.c<>'*' Then
        dr.r=dr.r cost.r.c
      End
    dr.r=words(dr.r) dr.r
    dr.r=diff(dr.r)
    If dr.r>dmax Then Do; dmax=dr.r; dmax.0='R'; dmax.1=r; dmax.2=dr.r; End
    End
  Do c=1 To cc
    dc.c=''
    Do r=1 To rr
      If cost.r.c<>'*' Then
        dc.c=dc.c cost.r.c
      End
    dc.c=words(dc.c) dc.c
    dc.c=diff(dc.c)
    If dc.c>dmax Then Do; dmax=dc.c; dmax.0='C'; dmax.1=c; dmax.2=dc.c; End
    End
  cmin=999
  Select
    When dmax.0='R' Then Do
      r=dmax.1
      Do c=1 To cc
        If cost.r.c<>'*' &,
           cost.r.c<cmin Then Do
          cmin=cost.r.c
          cx=c
          End
        End
      Call allocate r cx
      End
    When dmax.0='C' Then Do
      c=dmax.1
      Do r=1 To rr
        If cost.r.c<>'*' &,
           cost.r.c<cmin Then Do
          cmin=cost.r.c
          rx=r
          End
        End
      Call allocate rx c
      End
    Otherwise
      Leave
    End
  End

Do r=1 To rr
  Do c=1 To cc
    If cost.r.c<>'*' Then Do
      Call allocate r c
      cost.r.c='*'
      End
    End
  End

Call show_alloc 'Vogel''s Approximation'

Do r=1 To rr
  Do c=1 To cc
    cost.r.c=word(matrix.r.c,3)   /* restore cost.*.* */
    End
  End

Call steppingstone
Exit

/**********************************************************************
* Subroutines for Vogel's Approximation
**********************************************************************/

init:
If lines(fid)=0 Then Do
  Say 'Input file not specified or not found. Using default input instead.'
  fid='Default input'
  in.1=sourceline(4)
  Parse Var in.1 numSources .
  Do i=2 To numSources+3
    in.i=sourceline(i+3)
    End
  End
Else Do
  Do i=1 By 1 while lines(fid)>0
    in.i=linein(fid)
    End
  End
Parse Var in.1 numSources numDestinations . 1 rr cc .
source.=0
demand.=0
source_sum=0
Do i=1 To numSources
  Parse Var in.2 source.i in.2
  ss.i=source.i
  source_in.i=source.i
  source_sum=source_sum+source.i
  End
l=linein(fid)
demand_sum=0
Do i=1 To numDestinations
  Parse Var in.3 demand.i in.3
  dd.i=demand.i
  demand_in.i=demand.i
  demand_sum=demand_sum+demand.i
  End
Do i=1 To numSources
  j=i+3
  l=in.j
  Do j=1 To numDestinations
    Parse Var l cost.i.j l
    End
  End
Do i=1 To numSources
  ol=format(source.i,3)
  Do j=1 To numDestinations
    ol=ol format(cost.i.j,4)
    End
  End
ol='   '
Do j=1 To numDestinations
  ol=ol format(demand.j,4)
  End

Select
  When source_sum=demand_sum Then Nop  /* balanced */
  When source_sum>demand_sum Then Do   /* unbalanced - add dummy demand */
    Say 'This is an unbalanced case (sources exceed demands). We add a dummy consumer.'
    cc=cc+1
    demand.cc=source_sum-demand_sum
    demand_in.cc=demand.cc
    dd.cc=demand.cc
    Do r=1 To rr
      cost.r.cc=0
      End
    End
  Otherwise /* demand_sum>source_sum */ Do /* unbalanced - add dummy source */
    Say 'This is an unbalanced case (demands exceed sources). We add a dummy source.'
    rr=rr+1
    source.rr=demand_sum-source_sum
    source_in.rr=source.rr
    ss.rr=source.rr
    Do c=1 To cc
      cost.rr.c=0
      End
    End
  End

Say 'Sources / Demands / Cost'
ol='    '
Do c=1 To cc
  ol=ol format(demand.c,3)
  End
Say ol

Do r=1 To rr
  ol=format(source.r,4)
  Do c=1 To cc
    ol=ol format(cost.r.c,3)
    matrix.r.c=r c cost.r.c 0
    End
  Say ol
  End
Return

allocate: Procedure Expose m. source. demand. cost. rr cc matrix.
Parse Arg r c
sh=min(source.r,demand.c)
source.r=source.r-sh
demand.c=demand.c-sh
m.r.c=sh
matrix.r.c=subword(matrix.r.c,1,3) sh
If source.r=0 Then Do
  Do c=1 To cc
    cost.r.c='*'
    End
  End
If demand.c=0 Then Do
  Do r=1 To rr
    cost.r.c='*'
    End
  End
Return

diff: Procedure
Parse Value arg(1) With n list
If n<2 Then Return 0
list=wordsort(list)
Return word(list,2)-word(list,1)

wordsort: Procedure
/**********************************************************************
* Sort the list of words supplied as argument. Return the sorted list
**********************************************************************/
  Parse Arg wl
  wa.=''
  wa.0=0
  Do While wl<>''
    Parse Var wl w wl
    Do i=1 To wa.0
      If wa.i>w Then Leave
      End
    If i<=wa.0 Then Do
      Do j=wa.0 To i By -1
        ii=j+1
        wa.ii=wa.j
        End
      End
    wa.i=w
    wa.0=wa.0+1
    End
  swl=''
  Do i=1 To wa.0
    swl=swl wa.i
    End
  /* Say swl */
  Return strip(swl)

show_alloc: Procedure Expose matrix. rr cc demand_in. source_in.
Parse Arg header
If header='' Then
  Return
Say ''
Say header
total=0
ol='    '
Do c=1 to cc
  ol=ol format(demand_in.c,3)
  End
Say ol
as=''
Do r=1 to rr
  ol=format(source_in.r,4)
  a=word(matrix.r.1,4)
  If a=0.0000000001 Then a=0
  If a>0 Then
    ol=ol format(a,3)
  Else
    ol=ol ' - '
  total=total+word(matrix.r.1,4)*word(matrix.r.1,3)
  Do c=2 To cc
    a=word(matrix.r.c,4)
    If a=0.0000000001 Then a=0
    If a>0 Then
      ol=ol format(a,3)
    Else
      ol=ol ' - '
    total=total+word(matrix.r.c,4)*word(matrix.r.c,3)
    as=as a
    End
  Say ol
  End
Say 'Total costs:' format(total,4,1)
Return

/**********************************************************************
* Subroutines for Optimization
**********************************************************************/

steppingstone: Procedure Expose matrix. cost. rr cc matrix. demand_in.,
                              source_in. ms fid move cnt.
maxReduction=0
move=''
Call fixDegenerateCase
Do r=1 To rr
  Do c=1 To cc
    Parse Var matrix.r.c r c cost qrc
    If qrc=0 Then Do
      path=getclosedpath(r,c)
      If pelems(path)<4 Then Do
        Iterate
        End
      reduction = 0
      lowestQuantity = 1e10
      leavingCandidate = ''
      plus=1
      pathx=path
      Do While pathx<>''
        Parse Var pathx s '|' pathx
        If plus Then
          reduction=reduction+word(s,3)
        Else Do
          reduction=reduction-word(s,3)
          If word(s,4)<lowestQuantity Then Do
            leavingCandidate = s
            lowestQuantity = word(s,4)
            End
          End
        plus=\plus
        End
      If reduction < maxreduction Then Do
        move=path
        leaving=leavingCandidate
        maxReduction = reduction
        End
      End
    End
  End
if move<>'' Then Do
  quant=word(leaving,4)
  If quant=0 Then Do
    Call show_alloc 'Optimum'
    Exit
    End
  plus=1
  Do While move<>''
    Parse Var move m '|' move
    Parse Var m r c cpu qrc
    Parse Var matrix.r.c vr vc vcost vquant
    If plus Then
      nquant=vquant+quant
    Else
      nquant=vquant-quant
    matrix.r.c = vr vc vcost nquant
    plus=\plus
    End
  move=''
  Call steppingStone
  End
Else
  Call show_alloc 'Optimal Solution' fid
Return

getclosedpath: Procedure Expose matrix. cost. rr cc matrix.
Parse Arg rd,cd
path=rd cd cost.rd.cd word(matrix.rd.cd,4)
do r=1 To rr
  Do c=1 To cc
    If word(matrix.r.c,4)>0 Then Do
      path=path'|'r c cost.r.c word(matrix.r.c,4)
      End
    End
  End
path=magic(path)
Return stones(path)

magic: Procedure
Parse Arg list
Do Forever
  list_1=remove_1(list)
  If list_1=list Then Leave
  list=list_1
  End
Return list_1

remove_1: Procedure
Parse Arg list
cntr.=0
cntc.=0
Do i=1 By 1 While list<>''
  parse Var list e.i '|' list
  Parse Var e.i r c .
  cntr.r=cntr.r+1
  cntc.c=cntc.c+1
  End
n=i-1
keep.=1
Do i=1 To n
  Parse Var e.i r c .
  If cntr.r<2 |,
     cntc.c<2 Then Do
    keep.i=0
    End
  End
list=e.1
Do i=2 To n
  If keep.i Then
    list=list'|'e.i
  End
Return list

stones: Procedure
Parse Arg lst
tstc=lst
Do i=1 By 1 While tstc<>''
  Parse Var tstc o.i '|' tstc
  end
stones=lst
o.0=i-1
prev=o.1
Do i=1 To o.0
  st.i=prev
  k=i//2
  nbrs=getNeighbors(prev,lst)
  Parse Var nbrs n.1 '|' n.2
  If k=0 Then
    prev=n.2
  Else
    prev=n.1
  End
stones=st.1
Do i=2 To o.0
  stones=stones'|'st.i
  End
Return stones

getNeighbors: Procedure Expose o.
parse Arg s, lst
Do i=1 To 4
  Parse Var lst o.i '|' lst
  End
nbrs.=''
sr=word(s,1)
sc=word(s,2)
Do i=1 To o.0
  If o.i<>s Then Do
    or=word(o.i,1)
    oc=word(o.i,2)
    If or=sr & nbrs.0='' Then
      nbrs.0 = o.i
    else if oc=sc & nbrs.1='' Then
      nbrs.1 = o.i
    If nbrs.0<>'' & nbrs.1<>'' Then
      Leave
    End
  End
return nbrs.0'|'nbrs.1

m1: Procedure
Parse Arg z
Return z-1

pelems: Procedure
Call Trace 'O'
Parse Arg p
n=0
Do While p<>''
  Parse Var p x '|' p
  If x<>'' Then n=n+1
  End
Return n

fixDegenerateCase: Procedure Expose matrix. rr cc ms
Call matrixtolist
If (rr+cc-1)<>ms Then Do
  Do r=1 To rr
    Do c=1 To cc
      If word(matrix.r.c,4)=0 Then Do
        matrix.r.c=subword(matrix.r.c,1,3) 1.e-10
        Return
        End
      End
    End
  End
Return

matrixtolist: Procedure Expose matrix. rr cc ms
ms=0
list=''
Do r=1 To rr
  Do c=1 To cc
    If word(matrix.r.c,4)>0 Then Do
      list=list'|'matrix.r.c
      ms=ms+1
      End
    End
  End
Return strip(list,,'|')

Novalue:
  Say 'Novalue raised in line' sigl
  Say sourceline(sigl)
  Say 'Variable' condition('D')
  Signal lookaround

Syntax:
  Say 'Syntax raised in line' sigl
  Say sourceline(sigl)
  Say 'rc='rc '('errortext(rc)')'

halt:
lookaround:
  If fore() Then Do
    Say 'You can look around now.'
    Trace ?R
    Nop
    End
  Exit 12


package main

import "fmt"

func maxl(hm []int ) []int{
	res := make([]int,len(hm))
	max := 1
	for i := 0; i < len(hm);i++{
		if(hm[i] > max){
			max = hm[i]
		}
		res[i] = max;
	}
	return res
}
func maxr(hm []int ) []int{
	res := make([]int,len(hm))
	max := 1
	for i := len(hm) - 1 ; i >= 0;i--{
		if(hm[i] > max){
			max = hm[i]
		}
		res[i] = max;
	}
	return res
}
func min(a,b []int)  []int {
	res := make([]int,len(a))
	for i := 0; i < len(a);i++{
		if a[i] >= b[i]{
			res[i] = b[i]
		}else {
			res[i] = a[i]
		}
	}
	return res
}
func diff(hm, min []int) []int {
	res := make([]int,len(hm))
	for i := 0; i < len(hm);i++{
		if min[i] > hm[i]{
			res[i] = min[i] - hm[i]
		}
	}
	return res
}
func sum(a []int) int {
	res := 0
	for i := 0; i < len(a);i++{
		res += a[i]
	}
	return res
}

func waterCollected(hm []int) int {
	maxr := maxr(hm)
	maxl := maxl(hm)
	min := min(maxr,maxl)
	diff := diff(hm,min)
	sum := sum(diff)
	return sum
}

func main() {
	fmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))
	fmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))
	fmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))
	fmt.Println(waterCollected([]int{5, 5, 5, 5}))
	fmt.Println(waterCollected([]int{5, 6, 7, 8}))
	fmt.Println(waterCollected([]int{8, 7, 7, 6}))
	fmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))
}


(build (ftw "." (lambda (path type stat level base)
                  (if (ends-with ".tl" path)
                    (add path)))))


Sub walkTree(ByVal directory As IO.DirectoryInfo, ByVal pattern As String)
    For Each file In directory.GetFiles(pattern)
        Console.WriteLine(file.FullName)
    Next
    For Each subDir In directory.GetDirectories
        walkTree(subDir, pattern)
    Next
End Sub


import "io" for Directory, File
import "/pattern" for Pattern
import "/sort" for Sort

var walk // recursive function
walk = Fn.new { |dir, pattern, found|
    if (!Directory.exists(dir)) Fiber.abort("Directory %(dir) does not exist.")
    var files = Directory.list(dir)
    for (f in files) {
        var path = dir + "/%(f)"
        if (File.exists(path)) {  // it's a file not a directory
            if (pattern.isMatch(f)) found.add(f)
        } else {
            walk.call(path, pattern, found)
        }
    }
}

// get all C header files beginning with 'va' or 'vf'
var p = Pattern.new("v[a|f]+0^..h", Pattern.whole)
var found = []
walk.call("/usr/include", p, found)
Sort.quick(found)
for (f in found) System.print(f)


package main

import (
    "encoding/json"
    "fmt"
    "log"
)

type Node struct {
    Name     string
    Children []*Node
}

func main() {
    tree := &Node{"root", []*Node{
        &Node{"a", []*Node{
            &Node{"d", nil},
            &Node{"e", []*Node{
                &Node{"f", nil},
            }}}},
        &Node{"b", nil},
        &Node{"c", nil},
    }}
    b, err := json.MarshalIndent(tree, "", "   ")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(b))
}


data Tree a = Empty | Node { value :: a, left :: Tree a, right :: Tree a }
	deriving (Show, Eq)

tree = Node 1 (Node 2 (Node 4 (Node 7 Empty Empty) Empty)
	(Node 5 Empty Empty)) (Node 3 (Node 6 (Node 8 Empty Empty)
	(Node 9 Empty Empty)) Empty)

treeIndent Empty = ["-- (nil)"]
treeIndent t = ["--" ++ show (value t)]
	++ map ("  |"++) ls ++ ("  `" ++ r):map ("   "++) rs
	where
	(r:rs) = treeIndent$right t
	ls     = treeIndent$left t

main = mapM_ putStrLn $ treeIndent tree


with Ada.Numerics.Discrete_Random, Ada.Text_IO;

procedure Naive_Random is

   type M_1000 is mod 1000;
   package Rand is new Ada.Numerics.Discrete_Random(M_1000);
   Gen: Rand.Generator;

   procedure Perform(Modulus: Positive; Expected, Margin: Natural;
                    Passed: out boolean) is
      Low:  Natural  := (100-Margin) * Expected/100;
      High: Natural  := (100+Margin) * Expected/100;
      Buckets: array(0 .. Modulus-1) of Natural := (others => 0);
      Index: Natural;
   begin
      for I in 1 .. Expected * Modulus loop
         Index := Integer(Rand.Random(Gen)) mod Modulus;
         Buckets(Index) := Buckets(Index) + 1;
      end loop;
      Passed := True;
      for I in Buckets'Range loop
         Ada.Text_IO.Put("Bucket" & Integer'Image(I+1) & ":" &
                           Integer'Image(Buckets(I)));
         if Buckets(I) < Low or else Buckets(I) > High then
            Ada.Text_IO.Put_Line(" (failed)");
            Passed := False;
         else
            Ada.Text_IO.Put_Line(" (passed)");
         end if;
      end loop;
      Ada.Text_IO.New_Line;
   end Perform;

   Number_Of_Buckets: Positive := Natural'Value(Ada.Text_IO.Get_Line);
   Expected_Per_Bucket: Natural := Natural'Value(Ada.Text_IO.Get_Line);
   Margin_In_Percent: Natural := Natural'Value(Ada.Text_IO.Get_Line);
   OK: Boolean;

begin
   Ada.Text_IO.Put_Line(  "Buckets:"    & Integer'Image(Number_Of_Buckets) &
                          ", Expected:" & Integer'Image(Expected_Per_Bucket) &
                          ", Margin:"   & Integer'Image(Margin_In_Percent));
   Rand.Reset(Gen);

   Perform(Modulus  => Number_Of_Buckets,
           Expected => Expected_Per_Bucket,
           Margin   => Margin_In_Percent,
           Passed   => OK);

   Ada.Text_IO.Put_Line("Test Passed? (" & Boolean'Image(OK) & ")");
end Naive_Random;


MsgBox, % DistCheck("dice7",10000,3)

DistCheck(function, repetitions, delta)
{  Loop, % 7 ; initialize array
   {  bucket%A_Index% := 0
   }

   Loop, % repetitions ; populate buckets
   {  v := %function%()
      bucket%v% += 1
   }

   lbnd := round((repetitions/7)*(100-delta)/100)
   ubnd := round((repetitions/7)*(100+delta)/100)
   text := "Distribution check:`n`nTotal elements = " repetitions
         . "`n`nMargin = " delta "% --> Lbound = " lbnd ", Ubound = " ubnd "`n"
   Loop, % 7
   {  text := text "`nBucket " A_Index " contains " bucket%A_Index% " elements."
      If bucket%A_Index% not between %lbnd% and %ubnd%
         text := text " Skewed."
   }
   Return, text
}


# VAM
#
#  Nigel_Galloway
#  September 1st., 2013
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}
supply = {W: 50, X: 60, Y: 50, Z: 50}
COLS = demand.keys
res = {}; COSTS.each_key{|k| res[k] = Hash.new(0)}
g = {}; supply.each_key{|x| g[x] = COSTS[x].keys.sort_by{|g| COSTS[x][g]}}
        demand.each_key{|x| g[x] = COSTS.keys.sort_by{|g| COSTS[g][x]}}

until g.empty?
  d = demand.collect{|x,y| [x, z = COSTS[g[x][0]][x], g[x][1] ? COSTS[g[x][1]][x] - z : z]}
  dmax = d.max_by{|n| n[2]}
  d = d.select{|x| x[2] == dmax[2]}.min_by{|n| n[1]}
  s = supply.collect{|x,y| [x, z = COSTS[x][g[x][0]], g[x][1] ? COSTS[x][g[x][1]] - z : z]}
  dmax = s.max_by{|n| n[2]}
  s = s.select{|x| x[2] == dmax[2]}.min_by{|n| n[1]}
  t,f = d[2]==s[2] ? [s[1], d[1]] : [d[2],s[2]]
  d,s = t > f ? [d[0],g[d[0]][0]] : [g[s[0]][0],s[0]]
  v = [supply[s], demand[d]].min
  res[s][d] += v
  demand[d] -= v
  if demand[d] == 0 then
    supply.reject{|k, n| n == 0}.each_key{|x| g[x].delete(d)}
    g.delete(d)
    demand.delete(d)
  end
  supply[s] -= v
  if supply[s] == 0 then
    demand.reject{|k, n| n == 0}.each_key{|x| g[x].delete(s)}
    g.delete(s)
    supply.delete(s)
  end
end

COLS.each{|n| print "\t", n}
puts
cost = 0
COSTS.each_key do |g|
  print g, "\t"
  COLS.each do |n|
    y = res[g][n]
    print y if y != 0
    cost += y * COSTS[g][n]
    print "\t"
  end
  puts
end
print "\n\nTotal Cost = ", cost


Integer waterBetweenTowers(List<Integer> towers) {
    // iterate over the vertical axis. There the amount of water each row can hold is
    // the number of empty spots, minus the empty spots at the beginning and end
    return (1..towers.max()).collect { height ->
        // create a string representing the row, '#' for tower material and ' ' for air
        // use .trim() to remove spaces at beginning and end and then count remaining spaces
        towers.collect({ it >= height ? "#" : " " }).join("").trim().count(" ")
    }.sum()
}

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

tasks.each {
    println "$it => total water: ${waterBetweenTowers it}"
}


import Data.Vector.Unboxed (Vector)
import qualified Data.Vector.Unboxed as V

waterCollected :: Vector Int -> Int
waterCollected =
  V.sum .            -- Sum of the water depths over each of
  V.filter (> 0) .   -- the columns that are covered by some water.
  (V.zipWith (-) =<< -- Where coverages are differences between:
   (V.zipWith min .  -- the lower water level in each case of:
    V.scanl1 max <*> -- highest wall to left, and
    V.scanr1 max))   -- highest wall to right.

main :: IO ()
main =
  mapM_
    (print . waterCollected . V.fromList)
    [ [1, 5, 3, 7, 2]
    , [5, 3, 7, 2, 6, 4, 5, 9, 1, 2]
    , [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1]
    , [5, 5, 5, 5]
    , [5, 6, 7, 8]
    , [8, 7, 7, 6]
    , [6, 7, 10, 7, 6]
    ]


BOXC=: 9!:6 ''    NB. box drawing characters
EW  =: {: BOXC    NB. east-west

showtree=: 4 : 0
 NB. y is parent index for each node (non-indices for root nodes)
 NB. x is label for each node
 t=. (<EW,' ') ,@<@,:@,&":&.> x        NB. tree fragments
 c=. |:(#~ e./@|:);(~.,"0&.>(</. [email protected]#)) y
 while. +./ b=. ({.c)*.//.-.e.~/c do.
  i=. b#~.{.c                          NB. parents whose children are leaves
  j=. </./(({.c)e.i)#"1 c              NB. leaves grouped by parents
  t=. a: (;j)}t i}~ (i{t) subtree&.> j{&.><t
  c=. (-.({.c)e.i)#"1 c                NB. prune edges to leaves
 end.
 ;([: ,.&.>/ extend&.>)&> t -. a:
)

subtree=: 4 : 0
 p=. EW={."1 s=. >{.t=. graft y
 (<(>{.x) root p),(<(connect p),.s),}.t
)

graft=: 3 : 0
 n=. (-~ >./) #&> y
 f=. [email protected](,&0)@#&.>@{.&.> y
 ,&.>/ y ,&> n$&.>f
)

connect=: 3 : 0
 b=. (+./\ *. +./\.) y
 c=. (b+2*y){' ',9 3 3{BOXC  NB. │ NS ├ E
 c=. (0{BOXC) (b i. 1)}c     NB. ┌ NW
 c=. (6{BOXC) (b i: 1)}c     NB. └ SW
 j=. (b i. 1)+<.-:+/b
 EW&(j})^:(1=+/b) c j}~ ((0 3 6 9{BOXC)i.j{c){1 4 7 5{BOXC
)

root=: 4 : 0
 j=. k+<.-:1+(y i: 1)-k=. y i. 1
 (-j)|.(#y){.x,.,:' ',EW
)

extend=: 3 : '(+./\"1 (y=EW) *. *./\."1 y e.'' '',EW)}y,:EW'


      MAXRND = 7
      FOR r% = 2 TO 5
        check% = FNdistcheck(FNdice5, 10^r%, 0.05)
        PRINT "Over "; 10^r% " runs dice5 ";
        IF check% THEN
          PRINT "failed distribution check with "; check% " bin(s) out of range"
        ELSE
          PRINT "passed distribution check"
        ENDIF
      NEXT
      END

      DEF FNdistcheck(RETURN func%, repet%, delta)
      LOCAL i%, m%, r%, s%, bins%()
      DIM bins%(MAXRND)
      FOR i% = 1 TO repet%
        r% = FN(^func%)
        bins%(r%) += 1
        IF r%>m% m% = r%
      NEXT
      FOR i% = 1 TO m%
        IF bins%(i%)/(repet%/m%) > 1+delta s% += 1
        IF bins%(i%)/(repet%/m%) < 1-delta s% += 1
      NEXT
      = s%

      DEF FNdice5 = RND(5)


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

inline int rand5()
{
	int r, rand_max = RAND_MAX - (RAND_MAX % 5);
	while ((r = rand()) >= rand_max);
	return r / (rand_max / 5) + 1;
}

inline int rand5_7()
{
	int r;
	while ((r = rand5() * 5 + rand5()) >= 27);
	return r / 3 - 1;
}

/* assumes gen() returns a value from 1 to n */
int check(int (*gen)(), int n, int cnt, double delta) /* delta is relative */
{
	int i = cnt, *bins = calloc(sizeof(int), n);
	double ratio;
	while (i--) bins[gen() - 1]++;
	for (i = 0; i < n; i++) {
		ratio = bins[i] * n / (double)cnt - 1;
		if (ratio > -delta && ratio < delta) continue;

		printf("bin %d out of range: %d (%g%% vs %g%%), ",
			i + 1, bins[i], ratio * 100, delta * 100);
		break;
	}
	free(bins);
	return i == n;
}

int main()
{
	int cnt = 1;
	while ((cnt *= 10) <= 1000000) {
		printf("Count = %d: ", cnt);
		printf(check(rand5_7, 7, cnt, 0.03) ? "flat\n" : "NOT flat\n");
	}

	return 0;
}


collectLevels =: >./\ <. >./\.                          NB. collect levels after filling
waterLevels=: collectLevels - ]                         NB. water levels for each tower
collectedWater=: +/@waterLevels                         NB. sum the units of water collected
printTowers =: ' ' , [: |[email protected]|: '#~' #~ ] ,. waterLevels  NB. print a nice graph of towers and water


public class WaterBetweenTowers {
    public static void main(String[] args) {
        int i = 1;
        int[][] tba = new int[][]{
            new int[]{1, 5, 3, 7, 2},
            new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2},
            new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},
            new int[]{5, 5, 5, 5},
            new int[]{5, 6, 7, 8},
            new int[]{8, 7, 7, 6},
            new int[]{6, 7, 10, 7, 6}
        };

        for (int[] tea : tba) {
            int rht, wu = 0, bof;
            do {
                for (rht = tea.length - 1; rht >= 0; rht--) {
                    if (tea[rht] > 0) {
                        break;
                    }
                }

                if (rht < 0) {
                    break;
                }

                bof = 0;
                for (int col = 0; col <= rht; col++) {
                    if (tea[col] > 0) {
                        tea[col]--;
                        bof += 1;
                    } else if (bof > 0) {
                        wu++;
                    }
                }
                if (bof < 2) {
                    break;
                }
            } while (true);

            System.out.printf("Block %d", i++);
            if (wu == 0) {
                System.out.print(" does not hold any");
            } else {
                System.out.printf(" holds %d", wu);
            }
            System.out.println(" water units.");
        }
    }
}


public class VisualizeTree {
    public static void main(String[] args) {
        BinarySearchTree tree = new BinarySearchTree();

        tree.insert(100);
        for (int i = 0; i < 20; i++)
            tree.insert((int) (Math.random() * 200));
        tree.display();
    }
}

class BinarySearchTree {
    private Node root;

    private class Node {
        private int key;
        private Node left, right;

        Node(int k) {
            key = k;
        }
    }

    public boolean insert(int key) {
        if (root == null)
            root = new Node(key);
        else {
            Node n = root;
            Node parent;
            while (true) {
                if (n.key == key)
                    return false;

                parent = n;

                boolean goLeft = key < n.key;
                n = goLeft ? n.left : n.right;

                if (n == null) {
                    if (goLeft) {
                        parent.left = new Node(key);
                    } else {
                        parent.right = new Node(key);
                    }
                    break;
                }
            }
        }
        return true;
    }

    public void display() {
        final int height = 5, width = 64;

        int len = width * height * 2 + 2;
        StringBuilder sb = new StringBuilder(len);
        for (int i = 1; i <= len; i++)
            sb.append(i < len - 2 && i % width == 0 ? "\n" : ' ');

        displayR(sb, width / 2, 1, width / 4, width, root, " ");
        System.out.println(sb);
    }

    private void displayR(StringBuilder sb, int c, int r, int d, int w, Node n,
            String edge) {
        if (n != null) {
            displayR(sb, c - d, r + 2, d / 2, w, n.left, " /");

            String s = String.valueOf(n.key);
            int idx1 = r * w + c - (s.length() + 1) / 2;
            int idx2 = idx1 + s.length();
            int idx3 = idx1 - w;
            if (idx2 < sb.length())
                sb.replace(idx1, idx2, s).replace(idx3, idx3 + 2, edge);

            displayR(sb, c + d, r + 2, d / 2, w, n.right, "\\ ");
        }
    }
}


#include <map>
#include <iostream>
#include <cmath>

template<typename F>
 bool test_distribution(F f, int calls, double delta)
{
  typedef std::map<int, int> distmap;
  distmap dist;

  for (int i = 0; i < calls; ++i)
    ++dist[f()];

  double mean = 1.0/dist.size();

  bool good = true;

  for (distmap::iterator i = dist.begin(); i != dist.end(); ++i)
  {
    if (std::abs((1.0 * i->second)/calls - mean) > delta)
    {
      std::cout << "Relative frequency " << i->second/(1.0*calls)
                << " of result " << i->first
                << " deviates by more than " << delta
                << " from the expected value " << mean << "\n";
      good = false;
    }
  }

  return good;
}


(defn verify [rand n & [delta]]
  (let [rands (frequencies (repeatedly n rand))
        avg (/ (reduce + (map val rands)) (count rands))
        max-delta (* avg (or delta 1/10))
        acceptable? #(<= (- avg max-delta) % (+ avg max-delta))]
    (for [[num count] (sort rands)]
      [num count (acceptable? count)])))

(doseq [n [100 1000 10000]
        [num count okay?] (verify #(rand-int 7) n)]
  (println "Saw" num count "times:"
           (if okay? "that's" "   not") "acceptable"))


package require Tcl 8.6

# A sort that works by sorting by an auxiliary key computed by a lambda term
proc sortByFunction {list lambda} {
    lmap k [lsort -index 1 [lmap k $list {
	list $k [uplevel 1 [list apply $lambda $k]]
    }]] {lindex $k 0}
}

# A simple way to pick a “best” item from a list
proc minimax {list maxidx minidx} {
    set max -Inf; set min Inf
    foreach t $list {
	if {[set m [lindex $t $maxidx]] > $max} {
	    set best $t
	    set max $m
	    set min Inf
	} elseif {$m == $max && [set m [lindex $t $minidx]] < $min} {
	    set best $t
	    set min $m
	}
    }
    return $best
}

# The approximation engine. Note that this does not change the provided
# arguments at all since they are copied on write.
proc VAM {costs demand supply} {
    # Initialise the sorted sequence of pairs and the result dictionary
    foreach x [dict keys $demand] {
	dict set g $x [sortByFunction [dict keys $supply] {g {
	    upvar 1 costs costs x x; dict get $costs $g $x
	}}]
	dict set row $x 0
    }
    foreach x [dict keys $supply] {
	dict set g $x [sortByFunction [dict keys $demand] {g {
	    upvar 1 costs costs x x; dict get $costs $x $g
	}}]
	dict set res $x $row
    }

    # While there's work to do...
    while {[dict size $g]} {
	# Select "best" demand
	lassign [minimax [lmap x [dict keys $demand] {
	    if {![llength [set gx [dict get $g $x]]]} continue
	    set z [dict get $costs [lindex $gx 0] $x]
	    if {[llength $gx] > 1} {
		list $x $z [expr {[dict get $costs [lindex $gx 1] $x] - $z}]
	    } else {
		list $x $z $z
	    }
	}] 2 1] d dVal dCost

	# Select "best" supply
	lassign [minimax [lmap x [dict keys $supply] {
	    if {![llength [set gx [dict get $g $x]]]} continue
	    set z [dict get $costs $x [lindex $gx 0]]
	    if {[llength $gx] > 1} {
		list $x $z [expr {[dict get $costs $x [lindex $gx 1]] - $z}]
	    } else {
		list $x $z $z
	    }
	}] 2 1] s sVal sCost

	# Compute how much to transfer, and with which "best"
	if {$sCost == $dCost ? $sVal > $dVal : $sCost < $dCost} {
	    set s [lindex [dict get $g $d] 0]
	} else {
	    set d [lindex [dict get $g $s] 0]
	}
	set v [expr {min([dict get $supply $s], [dict get $demand $d])}]

	# Transfer some supply to demand
	dict update res $s inner {dict incr inner $d $v}
	dict incr demand $d -$v
	if {[dict get $demand $d] == 0} {
	    dict for {k n} $supply {
		if {$n != 0} {
		    # Filter list in dictionary to remove element
		    dict set g $k [lmap x [dict get $g $k] {
			if {$x eq $d} continue; set x
		    }]
		}
	    }
	    dict unset g $d
	    dict unset demand $d
	}
	dict incr supply $s -$v
	if {[dict get $supply $s] == 0} {
	    dict for {k n} $demand {
		if {$n != 0} {
		    dict set g $k [lmap x [dict get $g $k] {
			if {$x eq $s} continue; set x
		    }]
		}
	    }
	    dict unset g $s
	    dict unset supply $s
	}
    }
    return $res
}


(function () {
    'use strict';

    // waterCollected :: [Int] -> Int
    var waterCollected = function (xs) {
        return sum(                   // water above each bar
            zipWith(function (a, b) {
                    return a - b;     // difference between water level and bar
                },
                zipWith(min,          // lower of two flanking walls
                    scanl1(max, xs),  // highest walls to left
                    scanr1(max, xs)   // highest walls to right
                ),
                xs                    // tops of bars
            )
            .filter(function (x) {
                return x > 0;         // only bars with water above them
            })
        );
    };

    // GENERIC FUNCTIONS ----------------------------------------

    // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
    var zipWith = function (f, xs, ys) {
        var ny = ys.length;
        return (xs.length <= ny ? xs : xs.slice(0, ny))
            .map(function (x, i) {
                return f(x, ys[i]);
            });
    };

    // scanl1 is a variant of scanl that has no starting value argument
    // scanl1 :: (a -> a -> a) -> [a] -> [a]
    var scanl1 = function (f, xs) {
        return xs.length > 0 ? scanl(f, xs[0], xs.slice(1)) : [];
    };

    // scanr1 is a variant of scanr that has no starting value argument
    // scanr1 :: (a -> a -> a) -> [a] -> [a]
    var scanr1 = function (f, xs) {
        return xs.length > 0 ? scanr(f, xs.slice(-1)[0], xs.slice(0, -1)) : [];
    };

    // scanl :: (b -> a -> b) -> b -> [a] -> [b]
    var scanl = function (f, startValue, xs) {
        var lst = [startValue];
        return xs.reduce(function (a, x) {
            var v = f(a, x);
            return lst.push(v), v;
        }, startValue), lst;
    };

    // scanr :: (b -> a -> b) -> b -> [a] -> [b]
    var scanr = function (f, startValue, xs) {
        var lst = [startValue];
        return xs.reduceRight(function (a, x) {
            var v = f(a, x);
            return lst.push(v), v;
        }, startValue), lst.reverse();
    };

    // sum :: (Num a) => [a] -> a
    var sum = function (xs) {
        return xs.reduce(function (a, x) {
            return a + x;
        }, 0);
    };

    // max :: Ord a => a -> a -> a
    var max = function (a, b) {
        return a > b ? a : b;
    };

    // min :: Ord a => a -> a -> a
    var min = function (a, b) {
        return b < a ? b : a;
    };

    // TEST ---------------------------------------------------
    return [
        [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]
    ].map(waterCollected);

    //--> [2, 14, 35, 0, 0, 0, 0]
})();


<!doctype html>

  <meta charset="utf-8"/>
    <title>Stuff</title>

Headline

        Blah blah

More headline

Something something

Nested section

	  Somethin somethin list:

Apples

Oranges

Cetera Fruits

click me


0
├─ 1
├─ 2
└─ 3


using Gadfly, LightGraphs, GraphPlot

gx = kronecker(5, 12, 0.57, 0.19, 0.19)
gplot(gx)


// version 1.2.0

import java.util.Random

class Stem(var str: String? = null, var next: Stem? = null)

const val SDOWN = "  |"
const val SLAST = "  `"
const val SNONE = "   "

val rand = Random()

fun tree(root: Int, head: Stem?) {
    val col = Stem()
    var head2 = head
    var tail = head
    while (tail != null) {
        print(tail.str)
        if (tail.next == null) break
        tail = tail.next
    }
    println("--$root")
    if (root <= 1) return
    if (tail != null && tail.str == SLAST) tail.str = SNONE
    if (tail == null) {
        head2 = col
        tail = head2
    }
    else {
        tail.next = col
    }
    var root2 = root
    while (root2 != 0) { // make a tree by doing something random
        val r = 1 + rand.nextInt(root2)
        root2 -= r
        col.str = if (root2 != 0) SDOWN else SLAST
        tree(r, head2)
    }
    tail.next = null
}

fun main(args: Array<String>) {
    val n = 8
    tree(n, null)
}


(defun check-distribution (function n &optional (delta 1.0))
  (let ((bins (make-hash-table)))
    (loop repeat n do (incf (gethash (funcall function) bins 0)))
    (loop with target = (/ n (hash-table-count bins))
          for key being each hash-key of bins using (hash-value value)
          when (> (abs (- value target)) (* 0.01 delta n))
          do (format t "~&Distribution potentially skewed for ~w:~
                         expected around ~w got ~w." key target value)
          finally (return bins))))


import std.stdio, std.string, std.math, std.algorithm, std.traits;

/**
Bin the answers to fn() and check bin counts are within
+/- delta % of repeats/bincount.
*/
void distCheck(TF)(in TF func, in int nRepeats, in double delta) /*@safe*/
if (isCallable!TF) {
    int[int] counts;
    foreach (immutable i; 0 .. nRepeats)
        counts[func()]++;
    immutable double target = nRepeats / double(counts.length);
    immutable int deltaCount = cast(int)(delta / 100.0 * target);

    foreach (immutable k, const count; counts)
        if (abs(target - count) >= deltaCount)
            throw new Exception(format(
                "distribution potentially skewed for '%s': '%d'\n",
                k, count));

    foreach (immutable k; counts.keys.sort())
        writeln(k, " ", counts[k]);
    writeln;
}

version (verify_distribution_uniformity_naive_main) {
    void main() {
        import std.random;
        distCheck(() => uniform(1, 6), 1_000_000, 1);
    }
}


import "/math" for Int, Nums
import "/fmt" for Fmt

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

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

var nRows = supply.count
var nCols = demand.count

var rowDone = List.filled(nRows, false)
var colDone = List.filled(nCols, false)
var results = List.filled(nRows, null)
for (i in 0...nRows) results[i] = List.filled(nCols, 0)

var diff = Fn.new { |j, len, isRow|
    var min1 = Int.maxSafe
    var min2 = min1
    var minP = -1
    for (i in 0...len) {
        var done = isRow ? colDone[i] : rowDone[i]
        if (!done) {
            var c = isRow ? costs[j][i] : costs[i][j]
            if (c < min1) {
                min2 = min1
                min1 = c
                minP = i
            } else if (c < min2) min2 = c
        }
    }
    return [min2 - min1, min1, minP]
}

var maxPenalty = Fn.new { |len1, len2, isRow|
    var md = -Int.maxSafe
    var pc = -1
    var pm = -1
    var mc = -1
    for (i in 0...len1) {
        var done = isRow ? rowDone[i] : colDone[i]
        if (!done) {
            var res = diff.call(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 ? [pm, pc, mc, md] : [pc, pm, mc, md]
}

var nextCell = Fn.new {
    var res1 = maxPenalty.call(nRows, nCols, true)
    var res2 = maxPenalty.call(nCols, nRows, false)
    if (res1[3] == res2[3]) return (res1[2] < res2[2]) ? res1 : res2
    return (res1[3] > res2[3]) ? res2 : res1
}

var supplyLeft = Nums.sum(supply)
var totalCost = 0
while (supplyLeft > 0) {
    var cell = nextCell.call()
    var r = cell[0]
    var c = cell[1]
    var q = demand[c].min(supply[r])
    demand[c] = demand[c] - q
    if (demand[c] == 0) colDone[c] = true
    supply[r] = supply[r] - q
    if (supply[r] == 0) rowDone[r] = true
    results[r][c] = q
    supplyLeft = supplyLeft - q
    totalCost = totalCost + q*costs[r][c]
}

System.print("    A   B   C   D   E")
var i = 0
for (result in results) {
    Fmt.write("$c", "W".bytes[0] + i)
    for (item in result) Fmt.write("  $2d", item)
    System.print()
    i = i + 1
}
System.print("\nTotal Cost = %(totalCost)")


using Printf

function watercollected(towers::Vector{Int})
    high_lft = vcat(0, accumulate(max, towers[1:end-1]))
    high_rgt = vcat(reverse(accumulate(max, towers[end:-1:2])), 0)
    waterlvl = max.(min.(high_lft, high_rgt) .- towers, 0)
    return waterlvl
end

function towerprint(towers, levels)
    ctowers = copy(towers)
    clevels = copy(levels)
    hmax = maximum(towers)
    ntow = length(towers)
    for h in hmax:-1:1
        @printf("%2i |", h)
        for j in 1:ntow
            if ctowers[j] + clevels[j] ≥ h
                if clevels[j] > 0
                    cell = "≈≈"
                    clevels[j] -= 1
                else
                    cell = "NN"
                    ctowers[j] -= 1
                end
            else
                cell = "  "
            end
            print(cell)
        end
        println("|")
    end

    println("   " * join(lpad(t, 2) for t in levels) * ": Water lvl")
    println("   " * join(lpad(t, 2) for t in towers) * ": Tower lvl")
end

for towers in [[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]]
    towerprint(towers, watercollected(towers))
    println()
end


// version 1.1.2

fun waterCollected(tower: IntArray): Int {
    val n = tower.size
    val highLeft = listOf(0) + (1 until n).map { tower.slice(0 until it).max()!! }
    val highRight = (1 until n).map { tower.slice(it until n).max()!! } + 0
    return (0 until n).map { maxOf(minOf(highLeft[it], highRight[it]) - tower[it], 0) }.sum()
}

fun main(args: Array<String>) {
    val towers = listOf(
        intArrayOf(1, 5, 3, 7, 2),
        intArrayOf(5, 3, 7, 2, 6, 4, 5, 9, 1, 2),
        intArrayOf(2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1),
        intArrayOf(5, 5, 5, 5),
        intArrayOf(5, 6, 7, 8),
        intArrayOf(8, 7, 7, 6),
        intArrayOf(6, 7, 10, 7, 6)
    )
    for (tower in towers) {
        println("${"%2d".format(waterCollected(tower))} from ${tower.contentToString()}")
    }
}


-- parent script "TreeItem"
-- (minimal implementation with direct property access)

property name
property children

on new (me, itemName)
  me.name = itemName
  me.children = []
  return me
end

on addChild (me, child)
  me.children.add(child)
end

-- print a tree
on printTree (me, treeItem, indent)
  if voidP(treeItem) then treeItem = me
  if voidP(indent) then indent = ""
  put indent&treeItem.name
  repeat with c in treeItem.children
    me.printTree(c, indent&"  ")
  end repeat
end


function makeTree(v,ac)
    if type(ac) == "table" then
        return {value=v,children=ac}
    else
        return {value=v}
    end
end

function printTree(t,last,prefix)
    if last == nil then
        printTree(t, false, '')
    else
        local current = ''
        local next = ''

        if last then
            current = prefix .. '\\-' .. t.value
            next = prefix .. '  '
        else
            current = prefix .. '|-' .. t.value
            next = prefix .. '| '
        end

        print(current:sub(3))
        if t.children ~= nil then
            for k,v in pairs(t.children) do
                printTree(v, k == #t.children, next)
            end
        end
    end
end

printTree(
    makeTree('A', {
        makeTree('B0', {
            makeTree('C1'),
            makeTree('C2', {
                makeTree('D', {
                    makeTree('E1'),
                    makeTree('E2'),
                    makeTree('E3')
                })
            }),
            makeTree('C3', {
                makeTree('F1'),
                makeTree('F2'),
                makeTree('F3', {makeTree('G')}),
                makeTree('F4', {
                    makeTree('H1'),
                    makeTree('H2')
                })
            })
        }),
        makeTree('B1',{
            makeTree('K1'),
            makeTree('K2', {
                makeTree('L1', {makeTree('M')}),
                makeTree('L2'),
                makeTree('L3')
            }),
            makeTree('K3')
        })
    })
)


defmodule VerifyDistribution do
  def naive( generator, times, delta_percent ) do
    dict = Enum.reduce( List.duplicate(generator, times), Map.new, &update_counter/2 )
    values = Map.values(dict)
    average = Enum.sum( values ) / map_size( dict )
    delta = average * (delta_percent / 100)
    fun = fn {_key, value} -> abs(value - average) > delta end
    too_large_dict = Enum.filter( dict, fun )
    return( length(too_large_dict), too_large_dict, average, delta_percent )
  end

  def return( 0, _too_large_dict, _average, _delta ), do: :ok
  def return( _n, too_large_dict, average, delta ) do
    {:error, {too_large_dict, :failed_expected_average, average, 'with_delta_%', delta}}
  end

  def update_counter( fun, dict ), do: Map.update( dict, fun.(), 1, &(&1+1) )
end

fun = fn -> Dice.dice7 end
IO.inspect VerifyDistribution.naive( fun, 100000, 3 )
IO.inspect VerifyDistribution.naive( fun, 100, 3 )


-module( verify_distribution_uniformity ).

-export( [naive/3] ).

naive( Generator, Times, Delta_percent ) ->
    Dict = lists:foldl( fun update_counter/2, dict:new(), lists:duplicate(Times, Generator) ),
    Values = [dict:fetch(X, Dict) || X <- dict:fetch_keys(Dict)],
    Average = lists:sum( Values ) / dict:size( Dict ),
    Delta = Average * (Delta_percent / 100),
    Fun = fun(_Key, Value) -> erlang:abs(Value - Average) > Delta end,
    Too_large_dict = dict:filter( Fun, Dict ),
    return( dict:size(Too_large_dict), Too_large_dict, Average, Delta_percent ).

return( 0, _Too_large_dict, _Average, _Delta ) -> ok;
return( _N, Too_large_dict, Average, Delta ) ->
	{error, {dict:to_list(Too_large_dict), failed_expected_average, Average, 'with_delta_%', Delta}}.

update_counter( Fun, Dict ) -> dict:update_counter( Fun(), 1, Dict ).


>function checkrandom (frand$, n:index, delta:positive real) ...
$  v=zeros(1,n);
$  loop 1 to n; v{#}=frand$(); end;
$  K=max(v);
$  fr=getfrequencies(v,1:K);
$  return max(fr/n-1/K)<delta/sqrt(n);
$  endfunction
>function dice () := intrandom(1,1,6);
>checkrandom("dice",1000000,1)
 1
>wd = 0|((1:6)+[-0.01,0.01,0,0,0,0])/6
 [ 0  0.165  0.335  0.5  0.666666666667  0.833333333333  1 ]
>function wrongdice () := find(wd,random())
>checkrandom("wrongdice",1000000,1)
 0


N_ROWS = 4 : N_COLS = 5

dim supply(N_ROWS)
dim demand(N_COLS)

restore sup
for n = 0 to N_ROWS - 1
	read supply(n)
next n

restore dem
for n = 0 to N_COLS - 1
	read demand(n)
next n

label sup
data 50, 60, 50, 50

label dem
data 30, 20, 70, 30, 60

dim costs(N_ROWS, N_COLS)

label cost
data 16, 16, 13, 22, 17
data 14, 14, 13, 19, 15
data 19, 19, 20, 23, 50
data 50, 12, 50, 15, 11

restore cost
for i = 0 to N_ROWS - 1
	for j = 0 to N_COLS - 1
		read costs(i, j)
	next j
next i

dim row_done(N_ROWS)
dim col_done(N_COLS)

sub diff(j, leng, is_row, res())
    local i, c, min1, min2, min_p, test

    min1 = 10e300 : min2 = min1 : min_p = -1

    for i = 0 to leng - 1
    	if is_row then
    		test = col_done(i)
    	else
    		test = row_done(i)
    	end if
    	if test continue
    	if is_row then
    		c = costs(j, i)
    	else
    		c = costs(i, j)
    	end if
        if c < min1 then
            min2 = min1
            min1 = c
            min_p = i
        elseif c < min2 then
        	min2 = c
        end if
    next i
    res(0) = min2 - min1
    res(1) = min1
    res(2) = min_p
end sub

sub max_penalty(len1, len2, is_row, res())
    local i, pc, pm, mc, md, res2(3), test

    pc = -1 : pm = -1 : mc = -1 : md = -10e300

    for i = 0 to len1 - 1
        if is_row then
    		test = row_done(i)
    	else
    		test = col_done(i)
    	end if
        if test continue
       	diff(i, len2, is_row, res2())
        if res2(0) > md then
            md = res2(0)  //* max diff */
            pm = i        //* pos of max diff */
            mc = res2(1)  //* min cost */
            pc = res2(2)  //* pos of min cost */
        end if
    next i

    if is_row then
        res(0) = pm : res(1) = pc
    else
        res(0) = pc : res(1) = pm
    end if
    res(2) = mc : res(3) = md
end sub

sub next_cell(res())
    local i, res1(4), res2(4)

    max_penalty(N_ROWS, N_COLS, TRUE, res1())
    max_penalty(N_COLS, N_ROWS, FALSE, res2())

    if res1(3) = res2(3) then
        if res1(2) < res2(2) then
            for i = 0 to 3 : res(i) = res1(i) : next i
        else
            for i = 0 to 3 : res(i) = res2(i) : next i
        end if
        return
    end if
    if res1(3) > res2(3) then
        for i = 0 to 3 : res(i) = res2(i) : next i
    else
        for i = 0 to 3 : res(i) = res1(i) : next i
    end if
end sub

supply_left = 0 : total_cost = 0 : dim cell(4)

dim results(N_ROWS, N_COLS)

for i = 0 to N_ROWS - 1 : supply_left = supply_left + supply(i) : next i

while(supply_left > 0)
    next_cell(cell())
    r = cell(0)
    c = cell(1)
    q = min(demand(c), supply(r))
    demand(c) = demand(c) - q
    if not demand(c) col_done(c) = TRUE
    supply(r) = supply(r) - q
    if not supply(r) row_done(r) = TRUE
    results(r, c) = q
    supply_left = supply_left - q
    total_cost = total_cost + q * costs(r, c)
wend

print "    A   B   C   D   E\n"
for i = 0 to N_ROWS - 1
    print chr$(asc("W") + i), " ";
    for j = 0 to N_COLS - 1
    	print results(i, j) using "###";
    next j
    print
next i
print "\nTotal cost = ", total_cost


function waterCollected(i,tower)
    local length = 0
    for _ in pairs(tower) do
        length = length + 1
    end

    local wu = 0
    repeat
        local rht = length - 1
        while rht >= 0 do
            if tower[rht + 1] > 0 then
                break
            end
            rht = rht - 1
        end
        if rht < 0 then
            break
        end

        local bof = 0
        local col = 0
        while col <= rht do
            if tower[col + 1] > 0 then
                tower[col + 1] = tower[col + 1] - 1
                bof = bof + 1
            elseif bof > 0 then
                wu = wu + 1
            end
            col = col + 1
        end
        if bof < 2 then
            break
        end
    until false
    if wu == 0 then
        print(string.format("Block %d does not hold any water.", i))
    else
        print(string.format("Block %d holds %d water units.", i, wu))
    end
end

function main()
    local towers = {
        {1, 5, 3, 7, 2},
        {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},
        {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},
        {5, 5, 5, 5},
        {5, 6, 7, 8},
        {8, 7, 7, 6},
        {6, 7, 10, 7, 6}
    }

    for i,tbl in pairs(towers) do
        waterCollected(i,tbl)
    end
end

main()


edges = {1 \[DirectedEdge] 2, 1 \[DirectedEdge] 3, 2 \[DirectedEdge] 4, 2 \[DirectedEdge] 5,
              3 \[DirectedEdge] 6, 4 \[DirectedEdge] 7};
t = TreeGraph[edges, GraphStyle -> "VintageDiagram"]


load(graphs)$

g: random_tree(10)$

is_tree(g);
true

draw_graph(g)$


import strutils

type
  Node[T] = ref object
    data: T
    left, right: Node[T]

proc n[T](data: T; left, right: Node[T] = nil): Node[T] =
  Node[T](data: data, left: left, right: right)

proc indent[T](n: Node[T]): seq[string] =
  if n == nil: return @["-- (null)"]

  result = @["--" & $n.data]

  for a in indent n.left: result.add "  |" & a

  let r = indent n.right
  result.add "  `" & r[0]
  for a in r[1..r.high]: result.add "   " & a

let tree = 1.n(2.n(4.n(7.n),5.n),3.n(6.n(8.n,9.n)))

echo tree.indent.join("\n")


USING: kernel random sequences assocs locals sorting prettyprint
  math math.functions math.statistics math.vectors math.ranges ;
IN: rosetta-code.dice7

! Output a random integer 1..5.
: dice5 ( -- x )
   5 [1,b] random
;

! Output a random integer 1..7 using dice5 as randomness source.
: dice7 ( -- x )
   0 [ dup 21 < ] [ drop dice5 5 * dice5 + 6 - ] do until
   7 rem 1 +
;

! Roll the die by calling the quotation the given number of times and return
! an array with roll results.
! Sample call: 1000 [ dice7 ] roll
: roll ( times quot: ( -- x ) -- array )
   [ call( --  x ) ] curry replicate
;

! Input array contains outcomes of a number of die throws. Each die result is
! an integer in the range 1..X. Calculate and return the number of each
! of the results in the array so that in the first position of the result
! there is the number of ones in the input array, in the second position
! of the result there is the number of twos in the input array, etc.
: count-dice-outcomes ( X array -- array )
    histogram
    swap [1,b] [ over [ 0 or ] change-at ] each
    sort-keys values
;

! Verify distribution uniformity/Naive. Delta is the acceptable deviation
! from the ideal number of items in each bucket, expressed as a fraction of
! the total count. Sides is the number of die sides. Die-func is a word that
! produces a random number on stack in the range [1..sides], times is the
! number of times to call it.
! Sample call: 0.02 7 [ dice7 ] 100000 verify
:: verify ( delta sides die-func: ( -- random ) times -- )
   sides
   times die-func roll
   count-dice-outcomes
   dup .
   times sides / :> ideal-count
   ideal-count v-n vabs
   times v/n
   delta [ < ] curry all?
   [ "Random enough" . ] [ "Not random enough" . ] if
;

! Call verify with 1, 10, 100, ... 1000000 rolls of 7-sided die.
: verify-all ( -- )
   { 1 10 100 1000 10000 100000 1000000 }
   [| times | 0.02 7 [ dice7 ] times verify ] each
;


: .bounds ( u1 u2 -- )  ." lower bound = " .  ."  upper bound = " 1- .  cr ;
: init-bins ( n -- addr )
   cells dup allocate throw  tuck swap erase ;
: expected ( u1 cnt -- u2 )  over 2/ + swap / ;
: calc-limits ( n cnt pct -- low high )
   >r  expected  r>  over 100 */ 2dup  + 1+ >r  -  r> ;
: make-histogram ( bins xt cnt -- )
   0 ?do 2dup  execute 1- cells  +  1 swap +!  loop  2drop ;
: valid-bin? ( addr n low high -- f )
   2>r  cells + @ dup .  2r> within ;

: check-distribution {: xt cnt n pct -- f :}
\ assumes xt generates numbers from 1 to n
   n init-bins  {: bins :}
   n cnt pct calc-limits  {: low high :}
   high low .bounds
   bins xt cnt make-histogram
   true  \ result flag
   n 0 ?do
      i 1+ . ." : "  bins i low high valid-bin?
      dup 0= if ." not " then ." ok" cr
      and
   loop
   bins free throw ;


subroutine distcheck(randgen, n, delta)

  interface
    function randgen
      integer :: randgen
    end function randgen
  end interface

  real, intent(in) :: delta
  integer, intent(in) :: n
  integer :: i, mval, lolim, hilim
  integer, allocatable :: buckets(:)
  integer, allocatable :: rnums(:)
  logical :: skewed = .false.

  allocate(rnums(n))

  do i = 1, n
    rnums(i) = randgen()
  end do

  mval = maxval(rnums)
  allocate(buckets(mval))
  buckets = 0

  do i = 1, n
    buckets(rnums(i)) = buckets(rnums(i)) + 1
  end do

  lolim = n/mval - n/mval*delta
  hilim = n/mval + n/mval*delta

  do i = 1, mval
    if(buckets(i) < lolim .or. buckets(i) > hilim) then
      write(*,"(a,i0,a,i0,a,i0)") "Distribution potentially skewed for bucket ", i, "   Expected: ", &
                                   n/mval, "   Actual: ", buckets(i)
      skewed = .true.
    end if
  end do

  if (.not. skewed) write(*,"(a)") "Distribution uniform"

  deallocate(rnums)
  deallocate(buckets)

end subroutine


Module Water {
      Flush ' empty stack
      Data (1, 5, 3, 7, 2)
      Data (5, 3, 7, 2, 6, 4, 5, 9, 1, 2)
      Data (2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1)
      Data (5, 5, 5, 5), (5, 6, 7, 8),(8, 7, 7, 6)
      Data (6, 7, 10, 7, 6)
      bars=stack.size  ' mark stack frame
      Dim bar()
      for bar=1 to bars
            bar()=Array  ' pop an array from stack
            acc=0
            For i=1 to len(bar())-2
                  level1=bar(i)
                  level2=level1
                  m=each(bar(), i+1, 1)
                  while m
                        if array(m)>level1 then level1=array(m)
                  End While
                  n=each(bar(), i+1, -1)
                  while n
                        if array(n)>level2 then level2=array(n)
                  End While
                  acc+=max.data(min(level1, level2)-bar(i), 0)
            Next i
            Data acc  ' push to end value
      Next bar
      finalwater=[]   ' is a stack object
      Print finalwater
}
Water


import math, sequtils, sugar

proc water(barChart: seq[int], isLeftPeak = false, isRightPeak = false): int =
  if len(barChart) <= 2:
    return
  if isLeftPeak and isRightPeak:
    return sum(barChart[1..^2].map(x=>min(barChart[0], barChart[^1])-x))
  var i: int
  if isLeftPeak:
    i = maxIndex(barChart[1..^1])+1
  else:
    i = maxIndex(barChart[0..^2])
  return water(barChart[0..i], isLeftPeak, true)+water(barChart[i..^1], true, isRightPeak)

const barCharts = [
    @[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]]
const waterUnits = barCharts.map(chart=>water(chart, false, false))
echo(waterUnits)


#!/usr/bin/perl
use warnings;
use strict;
use utf8;
use open OUT => ':utf8', ':std';

sub parse {
    my ($tree) = shift;
    if (my ($root, $children) = $tree =~ /^(.+?)\((.*)\)$/) {

        my $depth = 0;
        for my $pos (0 .. length($children) - 1) {
            my $char = \substr $children, $pos, 1;
            if (0 == $depth and ',' eq $$char) {
                $$char = "\x0";
            } elsif ('(' eq $$char) {
                $depth++;
            } elsif (')' eq $$char) {
                $depth--;
            }
        }
        return($root, [map parse($_), split /\x0/, $children]);

    } else { # Leaf.
        return $tree;
    }
}

sub output {
    my ($parsed, $prefix) = @_;
    my $is_root = not defined $prefix;
    $prefix //= ' ';
    while (my $member = shift @$parsed) {
        my $last = !@$parsed || (1 == @$parsed and ref $parsed->[0]);
        unless ($is_root) {
            substr $prefix, -3, 1, ' ';
            substr($prefix, -4, 1) =~ s/├/│/;
            substr $prefix, -2, 1, ref $member ? ' ' : '└' if $last;
        }

        if (ref $member) {
            output($member, $prefix . '├─');
        } else {
            print $prefix, $member, "\n";
        }
    }
}

my $tree = 'a(b0(c1,c2(d(ef,gh)),c3(i1,i2,i3(jj),i4(kk,m))),b1(C1,C2(D1(E),D2,D3),C3))';
my $parsed = [parse($tree)];
output($parsed);


Randomize Timer
Function dice5() As Integer
    Return Int(Rnd * 5) + 1
End Function

Function dice7() As Integer
    Dim As Integer temp
    Do
        temp = dice5() * 5 + dice5() -6
    Loop Until temp < 21
    Return (temp Mod 7) +1
End Function

Function distCheck(n As Ulongint, delta As Double) As Ulongint

    Dim As Ulongint a(n)
    Dim As Ulongint maxBucket = 0
    Dim As Ulongint minBucket = 1000000
    For i As Ulongint = 1 To n
        a(i) = dice5()
        If a(i) > maxBucket Then maxBucket = a(i)
        If a(i) < minBucket Then minBucket = a(i)
    Next i

    Dim As Ulongint nBuckets = maxBucket + 1
    Dim As Ulongint buckets(maxBucket)
    For i As Ulongint = 1 To n
        buckets(a(i)) += 1
    Next i
    'check buckets
    Dim As Ulongint expected = n / (maxBucket-minBucket+1)
    Dim As Ulongint minVal = Int(expected*(1-delta))
    Dim As Ulongint maxVal = Int(expected*(1+delta))
    expected = Int(expected)
    Print "minVal", "Expected", "maxVal"
    Print minVal, expected, maxVal
    Print "Bucket", "Counter", "pass/fail"
    distCheck = true
    For i As Ulongint = minBucket To maxBucket
        Print i, buckets(i), Iif((minVal > buckets(i)) Or (buckets(i) > maxVal),"fail","")
        If (minVal > buckets(i)) Or (buckets(i) > maxVal) Then Return false
    Next i
End Function

Dim Shared As Ulongint n = 1000
Print "Testing ";n;" times"
If Not(distCheck(n, 0.05)) Then Print "Test failed" Else Print "Test passed"
Print

n = 10000
Print "Testing ";n;" times"
If Not(distCheck(n, 0.05)) Then Print "Test failed" Else Print "Test passed"
Print

n = 50000
Print "Testing ";n;" times"
If Not(distCheck(n, 0.05)) Then Print "Test failed" Else Print "Test passed"
Print
Sleep


package main

import (
    "fmt"
    "math"
    "math/rand"
    "time"
)

// "given"
func dice5() int {
    return rand.Intn(5) + 1
}

// function specified by task "Seven-sided dice from five-sided dice"
func dice7() (i int) {
    for {
        i = 5*dice5() + dice5()
        if i < 27 {
            break
        }
    }
    return (i / 3) - 1
}

// function specified by task "Verify distribution uniformity/Naive"
//
// Parameter "f" is expected to return a random integer in the range 1..n.
// (Values out of range will cause an unceremonious crash.)
// "Max" is returned as an "indication of distribution achieved."
// It is the maximum delta observed from the count representing a perfectly
// uniform distribution.
// Also returned is a boolean, true if "max" is less than threshold
// parameter "delta."
func distCheck(f func() int, n int,
    repeats int, delta float64) (max float64, flatEnough bool) {
    count := make([]int, n)
    for i := 0; i < repeats; i++ {
        count[f()-1]++
    }
    expected := float64(repeats) / float64(n)
    for _, c := range count {
        max = math.Max(max, math.Abs(float64(c)-expected))
    }
    return max, max < delta
}

// Driver, produces output satisfying both tasks.
func main() {
    rand.Seed(time.Now().UnixNano())
    const calls = 1000000
    max, flatEnough := distCheck(dice7, 7, calls, 500)
    fmt.Println("Max delta:", max, "Flat enough:", flatEnough)
    max, flatEnough = distCheck(dice7, 7, calls, 500)
    fmt.Println("Max delta:", max, "Flat enough:", flatEnough)
}


--
-- demo\rosetta\VisualiseTree.exw
--
with javascript_semantics

-- To the theme tune of the Milk Tray Ad iyrt,
-- All because the Windows console hates utf8:
constant TL = '\#DA', -- aka '┌'
         VT = '\#B3', -- aka '│'
         BL = '\#C0', -- aka '└'
         HZ = '\#C4', -- aka '─'
         HS = "\#C4"  -- (string version of HZ)

function w1252_to_utf8(string s)
    if platform()!=WINDOWS then
        s = substitute_all(s,{ TL, VT, BL, HZ},
                             {"┌","│","└","─"})
    end if
    return s
end function
--</hates utf8>

procedure visualise_tree(object tree, string root=HS)
    if atom(tree) then
        puts(1,"<empty>\n")
    else
        object {v,l,r} = tree
        integer g = root[$]
        if sequence(l) then
            root[$] = iff(g=TL or g=HZ?' ':VT)
            visualise_tree(l,root&TL)
        end if
        root[$] = g
        printf(1,"%s%d\n",{w1252_to_utf8(root),v})
        if sequence(r) then
            root[$] = iff(g=TL?VT:' ')
            visualise_tree(r,root&BL)
        end if
    end if
end procedure

function rand_tree(integer low, integer high)
    for i=1 to 2 do
        integer v = rand(high-low+1)-1+low
        if v!=low
        and v!=high then
            return {v,rand_tree(low,v),rand_tree(v,high)}
        end if
    end for
    return 0
end function

object tree = rand_tree(0,20)   -- (can be 0, <1% chance)

visualise_tree(tree)
--pp(tree,{pp_Nest,10})
{} = wait_key()


import System.Random
import Data.List
import Control.Monad
import Control.Arrow

distribCheck :: IO Int -> Int -> Int -> IO [(Int,(Int,Bool))]
distribCheck f n d = do
  nrs <- replicateM n f
  let group  = takeWhile (not.null) $ unfoldr (Just. (partition =<< (==). head)) nrs
      avg    = (fromIntegral n) / fromIntegral (length group)
      ul     = round $ (100 + fromIntegral d)/100 * avg
      ll     = round $ (100 - fromIntegral d)/100 * avg
  return $ map (head &&& (id &&& liftM2 (&&) (>ll)(<ul)).length) group


(import [collections [Counter]])
(import [random [randint]])

(defn uniform? [f repeats delta]
; Call 'f' 'repeats' times, then check if the proportion of each
; value seen is within 'delta' of the reciprocal of the count
; of distinct values.
  (setv bins (Counter (list-comp (f) [i (range repeats)])))
  (setv target (/ 1 (len bins)))
  (all (list-comp
    (<= (- target delta) (/ n repeats) (+ target delta))
    [n (.values bins)])))


# rnd  : a co-expression, which will generate the random numbers
# n    : the number of numbers to test
# delta: tolerance in non-uniformity
# This procedure fails if after the sampling the difference
# in uniformity exceeds delta, a proportion of n / number-of-alternatives
procedure verify_uniform (rnd, n, delta)
  # generate a table counting the outcome of the generator
  results := table (0)
  every (1 to n) do results[@rnd] +:= 1
  # retrieve the statistics
  smallest := n
  largest := 0
  every num := key(results) do { # record result and limits
    write (num || " " || results[num])
    if results[num] < smallest then smallest := results[num]
    if results[num] > largest  then largest  := results[num]
  }
  # decide if difference is within bounds defined by delta
  return largest-smallest < delta * n / *results
end

procedure main ()
  gen_1 := create (|?10) # uniform integers, 1 to 10
  if verify_uniform (gen_1, 1000000, 0.01)
    then write ("uniform")
    else write ("skewed")
  gen_2 := create (|(if ?2 = 1 then 6 else ?10)) # skewed integers, 1 to 10
  if verify_uniform (gen_2, 1000000, 0.01)
    then write ("uniform")
    else write ("skewed")
end


with javascript_semantics
function collect_water(sequence heights)
    integer res = 0
    for i=2 to length(heights)-1 do
        integer lm = max(heights[1..i-1]),
                rm = max(heights[i+1..$]),
                d = min(lm,rm)-heights[i]
        res += max(0,d)
    end for
    return res
end function

constant tests = {{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 i=1 to length(tests) do
    sequence ti = tests[i]
    printf(1,"%35s : %d\n",{sprint(ti),collect_water(ti)})
end for


% direction may be horizontal/vertical/list
display_tree(Direction) :-
	sformat(A, 'Display tree ~w', [Direction]),
	new(D, window(A)),
	send(D, size, size(350,200)),
	new(T, tree(text('Root'))),
	send(T, neighbour_gap, 10),
	new(S1, node(text('Child1'))),
	new(S2, node(text('Child2'))),
	send_list(T, son,[S1,S2]),
	new(S11, node(text('Grandchild1'))),
	new(S12, node(text('Grandchild2'))),
	send_list(S1, son, [S11, S12]),
	new(S21, node(text('Grandchild3'))),
	new(S22, node(text('Grandchild4'))),
	send_list(S2, son, [S21, S22]),
	send(T, direction, Direction),
	send(D, display, T),
	send(D, open).


checkUniform=: adverb define
  0.05 u checkUniform y
  :
  n=. */y
  delta=. x
  sample=. u n              NB. the "u" refers to the verb to left of adverb
  freqtable=. /:~ (~. sample) ,. #/.~ sample
  expected=. n % # freqtable
  errmsg=. 'Distribution is potentially skewed'
  errmsg assert (delta * expected) > | expected - {:"1 freqtable
  freqtable
)


import static java.lang.Math.abs;
import java.util.*;
import java.util.function.IntSupplier;

public class Test {

    static void distCheck(IntSupplier f, int nRepeats, double delta) {
        Map<Integer, Integer> counts = new HashMap<>();

        for (int i = 0; i < nRepeats; i++)
            counts.compute(f.getAsInt(), (k, v) -> v == null ? 1 : v + 1);

        double target = nRepeats / (double) counts.size();
        int deltaCount = (int) (delta / 100.0 * target);

        counts.forEach((k, v) -> {
            if (abs(target - v) >= deltaCount)
                System.out.printf("distribution potentially skewed "
                        + "for '%s': '%d'%n", k, v);
        });

        counts.keySet().stream().sorted().forEach(k
                -> System.out.printf("%d %d%n", k, counts.get(k)));
    }

    public static void main(String[] a) {
        distCheck(() -> (int) (Math.random() * 5) + 1, 1_000_000, 1);
    }
}


function distcheck(random_func, times, opts) {
    if (opts === undefined) opts = {}
    opts['delta'] = opts['delta'] || 2;

    var count = {}, vals = [];
    for (var i = 0; i < times; i++) {
        var val = random_func();
        if (! has_property(count, val)) {
            count[val] = 1;
            vals.push(val);
        }
        else
            count[val] ++;
    }
    vals.sort(function(a,b) {return a-b});

    var target = times / vals.length;
    var tolerance = target * opts['delta'] / 100;

    for (var i = 0; i < vals.length; i++) {
        var val = vals[i];
        if (Math.abs(count[val] - target) > tolerance)
            throw "distribution potentially skewed for " + val +
                  ": expected result around " + target + ", got " +count[val];
        else
            print(val + "\t" + count[val]);
    }
}

function has_property(obj, propname) {
    return typeof(obj[propname]) == "undefined" ? false : true;
}

try {
    distcheck(function() {return Math.floor(10 * Math.random())}, 100000);
    print();
    distcheck(function() {return (Math.random() > 0.95 ? 1 : 0)}, 100000);
} catch (e) {
    print(e);
}


include ..\Utilitys.pmt

def collect_water
    0 var res
    len 1 - 2 swap 2 tolist
    for
        var i
        1 i 1 - slice max >ps
        len i - 1 + i swap slice max >ps
        i get ps> ps> min swap -
        0 max res + var res
    endfor
    drop
    res
enddef

( ( 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 ) )

len for
    get dup print " : " print collect_water ?
endfor


def water_collected(tower):
    N = len(tower)
    highest_left = [0] + [max(tower[:n]) for n in range(1,N)]
    highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]
    water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)
        for n in range(N)]
    print("highest_left:  ", highest_left)
    print("highest_right: ", highest_right)
    print("water_level:   ", water_level)
    print("tower_level:   ", tower)
    print("total_water:   ", sum(water_level))
    print("")
    return sum(water_level)

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

[water_collected(tower) for tower in towers]


Python 3.2.3 (default, May  3 2012, 15:54:42)
[GCC 4.6.3] on linux2
Type "copyright", "credits" or "license()" for more information.
>>> help('pprint.pprint')
Help on function pprint in pprint:

pprint.pprint = pprint(object, stream=None, indent=1, width=80, depth=None)
    Pretty-print a Python object to a stream [default is sys.stdout].

>>> from pprint import pprint
>>> for tree in [ (1, 2, 3, 4, 5, 6, 7, 8),
	          (1, (( 2, 3 ), (4, (5, ((6, 7), 8))))),
	          ((((1, 2), 3), 4), 5, 6, 7, 8) ]:
	print("\nTree %r can be pprint'd as:" % (tree, ))
	pprint(tree, indent=1, width=1)

Tree (1, 2, 3, 4, 5, 6, 7, 8) can be pprint'd as:
(1,
 2,
 3,
 4,
 5,
 6,
 7,
 8)

Tree (1, ((2, 3), (4, (5, ((6, 7), 8))))) can be pprint'd as:
(1,
 ((2,
   3),
  (4,
   (5,
    ((6,
      7),
     8)))))

Tree ((((1, 2), 3), 4), 5, 6, 7, 8) can be pprint'd as:
((((1,
    2),
   3),
  4),
 5,
 6,
 7,
 8)
>>>


using Printf

function distcheck(f::Function, rep::Int=10000, Δ::Int=3)
    smpl = f(rep)
    counts = Dict(k => count(smpl .== k) for k in unique(smpl))
    expected = rep / length(counts)
    lbound = expected * (1 - 0.01Δ)
    ubound = expected * (1 + 0.01Δ)
    noobs = count(x -> !(lbound ≤ x ≤ ubound), values(counts))
    if noobs > 0 warn(@sprintf "%2.4f%% values out of bounds" noobs / rep) end
    return counts
end

# Dice5 check
distcheck(x -> rand(1:5, x))
# Dice7 check
distcheck(dice7)


// version 1.1.3

import java.util.Random

val r = Random()

fun dice5() = 1 + r.nextInt(5)

fun checkDist(gen: () -> Int, nRepeats: Int, tolerance: Double = 0.5) {
    val occurs = mutableMapOf<Int, Int>()
    for (i in 1..nRepeats) {
        val d = gen()
        if (occurs.containsKey(d))
            occurs[d] = occurs[d]!! + 1
        else
            occurs.put(d, 1)
    }
    val expected = (nRepeats.toDouble()/ occurs.size).toInt()
    val maxError = (expected * tolerance / 100.0).toInt()
    println("Repetitions = $nRepeats, Expected = $expected")
    println("Tolerance = $tolerance%, Max Error = $maxError\n")
    println("Integer   Occurrences   Error  Acceptable")
    val f = "  %d        %5d      %5d     %s"
    var allAcceptable = true
    for ((k,v) in occurs.toSortedMap()) {
        val error = Math.abs(v - expected)
        val acceptable = if (error <= maxError) "Yes" else "No"
        if (acceptable == "No") allAcceptable = false
        println(f.format(k, v, error, acceptable))
    }
    println("\nAcceptable overall: ${if (allAcceptable) "Yes" else "No"}")
}

fun main(args: Array<String>) {
    checkDist(::dice5, 1_000_000)
    println()
    checkDist(::dice5, 100_000)
}


n=1000
print "Testing ";n;" times"
if  not(check(n, 0.05)) then print "Test failed" else print "Test passed"
print

n=10000
print "Testing ";n;" times"
if  not(check(n, 0.05)) then print "Test failed" else print "Test passed"
print

n=50000
print "Testing ";n;" times"
if  not(check(n, 0.05)) then print "Test failed" else print "Test passed"
print

end

function check(n, delta)
    'fill randoms
    dim a(n)
    maxBucket=0
    minBucket=1e10
    for i = 1 to n
        a(i) = GENERATOR()
        if a(i)>maxBucket then maxBucket=a(i)
        if a(i)<minBucket then minBucket=a(i)
    next
    'fill buckets
    nBuckets = maxBucket+1 'from 0
    dim buckets(maxBucket)
    for i = 1 to n
        buckets(a(i)) =  buckets(a(i))+1
    next
    'check buckets
    expected=n/(maxBucket-minBucket+1)
    minVal=int(expected*(1-delta))
    maxVal=int(expected*(1+delta))
    expected=int(expected)
    print "minVal", "Expected", "maxVal"
    print minVal, expected, maxVal
    print "Bucket", "Counter", "pass/fail"
    check = 1
    for i = minBucket to maxBucket
        print i, buckets(i), _
            iif$((minVal > buckets(i)) OR (buckets(i) > maxVal) ,"fail","")
        if (minVal > buckets(i)) OR (buckets(i) > maxVal) then check = 0
    next
end function

function iif$(test, valYes$, valNo$)
    iif$ =  valNo$
    if test then iif$ =  valYes$
end function

function GENERATOR()
    'GENERATOR = int(rnd(0)*10) '0..9
    GENERATOR = 1+int(rnd(0)*5) '1..5: dice5
end function


#lang racket/base
(require racket/match)

(define (water-collected-between-towers towers)
  (define (build-tallest-left/rev-list t mx/l rv)
    (match t
      [(list) rv]
      [(cons a d)
       (define new-mx/l (max a mx/l))
       (build-tallest-left/rev-list d new-mx/l (cons mx/l rv))]))

  (define (collect-from-right t tallest/l mx/r rv)
    (match t
      [(list) rv]
      [(cons a d)
       (define new-mx/r (max a mx/r))
       (define new-rv (+ rv (max (- (min new-mx/r (car tallest/l)) a) 0)))
       (collect-from-right d (cdr tallest/l) new-mx/r new-rv)]))

  (define reversed-left-list (build-tallest-left/rev-list towers 0 null))
  (collect-from-right (reverse towers) reversed-left-list 0 0))

(module+ test
  (require rackunit)
  (check-equal?
   (let ((towerss
          '[[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]]))
     (map water-collected-between-towers towerss))
   (list 2 14 35 0 0 0 0)))


#lang racket/base

(define (visualize t0)
  (let loop ([t t0] [last? #t] [indent '()])
    (define (I mid last) (cond [(eq? t t0) ""] [last? mid] [else last]))
    (for-each display (reverse indent))
    (unless (eq? t t0) (printf "|\n"))
    (for-each display (reverse indent))
    (printf "~a~a\n" (I "\\-" "+-") (car t))
    (for ([s (cdr t)] [n (in-range (- (length t) 2) -1 -1)])
      (loop s (zero? n) (cons (I "  " "| ") indent)))))

(visualize '(1 (2 (3 (4) (5) (6 (7))) (8 (9)) (10)) (11 (12) (13))))


sub visualize-tree($tree, &label, &children,
                   :$indent = '',
                   :@mid = ('├─', '│ '),
                   :@end = ('└─', '  '),
) {
    sub visit($node, *@pre) {
        | gather {
            take @pre[0] ~ label($node);
            my @children := children($node);
            my $end = @children.end;
            for @children.kv -> $_, $child {
                when $end { take visit($child, (@pre[1] X~ @end)) }
                default   { take visit($child, (@pre[1] X~ @mid)) }
            }
        }
    }
    visit($tree, $indent xx 2);
}

# example tree built up of pairs
my $tree = root=>[a=>[a1=>[a11=>[]]],b=>[b1=>[b11=>[]],b2=>[],b3=>[]]];

.map({.join("\n")}).join("\n").say for visualize-tree($tree, *.key, *.value.list);


SetAttributes[CheckDistribution, HoldFirst]
CheckDistribution[function_,number_,delta_] :=(Print["Expected: ", N[number/7], ", Generated :",
Transpose[Tally[Table[function, {number}]]][[2]] // Sort];  If[(Max[#]-Min[#])&
 [Transpose[Tally[Table[function, {number}]]][[2]]] < delta*number/700, "Flat", "Skewed"])


import tables

proc checkDist(f: proc(): int; repeat: Positive; tolerance: float) =

  var counts: CountTable[int]
  for _ in 1..repeat:
    counts.inc f()

  let expected = (repeat / counts.len).toInt    # Rounded to nearest.
  let allowedDelta = (expected.toFloat * tolerance / 100).toInt
  var maxDelta = 0
  for val, count in counts.pairs:
    let d = abs(count - expected)
    if d > maxDelta: maxDelta = d

  let status = if maxDelta <= allowedDelta: "passed" else: "failed"
  echo "Checking ", repeat, " values with a tolerance of ", tolerance, "%."
  echo "Random generator ", status, " the uniformity test."
  echo "Max delta encountered = ", maxDelta, "   Allowed delta = ", allowedDelta

when isMainModule:
  import random
  randomize()
  proc rand5(): int = rand(1..5)
  checkDist(rand5, 1_000_000, 0.5)


let distcheck fn n ?(delta=1.0) () =
  let h = Hashtbl.create 5 in
  for i = 1 to n do
    let v = fn() in
    let n =
      try Hashtbl.find h v
      with Not_found -> 0
    in
    Hashtbl.replace h v (n+1)
  done;
  Hashtbl.iter (fun v n -> Printf.printf "%d => %d\n%!" v n) h;
  let target = (float n) /. float (Hashtbl.length h) in
  Hashtbl.iter (fun key value ->
    if abs_float(float value -. target) > 0.01 *. delta *. (float n)
    then (Printf.eprintf
      "distribution potentially skewed for '%d': expected around %f, got %d\n%!"
       key target value)
  ) h;
;;


dice5()=random(5)+1;

dice7()={
  my(t);
  while((t=dice5()*5+dice5()) > 26,);
  t\3-1
};

cumChi2(chi2,dof)={
	my(g=gamma(dof/2));
	incgam(dof/2,chi2/2,g)/g
};

test(f,n,alpha=.05)={
	v=vector(n,i,f());
	my(s,ave,dof,chi2,p);
	s=sum(i=1,n,v[i],0.);
	ave=s/n;
	dof=n-1;
	chi2=sum(i=1,n,(v[i]-ave)^2)/ave;
	p=cumChi2(chi2,dof);
	if(p<alpha,
		error("Not flat enough, significance only "p)
	,
		print("Flat with significance "p);
	)
};

test(dice7, 10^5)
test(()->if(random(1000),random(1000),1), 10^5)


/* REXX */
Call bars '1 5 3 7 2'
Call bars '5 3 7 2 6 4 5 9 1 2'
Call bars '2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1'
Call bars '5 5 5 5'
Call bars '5 6 7 8'
Call bars '8 7 7 6'
Call bars '6 7 10 7 6'
Exit
bars:
Parse Arg bars
bar.0=words(bars)
high=0
box.=' '
Do i=1 To words(bars)
  bar.i=word(bars,i)
  high=max(high,bar.i)
  Do j=1 To bar.i
    box.i.j='x'
    End
  End
m=1
w=0
Do Forever
  Do i=m+1 To bar.0
    If bar.i>bar.m Then
      Leave
    End
  If i>bar.0 Then Leave
  n=i
  Do i=m+1 To n-1
    w=w+bar.m-bar.i
    Do j=bar.i+1 To bar.m
      box.i.j='*'
      End
    End
  m=n
  End
m=bar.0
Do Forever
  Do i=bar.0 To 1 By -1
    If bar.i>bar.m Then
      Leave
    End
  If i<1 Then Leave
  n=i
  Do i=m-1 To n+1 By -1
    w=w+bar.m-bar.i
    Do j=bar.i+1 To bar.m
      box.i.j='*'
      End
    End
  m=n
  End
Say bars '->' w
Call show
Return
show:
Do j=high To 1 By -1
  ol=''
  Do i=1 To bar.0
    ol=ol box.i.j
    End
  Say ol
  End
Return


sub roll7 { 1+int rand(7) }
sub roll5 { 1+int rand(5) }
sub roll7_5 {
  while(1) {
    my $d7 = (5*&roll5 + &roll5 - 6) % 8;
    return $d7 if $d7;
  }
}

my $threshold = 5;

print dist( $_, $threshold,  \&roll7   ) for <1001 1000006>;
print dist( $_, $threshold,  \&roll7_5 ) for <1001 1000006>;

sub dist {
my($n, $threshold, $producer) = @_;
    my @dist;
    my $result;
    my $expect = $n / 7;
    $result .= sprintf "%10d expected\n", $expect;

    for (1..$n) { @dist[&$producer]++; }

    for my $i (1..7) {
        my $v = @dist[$i];
        my $pct = ($v - $expect)/$expect*100;
        $result .= sprintf "%d %8d %6.1f%%%s\n", $i, $v, $pct, (abs($pct) > $threshold ? ' - skewed' : '');
    }
    return $result . "\n";
}


with javascript_semantics
function check(integer fid, range, iterations, atom delta)
--
-- fid: routine_id of function that yields integer 1..range
-- range: the maximum value that is returned from fid
-- iterations: number of iterations to test
-- delta: variance, for example 0.005 means 0.5%
--
-- returns -1/0/1 for impossible/not flat/flat.
--
    atom av = iterations/range  -- average/expected value

    if floor(av)<av-delta*av
    or ceil(av)>av+delta*av then
        return -1   -- impossible
    end if
    sequence counts = repeat(0,range)
    for i=1 to iterations do
        integer cdx = fid()
        counts[cdx] += 1
    end for
    atom max_delta = max(sq_abs(sq_sub(counts,av)))
    return max_delta<delta*av
end function

function rand7()
  return rand(7)
end function

constant flats = {"impossible","not flat","flat"}
for p=2 to 7 do
    integer n = power(10,p)
--  n = n+7-remainder(n,7)
    integer flat = check(rand7, 7, n, 0.005)
    printf(1,"%d iterations: %s\n",{n,flats[flat+2]})
end for


def a(array)
n=array.length
left={}
right={}
left[0]=array[0]
i=1
loop do
   break if i >=n
left[i]=[left[i-1],array[i]].max
   i += 1
end
right[n-1]=array[n-1]
i=n-2
loop do
break if i<0
 right[i]=[right[i+1],array[i]].max
i-=1
end
i=0
water=0
loop do
break if i>=n
water+=[left[i],right[i]].min-array[i]
i+=1
end
puts water
end

a([ 5, 3,  7, 2, 6, 4, 5, 9, 1, 2 ])
a([ 2, 6,  3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 ])
a([ 5, 5,  5, 5 ])
a([ 5, 6,  7, 8 ])
a([ 8, 7,  7, 6 ])
a([ 6, 7, 10, 7, 6 ])
return


extern crate rustc_serialize;
extern crate term_painter;

use rustc_serialize::json;
use std::fmt::{Debug, Display, Formatter, Result};
use term_painter::ToStyle;
use term_painter::Color::*;

type NodePtr = Option<usize>;

#[derive(Debug, PartialEq, Clone, Copy)]
enum Side {
    Left,
    Right,
    Up,
}

#[derive(Debug, PartialEq, Clone, Copy)]
enum DisplayElement {
    TrunkSpace,
    SpaceLeft,
    SpaceRight,
    SpaceSpace,
    Root,
}

impl DisplayElement {
    fn string(&self) -> String {
        match *self {
            DisplayElement::TrunkSpace => "    │   ".to_string(),
            DisplayElement::SpaceRight => "    ┌───".to_string(),
            DisplayElement::SpaceLeft => "    └───".to_string(),
            DisplayElement::SpaceSpace => "        ".to_string(),
            DisplayElement::Root => "├──".to_string(),
        }
    }
}

#[derive(Debug, Clone, Copy, RustcDecodable, RustcEncodable)]
struct Node<K, V> {
    key: K,
    value: V,
    left: NodePtr,
    right: NodePtr,
    up: NodePtr,
}

impl<K: Ord + Copy, V: Copy> Node<K, V> {
    pub fn get_ptr(&self, side: Side) -> NodePtr {
        match side {
            Side::Up => self.up,
            Side::Left => self.left,
            _ => self.right,
        }
    }
}

#[derive(Debug, RustcDecodable, RustcEncodable)]
struct Tree<K, V> {
    root: NodePtr,
    store: Vec<Node<K, V>>,
}

impl<K: Ord + Copy + Debug + Display, V: Debug + Copy + Display> Tree<K, V> {
    pub fn get_node(&self, np: NodePtr) -> Node<K, V> {
        assert!(np.is_some());
        self.store[np.unwrap()]
    }

    pub fn get_pointer(&self, np: NodePtr, side: Side) -> NodePtr {
        assert!(np.is_some());
        self.store[np.unwrap()].get_ptr(side)
    }

    // Prints the tree with root p.  The idea is to do an in-order traversal
    // (reverse in-order in this case, where right is on top), and print nodes as they
    // are visited, one per line. Each invocation of display() gets its own copy
    // of the display element vector e, which is grown with either whitespace or
    // a trunk element, then modified in its last and possibly second-to-last
    // characters in context.
    fn display(&self, p: NodePtr, side: Side, e: &Vec<DisplayElement>, f: &mut Formatter) {
        if p.is_none() {
            return;
        }

        let mut elems = e.clone();
        let node = self.get_node(p);
        let mut tail = DisplayElement::SpaceSpace;
        if node.up != self.root {
            // If the direction is switching, I need the trunk element to appear in the lines
            // printed before that node is visited.
            if side == Side::Left && node.right.is_some() {
                elems.push(DisplayElement::TrunkSpace);
            } else {
                elems.push(DisplayElement::SpaceSpace);
            }
        }
        let hindex = elems.len() - 1;
        self.display(node.right, Side::Right, &elems, f);

        if p == self.root {
            elems[hindex] = DisplayElement::Root;
            tail = DisplayElement::TrunkSpace;
        } else if side == Side::Right {
            // Right subtree finished
            elems[hindex] = DisplayElement::SpaceRight;
            // Prepare trunk element in case there is a left subtree
            tail = DisplayElement::TrunkSpace;
        } else if side == Side::Left {
            elems[hindex] = DisplayElement::SpaceLeft;
            let parent = self.get_node(node.up);
            if parent.up.is_some() && self.get_pointer(parent.up, Side::Right) == node.up {
                // Direction switched, need trunk element starting with this node/line
                elems[hindex - 1] = DisplayElement::TrunkSpace;
            }
        }

        // Visit node => print accumulated elements. Each node gets a line and each line gets a
        // node.
        for e in elems.clone() {
            let _ = write!(f, "{}", e.string());
        }
        let _ = write!(f,
                       "{key:>width$} ",
                       key = Green.bold().paint(node.key),
                       width = 2);
        let _ = write!(f,
                       "{value:>width$}\n",
                       value = Blue.bold().paint(format!("{:.*}", 2, node.value)),
                       width = 4);

        // Overwrite last element before continuing traversal
        elems[hindex] = tail;

        self.display(node.left, Side::Left, &elems, f);
    }
}

impl<K: Ord + Copy + Debug + Display, V: Debug + Copy + Display> Display for Tree<K, V> {
    fn fmt(&self, f: &mut Formatter) -> Result {
        if self.root.is_none() {
            write!(f, "[empty]")
        } else {
            let mut v: Vec<DisplayElement> = Vec::new();
            self.display(self.root, Side::Up, &mut v, f);
            Ok(())
        }
    }
}

/// Decodes and prints a previously generated tree.
fn main() {
    let encoded = r#"{"root":0,"store":[{"key":0,"value":0.45,"left":1,"right":3,
        "up":null},{"key":-8,"value":-0.94,"left":7,"right":2,"up":0}, {"key":-1,
        "value":0.15,"left":8,"right":null,"up":1},{"key":7, "value":-0.29,"left":4,
        "right":9,"up":0},{"key":5,"value":0.80,"left":5,"right":null,"up":3},
        {"key":4,"value":-0.85,"left":6,"right":null,"up":4},{"key":3,"value":-0.46,
        "left":null,"right":null,"up":5},{"key":-10,"value":-0.85,"left":null,
        "right":13,"up":1},{"key":-6,"value":-0.42,"left":null,"right":10,"up":2},
        {"key":9,"value":0.63,"left":12,"right":null,"up":3},{"key":-3,"value":-0.83,
        "left":null,"right":11,"up":8},{"key":-2,"value":0.75,"left":null,"right":null,
        "up":10},{"key":8,"value":-0.48,"left":null,"right":null,"up":9},{"key":-9,
        "value":0.53,"left":null,"right":null,"up":7}]}"#;
    let tree: Tree<i32, f32> = json::decode(&encoded).unwrap();
    println!("{}", tree);
}


func visualize_tree(tree, label, children,
                    indent = '',
                    mids = ['├─', '│ '],
                    ends = ['└─', '  '],
) {
    func visit(node, pre) {
        gather {
            take(pre[0] + label(node))
            var chldn = children(node)
            var end = chldn.end
            chldn.each_kv { |i, child|
                if (i == end) { take(visit(child, [pre[1]] ~X+ ends)) }
                else          { take(visit(child, [pre[1]] ~X+ mids)) }
            }
        }
    }
    visit(tree, [indent] * 2)
}

var tree = 'root':['a':['a1':['a11':[]]],'b':['b1':['b11':[]],'b2':[],'b3':[]]]
say visualize_tree(tree, { .first }, { .second }).flatten.join("\n")


(de checkDistribution (Cnt Pm . Prg)
   (let Res NIL
      (do Cnt (accu 'Res (run Prg 1) 1))
      (let
         (N (/ Cnt (length Res))
            Min (*/ N (- 1000 Pm) 1000)
            Max (*/ N (+ 1000 Pm) 1000) )
         (for R Res
            (prinl (cdr R) " " (if (>= Max (cdr R) Min) "Good" "Bad")) ) ) ) )


Prototype RandNum_prt()

Procedure.s distcheck(*function.RandNum_prt, repetitions, delta.d)
  Protected text.s, maxIndex = 0
  Dim bucket(maxIndex) ;array will be resized as needed

  For i = 1 To repetitions ;populate buckets
    v = *function()
    If v > maxIndex
      maxIndex = v
      Redim bucket(maxIndex)
    EndIf
    bucket(v) + 1
  Next

  lbnd = Round((repetitions / maxIndex) * (100 - delta) / 100, #PB_Round_Up)
  ubnd = Round((repetitions / maxIndex) * (100 + delta) / 100, #PB_Round_Down)
  text = "Distribution check:" + #crlf$ + #crlf$
  text + "Total elements = " + Str(repetitions) + #crlf$ + #crlf$
  text + "Margin = " + StrF(delta, 2) + "% --> Lbound = " + Str(lbnd) + ", Ubound = " + Str(ubnd) + #crlf$

  For i = 1 To maxIndex
    If bucket(i) < lbnd Or bucket(i) > ubnd
      text + #crlf$ + "Bucket " + Str(i) + " contains " + Str(bucket(i)) + " elements.  Skewed."
    EndIf
  Next
  ProcedureReturn text
EndProcedure

MessageRequester("Results", distcheck(@dice7(), 1000000, 0.20))


from collections import Counter
from pprint import pprint as pp

def distcheck(fn, repeats, delta):
    '''\
    Bin the answers to fn() and check bin counts are within +/- delta %
    of repeats/bincount'''
    bin = Counter(fn() for i in range(repeats))
    target = repeats // len(bin)
    deltacount = int(delta / 100. * target)
    assert all( abs(target - count) < deltacount
                for count in bin.values() ), "Bin distribution skewed from %i +/- %i: %s" % (
                    target, deltacount, [ (key, target - count)
                                          for key, count in sorted(bin.items()) ]
                    )
    pp(dict(bin))


use std::cmp::min;

fn getfill(pattern: &[usize]) -> usize {
    let mut total = 0;
    for (idx, val) in pattern.iter().enumerate() {
        let l_peak = pattern[..idx].iter().max();
        let r_peak = pattern[idx + 1..].iter().max();
        if l_peak.is_some() && r_peak.is_some() {
            let peak = min(l_peak.unwrap(), r_peak.unwrap());
            if peak > val {
                total += peak - val;
            }
        }
    }
    total
}

fn main() {
    let patterns = vec![
        vec![1, 5, 3, 7, 2],
        vec![5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
        vec![2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
        vec![5, 5, 5, 5],
        vec![5, 6, 7, 8],
        vec![8, 7, 7, 6],
        vec![6, 7, 10, 7, 6],
    ];

    for pattern in patterns {
        println!("pattern: {:?}, fill: {}", &pattern, getfill(&pattern));
    }
}


import scala.collection.parallel.CollectionConverters.VectorIsParallelizable

// Program to find maximum amount of water
// that can be trapped within given set of bars.
object TrappedWater extends App {
  private val barLines = List(
    Vector(1, 5, 3, 7, 2),
    Vector(5, 3, 7, 2, 6, 4, 5, 9, 1, 2),
    Vector(2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1),
    Vector(5, 5, 5, 5),
    Vector(5, 6, 7, 8),
    Vector(8, 7, 7, 6),
    Vector(6, 7, 10, 7, 6)).zipWithIndex

  // Method for maximum amount of water
  private def sqBoxWater(barHeights: Vector[Int]): Int = {
    def maxOfLeft = barHeights.par.scanLeft(0)(math.max).tail
    def maxOfRight = barHeights.par.scanRight(0)(math.max).init

    def waterlevels = maxOfLeft.zip(maxOfRight)
      .map { case (maxL, maxR) => math.min(maxL, maxR) }

    waterlevels.zip(barHeights).map { case (level, towerHeight) => level - towerHeight }.sum
  }

  barLines.foreach(barSet =>
    println(s"Block ${barSet._2 + 1} could hold max. ${sqBoxWater(barSet._1)} units."))

}


package require struct::tree

proc visualize_tree {tree {nameattr name}} {
    set path {}
    $tree walk [$tree rootname] -order both {mode node} {
	if {$mode eq "enter"} {
	    set s ""
	    foreach p $path {
		append s [expr {[$tree next $p] eq "" ? "  " : "\u2502 "}]
	    }
	    lappend path $node
	    append s [expr {
		[$tree next $node] eq "" ? "\u2514\u2500" : "\u251c\u2500"
	    }]
	    if {[$tree keyexists $node $nameattr]} {
		set name [$tree get $node $nameattr]
	    } else {
		# No node name attribute; use the raw name
		set name $node
	    }
	    puts "$s$name"
	} else {
	    set path [lrange $path 0 end-1]
	}
    }
}


import "/dynamic" for Struct
import "random" for Random

var Stem = Struct.create("Stem", ["str", "next"])

var SDOWN = "  |"
var SLAST = "  `"
var SNONE = "   "

var rand = Random.new()

var tree // recursive
tree = Fn.new { |root, head|
    var col = Stem.new(null, null)
    var tail = head
    while (tail) {
        System.write(tail.str)
        if (!tail.next) break
        tail = tail.next
    }
    System.print("--%(root)")
    if (root <= 1) return
    if (tail && tail.str == SLAST) tail.str = SNONE
    if (!tail) {
        tail = head = col
    } else {
        tail.next = col
    }
    while (root != 0) { // make a tree by doing something random
        var r = 1 + rand.int(root)
        root = root - r
        col.str = (root != 0) ? SDOWN : SLAST
        tree.call(r, head)
    }
    tail.next = null
}

var n = 8
tree.call(n, null)


  [ stack [ 0 0 0 0 0 0 0 ] ]   is bins         (       --> s )

  [ 7 times
      [ 0 bins take
        i poke
        bins put ] ]            is emptybins    (       -->   )

  [ bins share over peek
    1+ bins take rot poke
    bins put ]                  is bincrement   (     n -->   )

  [ emptybins
    over 7 / temp put
    swap times
      [ over do 1 -
        bincrement ]
    bins share dup echo cr
    witheach
      [ temp share - abs
        over > if
          [ say "Number of "
            i^ 1+ echo
            say "s is sketchy."
            cr ] ]
    2drop temp release ]        is distribution ( x n n -->   )


distcheck <- function(fn, repetitions=1e4, delta=3)
{
   if(is.character(fn))
   {
      fn <- get(fn)
   }
   if(!is.function(fn))
   {
      stop("fn is not a function")
   }
   samp <- fn(n=repetitions)
   counts <- table(samp)
   expected <- repetitions/length(counts)
   lbound <- expected * (1 - 0.01*delta)
   ubound <- expected * (1 + 0.01*delta)
   status <- ifelse(counts < lbound, "under",
      ifelse(counts > ubound, "over", "okay"))
   data.frame(value=names(counts), counts=as.vector(counts), status=status)
}
distcheck(dice7.vec)


#lang racket
(define (pretty-fraction f)
  (if (integer? f) f
      (let* ((d (denominator f)) (n (numerator f)) (q (quotient n d)) (r (remainder n d)))
        (format "~a ~a" q (/ r d)))))

(define (test-uniformity/naive r n δ)
  (define observation (make-hash))
  (for ((_ (in-range n))) (hash-update! observation (r) add1 0))
  (define target (/ n (hash-count observation)))
  (define max-skew (* n δ 1/100))
  (define (skewed? v)
    (> (abs (- v target)) max-skew))
  (let/ec ek
    (cons
     #t
     (for/list ((k (sort (hash-keys observation) <)))
       (define v (hash-ref observation k))
       (when (skewed? v)
         (ek (cons
              #f
              (format "~a distribution of ~s potentially skewed for ~a. expected ~a got ~a"
                      'test-uniformity/naive r k (pretty-fraction target) v))))
       (cons k v)))))

(define (straight-die)
  (min 6 (add1 (random 6))))

(define (crooked-die)
  (min 6 (add1 (random 7))))

; Test whether the builtin generator is uniform:
(test-uniformity/naive (curry random 10) 1000 5)
; Test whether a straight die is uniform:
(test-uniformity/naive straight-die 1000 5)
; Test whether a biased die fails:
(test-uniformity/naive crooked-die 1000 5)


my $d7 = 1..7;
sub roll7 { $d7.roll };

my $threshold = 3;

for 14, 105, 1001, 10003, 100002, 1000006 ->  $n
  { dist( $n, $threshold,  &roll7 ) };

sub dist ( $n is copy, $threshold, &producer ) {
    my @dist;
    my $expect = $n / 7;
    say "Expect\t",$expect.fmt("%.3f");

    loop ($_ = $n; $n; --$n) { @dist[&producer()]++; }

    for @dist.kv -> $i, $v is copy {
        next unless $i;
        $v //= 0;
        my $pct = ($v - $expect)/$expect*100;
        printf "%d\t%d\t%+.2f%% %s\n", $i, $v, $pct,
          ($pct.abs > $threshold ?? '- skewed' !! '');
    }
    say '';
}


(import (scheme base)
        (scheme write))

(define (total-collected chart)
  (define (highest-left vals curr)
    (if (null? vals)
      (list curr)
      (cons curr
            (highest-left (cdr vals) (max (car vals) curr)))))
  (define (highest-right vals curr)
    (reverse (highest-left (reverse vals) curr)))
  ;
  (if (< (length chart) 3) ; catch the end cases
    0
    (apply +
           (map (lambda (l c r)
                  (if (or (<= l c)
                          (<= r c))
                    0
                    (- (min l r) c)))
                (highest-left chart 0)
                chart
                (highest-right chart 0)))))

(for-each
  (lambda (chart)
    (display chart) (display " -> ") (display (total-collected chart)) (newline))
  '((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)))


clear screen

dim colore$(1)

maxCol = token("white yellow cyan green red", colore$())

showTree(0, "[1[2[3][4[5][6]][7]][8[9]]]")
print "\n\n\n"
showTree(0, "[1[2[3[4]]][5[6][7[8][9]]]]")

sub showTree(n, A$)
    local i, c$
    static co

    c$ = left$(A$, 1)

    if c$ = "" return

    switch c$
    case "[":   co = co + 1 : showTree(n + 1, right$(A$, len(A$) - 1))
                break
    case "]":   co = co - 1 : showTree(n - 1, right$(A$, len(A$) - 1))
                break
    default:    for i = 2 to n
                    print "  ";
                next i
                co = max(min(co, maxCol), 1)
                print color(colore$(co)) "\xc0-", c$
                showTree(n, right$(A$, len(A$) - 1))
                break
    end switch
end sub


:Vault.dir()
...
Compiler
   Asm
   Compiler
Dictionary
Exception
Test
   UnitTester
   foo
      bar
...