How to resolve the algorithm Water collected between towers step by step in the zkl programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Water collected between towers step by step in the zkl programming language
Table of Contents
Problem Statement
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, completely filling all convex enclosures in the chart with water.
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water. Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart. Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
See, also:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Water collected between towers step by step in the zkl programming language
Source code in the zkl programming language
fcn waterCollected(walls){
// compile max wall heights from left to right and right to left
// then each pair is left/right wall of that cell.
// Then the min of each wall pair == water height for that cell
scanl(walls,(0).max) // scan to right, f is max(0,a,b)
.zipWith((0).MAX.min, // f is MAX.min(a,b) == min(a,b)
scanl(walls.reverse(),(0).max).reverse()) // right to left
// now subtract the wall height from the water level and add 'em up
.zipWith('-,walls).filter('>(0)).sum(0);
}
fcn scanl(xs,f,i=0){ // aka reduce but save list of results
xs.reduce('wrap(s,x,a){ s=f(s,x); a.append(s); s },i,ss:=List());
ss
} // scanl((1,5,3,7,2),max,0) --> (1,5,5,7,7)
T( T(1, 5, 3, 7, 2), T(5, 3, 7, 2, 6, 4, 5, 9, 1, 2),
T(2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1),
T(5, 5, 5, 5), T(5, 6, 7, 8),T(8, 7, 7, 6),
T(6, 7, 10, 7, 6) )
.pump(List, waterCollected).println();
You may also check:How to resolve the algorithm Primality by trial division step by step in the Cowgol programming language
You may also check:How to resolve the algorithm Set puzzle step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Doubly-linked list/Element definition step by step in the Delphi programming language
You may also check:How to resolve the algorithm Sort three variables step by step in the Fortran programming language
You may also check:How to resolve the algorithm Miller–Rabin primality test step by step in the Sidef programming language