Water collected between towers: Difference between revisions

uBasic/4tH - eliminated a global
m (→‎{{header|BASIC}}: Refine implementation: GW-BASIC.)
imported>Thebeez
(uBasic/4tH - eliminated a global)
 
(11 intermediate revisions by 7 users not shown)
Line 864:
 
=={{header|BASIC}}==
==={{header|FreeBASIC}}===
Uses Nigel Galloway's very elegant idea, expressed verbosely so you can really see what's going on.
<syntaxhighlight lang="freebasic">type tower
hght as uinteger
posi as uinteger
end type
 
sub shellsort( a() as tower )
'quick and dirty shellsort, not the focus of this exercise
dim as uinteger gap = ubound(a), i, j, n=ubound(a)
dim as tower temp
do
gap = int(gap / 2.2)
if gap=0 then gap=1
for i=gap to n
temp = a(i)
j=i
while j>=gap andalso a(j-gap).hght < temp.hght
a(j) = a(j - gap)
j -= gap
wend
a(j) = temp
next i
loop until gap = 1
end sub
 
'heights of towers in each city prefixed by the number of towers
data 5, 1, 5, 3, 7, 2
data 10, 5, 3, 7, 2, 6, 4, 5, 9, 1, 2
data 16, 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1
data 4, 5, 5, 5, 5
data 4, 5, 6, 7, 8
data 4, 8, 7, 7, 6
data 5, 6, 7, 10, 7, 6
 
dim as uinteger i, n, j, first, last, water
dim as tower manhattan(0 to 1)
for i = 1 to 7
read n
redim manhattan( 0 to n-1 )
for j = 0 to n-1
read manhattan(j).hght
manhattan(j).posi = j
next j
shellsort( manhattan() )
if manhattan(0).posi < manhattan(1).posi then
first = manhattan(0).posi
last = manhattan(1).posi
else
first = manhattan(1).posi
last = manhattan(0).posi
end if
water = manhattan(1).hght * (last-first-1)
for j = 2 to n-1
if first<manhattan(j).posi and manhattan(j).posi<last then water -= manhattan(j).hght
if manhattan(j).posi < first then
water += manhattan(j).hght * (first-manhattan(j).posi-1)
first = manhattan(j).posi
end if
if manhattan(j).posi > last then
water += manhattan(j).hght * (manhattan(j).posi-last-1)
last = manhattan(j).posi
end if
next j
print using "City configuration ## collected #### units of water."; i; water
next i</syntaxhighlight>
{{out}}
<pre>City configuration 1 collected 2 units of water.
City configuration 2 collected 14 units of water.
City configuration 3 collected 35 units of water.
City configuration 4 collected 0 units of water.
City configuration 5 collected 0 units of water.
City configuration 6 collected 0 units of water.
City configuration 7 collected 0 units of water.</pre>
 
==={{header|GW-BASIC}}===
{{works with|BASICA}}
Line 894 ⟶ 969:
Block 6 holds 0 water units.
Block 7 holds 0 water units.</pre>
 
 
==={{header|Nascom BASIC}}===
{{trans|FreeBasic}}
{{works with|Nascom ROM BASIC|4.7}}
<syntaxhighlight lang="basic">
10 REM Water collected between towers
20 MXN=19
30 REM Heights of towers in each city
40 REM prefixed by the number of towers
50 DATA 5,1,5,3,7,2
60 DATA 10,5,3,7,2,6,4,5,9,1,2
70 DATA 16,2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1
80 DATA 4,5,5,5,5
90 DATA 4,5,6,7,8
100 DATA 4,8,7,7,6
110 DATA 5,6,7,10,7,6
120 DIM A(MXN,1)
130 FOR I=1 TO 7
140 READ N
150 FOR J=0 TO N-1
160 READ A(J,0)
170 A(J,1)=J
180 NEXT J
190 GOSUB 390
200 IF A(0,1)>=A(1,1) THEN 220
210 FRST=A(0,1):LST=A(1,1):GOTO 230
220 FRST=A(1,1):LST=A(0,1)
230 WTR=A(1,0)*(LST-FRST-1)
240 FOR J=2 TO N-1
250 IF FRST>=A(J,1) OR A(J,1)>=LST THEN 270
260 WTR=WTR-A(J,0)
270 IF A(J,1)>=FRST THEN 300
280 WTR=WTR+A(J,0)*(FRST-A(J,1)-1)
290 FRST=A(J,1)
300 IF A(J,1)<=LST THEN 330
310 WTR=WTR+A(J,0)*(A(J,1)-LST-1)
320 LST=A(J,1)
330 NEXT J
340 PRINT "Bar chart";I;"collected";
350 PRINT WTR;"units of water."
360 NEXT I
370 END
380 REM ** ShellSort
390 GAP=N-1
400 GAP=INT(GAP/2.2)
410 IF GAP=0 THEN GAP=1
420 FOR K=GAP TO N-1
430 TH=A(K,0):TP=A(K,1)
440 L=K
450 IF L<GAP THEN 500
460 IF A(L-GAP,0)>=TH THEN 500
470 A(L,0)=A(L-GAP,0):A(L,1)=A(L-GAP,1)
480 L=L-GAP
490 GOTO 450
500 A(L,0)=TH:A(L,1)=TP
510 NEXT K
520 IF GAP<>1 THEN 400
530 RETURN
</syntaxhighlight>
{{out}}
<pre>
Bar chart 1 collected 2 units of water.
Bar chart 2 collected 14 units of water.
Bar chart 3 collected 35 units of water.
Bar chart 4 collected 0 units of water.
Bar chart 5 collected 0 units of water.
Bar chart 6 collected 0 units of water.
Bar chart 7 collected 0 units of water.
</pre>
 
==={{header|QuickBASIC}}===
{{trans|FreeBasic}}
<syntaxhighlight lang="qbasic">
' Water collected between towers
DECLARE SUB ShellSort (A() AS ANY)
TYPE TTowerRec
Hght AS INTEGER
Posi AS INTEGER
END TYPE
 
'heights of towers in each city prefixed by the number of towers
DATA 5, 1, 5, 3, 7, 2
DATA 10, 5, 3, 7, 2, 6, 4, 5, 9, 1, 2
DATA 16, 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1
DATA 4, 5, 5, 5, 5
DATA 4, 5, 6, 7, 8
DATA 4, 8, 7, 7, 6
DATA 5, 6, 7, 10, 7, 6
 
REM $DYNAMIC
DIM Manhattan(0 TO 1) AS TTowerRec
FOR I% = 1 TO 7
READ N%
ERASE Manhattan
REDIM Manhattan(0 TO N% - 1) AS TTowerRec
FOR J% = 0 TO N% - 1
READ Manhattan(J%).Hght
Manhattan(J%).Posi = J%
NEXT J%
ShellSort Manhattan()
IF Manhattan(0).Posi < Manhattan(1).Posi THEN
First% = Manhattan(0).Posi
Last% = Manhattan(1).Posi
ELSE
First% = Manhattan(1).Posi
Last% = Manhattan(0).Posi
END IF
Water% = Manhattan(1).Hght * (Last% - First% - 1)
FOR J% = 2 TO N% - 1
IF First% < Manhattan(J%).Posi AND Manhattan(J%).Posi < Last% THEN Water% = Water% - Manhattan(J%).Hght
IF Manhattan(J%).Posi < First% THEN
Water% = Water% + Manhattan(J%).Hght * (First% - Manhattan(J%).Posi - 1)
First% = Manhattan(J%).Posi
END IF
IF Manhattan(J%).Posi > Last% THEN
Water% = Water% + Manhattan(J%).Hght * (Manhattan(J%).Posi - Last% - 1)
Last% = Manhattan(J%).Posi
END IF
NEXT J%
PRINT USING "City configuration ## collected #### units of water."; I%; Water%
NEXT I%
END
 
REM $STATIC
SUB ShellSort (A() AS TTowerRec)
'quick and dirty shellsort, not the focus of this exercise
Gap% = UBOUND(A): N% = UBOUND(A)
DIM Temp AS TTowerRec
DO
Gap% = INT(Gap% / 2.2)
IF Gap% = 0 THEN Gap% = 1
FOR I% = Gap% TO N%
Temp = A(I%)
J% = I%
' Simulated WHILE J% >= Gap% ANDALSO A(J% - Gap%).Hght < Temp.Hght
DO
IF J% < Gap% THEN EXIT DO
IF A(J% - Gap%).Hght >= Temp.Hght THEN EXIT DO
A(J%) = A(J% - Gap%)
J% = J% - Gap%
LOOP
A(J%) = Temp
NEXT I%
LOOP UNTIL Gap% = 1
END SUB
</syntaxhighlight>
{{out}}
<pre>
City configuration 1 collected 2 units of water.
City configuration 2 collected 14 units of water.
City configuration 3 collected 35 units of water.
City configuration 4 collected 0 units of water.
City configuration 5 collected 0 units of water.
City configuration 6 collected 0 units of water.
City configuration 7 collected 0 units of water.
</pre>
 
==={{header|uBasic/4tH}}===
{{Trans|GW-BASIC}}
<syntaxhighlight lang="basic">Dim @t(20)
 
k = FUNC (_getWater (1, 5, 3, 7, 2, 1))
k = FUNC (_getWater (5, 3, 7, 2, 6, 4, 5, 9, 1, 2, k))
k = FUNC (_getWater (2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1, k))
k = FUNC (_getWater (5, 5, 5, 5, k))
k = FUNC (_getWater (5, 6, 7, 8, k))
k = FUNC (_getWater (8, 7, 7, 6, k))
k = FUNC (_getWater (6, 7, 10, 7, 6, k))
End
 
_getWater
Param (1)
Local (2)
 
w = 0
c@ = Used()
 
For b@ = c@ - 1 To 0 Step -1
@t(b@) = Pop()
Next
 
Do While FUNC(_netWater (c@)) > 1 : Loop
 
Print "Block ";a@;" holds ";w;" water units."
Return (a@ + 1)
 
_netWater
Param (1)
Local (3)
 
For d@ = a@-1 To 0 Step -1
If @t(d@) Then
If d@ = 0 Then Unloop : Return (0) : fi
Else
Continue
EndIf
 
b@ = 0
 
For c@ = 0 To d@
If @t(c@) > 0 Then
@t(c@) = @t(c@) - 1
b@ = b@ + 1
Else
If b@ > 0 Then w = w + 1 : fi
EndIf
Next
 
Unloop : Return (b@)
Next
Return (0)</syntaxhighlight>
{{Out}}
<pre>Block 1 holds 2 water units.
Block 2 holds 14 water units.
Block 3 holds 35 water units.
Block 4 holds 0 water units.
Block 5 holds 0 water units.
Block 6 holds 0 water units.
Block 7 holds 0 water units.
 
0 OK, 0:409</pre>
 
==={{header|Visual Basic .NET}}===
====Version 1====
'''Method:''' Instead of "scanning" adjoining towers for each column, this routine converts the tower data into a string representation with building blocks, empty spaces, and potential water retention sites. The potential water retention sites are then "eroded" away where they are found to be unsupported. This is accomplished with the '''.Replace()''' function. The replace operations are unleashed upon the entire "block" of towers, rather than a cell at a time or a line at a time - which perhaps increases the program's execution-time, but reduces program's complexity.
 
The program can optionally display the interim string representation of each tower block before the final count is completed. I've since modified it to have the same block and wavy characters are the
[[{{FULLPAGENAME}}#version_3|REXX 9.3]] output, but used the double-wide columns, as pictured in the task definition area.
<syntaxhighlight lang="vbnet">' Convert tower block data into a string representation, then manipulate that.
Module Module1
Sub Main(Args() As String)
Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1 ' Show towers.
Dim wta As Integer()() = { ' Water tower array (input data).
New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},
New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},
New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},
New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}
Dim blk As String, ' String representation of a block of towers.
lf As String = vbLf, ' Line feed to separate floors in a block of towers.
tb = "██", wr = "≈≈", mt = " " ' Tower Block, Water Retained, eMpTy space.
For i As Integer = 0 To wta.Length - 1
Dim bpf As Integer ' Count of tower blocks found per floor.
blk = ""
Do
bpf = 0 : Dim floor As String = "" ' String representation of each floor.
For j As Integer = 0 To wta(i).Length - 1
If wta(i)(j) > 0 Then ' Tower block detected, add block to floor,
floor &= tb : wta(i)(j) -= 1 : bpf += 1 ' reduce tower by one.
Else ' Empty space detected, fill when not first or last column.
floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt)
End If
Next
If bpf > 0 Then blk = floor & lf & blk ' Add floors until blocks are gone.
Loop Until bpf = 0 ' No tower blocks left, so terminate.
' Erode potential water retention cells from left and right.
While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While
While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While
' Optionaly show towers w/ water marks.
If shoTow Then Console.Write("{0}{1}", lf, blk)
' Subtract the amount of non-water mark characters from the total char amount.
Console.Write("Block {0} retains {1,2} water units.{2}", i + 1,
(blk.Length - blk.Replace(wr, "").Length) \ 2, lf)
Next
End Sub
End Module</syntaxhighlight>
{{out}}<syntaxhighlight lang="text">Block 1 retains 2 water units.
Block 2 retains 14 water units.
Block 3 retains 35 water units.
Block 4 retains 0 water units.
Block 5 retains 0 water units.
Block 6 retains 0 water units.
Block 7 retains 0 water units.</syntaxhighlight>
Verbose output shows towers with water ("Almost equal to" characters) left in the "wells" between towers. Just supply any command-line parameter to see it. Use no command line parameters to see the plain output above.
<syntaxhighlight lang="text"> ██
██
██≈≈██
██≈≈██
██████
████████
██████████
Block 1 retains 2 water units.
 
██
██
██≈≈≈≈≈≈≈≈██
██≈≈██≈≈≈≈██
██≈≈██≈≈██≈≈████
██≈≈██≈≈████████
██████≈≈████████
████████████████≈≈██
████████████████████
Block 2 retains 14 water units.
 
██
██≈≈≈≈≈≈≈≈≈≈≈≈≈≈██
██≈≈≈≈≈≈██≈≈≈≈≈≈≈≈≈≈≈≈≈≈██
██≈≈██≈≈██≈≈≈≈≈≈≈≈██≈≈████
██≈≈██≈≈██≈≈██≈≈≈≈██≈≈██████
██████≈≈██≈≈██≈≈≈≈██████████
████████████≈≈████████████████
████████████████████████████████
Block 3 retains 35 water units.
 
████████
████████
████████
████████
████████
Block 4 retains 0 water units.
 
██
████
██████
████████
████████
████████
████████
████████
Block 5 retains 0 water units.
 
██
██████
████████
████████
████████
████████
████████
████████
Block 6 retains 0 water units.
 
██
██
██
██████
██████████
██████████
██████████
██████████
██████████
██████████
Block 7 retains 0 water units.</syntaxhighlight>
 
====Version 2====
'''Method:''' More conventional "scanning" method. A Char array is used, but no Replace() statements. Output is similar to version 1, although there is now a left margin of three spaces, the results statement is immediately to the right of the string representation of the tower blocks (instead of underneath), the verb is "hold(s)" instead of "retains", and there is a special string when the results indicate zero.
 
<syntaxhighlight lang="vbnet">Module Module1
''' <summary>
''' wide - Widens the aspect ratio of a linefeed separated string.
''' </summary>
''' <param name="src">A string representing a block of towers.</param>
''' <param name="margin">Optional padding for area to the left.</param>
''' <returns>A double-wide version of the string.</returns>
Function wide(src As String, Optional margin As String = "") As String
Dim res As String = margin : For Each ch As Char In src
res += If(ch < " ", ch & margin, ch + ch) : Next : Return res
End Function
 
''' <summary>
''' cntChar - Counts characters, also custom formats the output.
''' </summary>
''' <param name="src">The string to count characters in.</param>
''' <param name="ch">The character to be counted.</param>
''' <param name="verb">Verb to include in format. Expecting "hold",
''' but can work with "retain" or "have".</param>
''' <returns>The count of chars found in a string, and formats a verb.</returns>
Function cntChar(src As String, ch As Char, verb As String) As String
Dim cnt As Integer = 0
For Each c As Char In src : cnt += If(c = ch, 1, 0) : Next
Return If(cnt = 0, "does not " & verb & " any",
verb.Substring(0, If(verb = "have", 2, 4)) & "s " & cnt.ToString())
End Function
 
''' <summary>
''' report - Produces a report of the number of rain units found in
''' a block of towers, optionally showing the towers.
''' Autoincrements the blkID for each report.
''' </summary>
''' <param name="tea">An int array with tower elevations.</param>
''' <param name="blkID">An int of the block of towers ID.</param>
''' <param name="verb">The verb to use in the description.
''' Defaults to "has / have".</param>
''' <param name="showIt">When true, the report includes a string representation
''' of the block of towers.</param>
''' <returns>A string containing the amount of rain units, optionally preceeded by
''' a string representation of the towers holding any water.</returns>
Function report(tea As Integer(), ' Tower elevation array.
ByRef blkID As Integer, ' Block ID for the description.
Optional verb As String = "have", ' Verb to use in the description.
Optional showIt As Boolean = False) As String ' Show representaion.
Dim block As String = "", ' The block of towers.
lf As String = vbLf, ' The separator between floors.
rTwrPos As Integer ' The position of the rightmost tower of this floor.
Do
For rTwrPos = tea.Length - 1 To 0 Step -1 ' Determine the rightmost tower
If tea(rTwrPos) > 0 Then Exit For ' postition on this floor.
Next
If rTwrPos < 0 Then Exit Do ' When no towers remain, exit the do loop.
' init the floor to a space filled Char array, as wide as the block of towers.
Dim floor As Char() = New String(" ", tea.Length).ToCharArray()
Dim bpf As Integer = 0 ' The count of blocks found per floor.
For column As Integer = 0 To rTwrPos ' Scan from left to right.
If tea(column) > 0 Then ' If a tower exists here,
floor(column) = "█" ' mark the floor with a block,
tea(column) -= 1 ' drop the tower elevation by one,
bpf += 1 ' and advance the block count.
ElseIf bpf > 0 Then ' Otherwise, see if a tower is present to the left.
floor(column) = "≈" ' OK to fill with water.
End If
Next
If bpf > If(showIt, 0, 1) Then ' Continue the building only when needed.
' If not showing blocks, discontinue building when a single tower remains.
' build tower blocks string with each floor added to top.
block = New String(floor) & If(block = "", "", lf) & block
Else
Exit Do ' Ran out of towers, so exit the do loop.
End If
Loop While True ' Depending on previous break statements to terminate the do loop.
blkID += 1 ' increment block ID counter.
' format report and return it.
Return If(showIt, String.Format(vbLf & "{0}", wide(block, " ")), "") &
String.Format(" Block {0} {1} water units.", blkID, cntChar(block, "≈", verb))
End Function
 
''' <summary>
''' Main routine.
'''
''' With one command line parameter, it shows tower blocks,
''' with no command line parameters, it shows a plain report
'''</summary>
Sub Main()
Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1 ' Show towers.
Dim blkCntr As Integer = 0 ' Block ID for reports.
Dim verb As String = "hold" ' "retain" or "have" can be used instead of "hold".
Dim tea As Integer()() = {New Integer() {1, 5, 3, 7, 2}, ' Tower elevation data.
New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},
New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},
New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},
New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}
For Each block As Integer() In tea
' Produce report for each block of towers.
Console.WriteLine(report(block, blkCntr, verb, shoTow))
Next
End Sub
End Module</syntaxhighlight>
Regular version 2 output:
<syntaxhighlight lang="text"> Block 1 holds 2 water units.
Block 2 holds 14 water units.
Block 3 holds 35 water units.
Block 4 does not hold any water units.
Block 5 does not hold any water units.
Block 6 does not hold any water units.
Block 7 does not hold any water units.</syntaxhighlight>
Sample of version 2 verbose output:
<syntaxhighlight lang="text"> ██
██≈≈≈≈≈≈≈≈≈≈≈≈≈≈██
██≈≈≈≈≈≈██≈≈≈≈≈≈≈≈≈≈≈≈≈≈██
██≈≈██≈≈██≈≈≈≈≈≈≈≈██≈≈████
██≈≈██≈≈██≈≈██≈≈≈≈██≈≈██████
██████≈≈██≈≈██≈≈≈≈██████████
████████████≈≈████████████████
████████████████████████████████ Block 3 holds 35 water units.
 
████████
████████
████████
████████
████████ Block 4 does not hold any water units.</syntaxhighlight>
 
==={{header|Yabasic}}===
{{trans|AWK}}
<syntaxhighlight lang="yabasic">data 7
data "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"
data "5,5,5,5", "5,6,7,8", "8,7,7,6", "6,7,10,7,6"
 
read n
 
for i = 1 to n
read n$
wcbt(n$)
next i
 
sub wcbt(s$)
local tower$(1), hr(1), hl(1), n, i, ans, k
n = token(s$, tower$(), ",")
 
redim hr(n)
redim hl(n)
for i = n to 1 step -1
if i < n then
k = hr(i + 1)
else
k = 0
end if
hr(i) = max(val(tower$(i)), k)
next i
for i = 1 to n
if i then
k = hl(i - 1)
else
k = 0
end if
hl(i) = max(val(tower$(i)), k)
ans = ans + min(hl(i), hr(i)) - val(tower$(i))
next i
print ans," ",n$
end sub</syntaxhighlight>
 
=={{header|C}}==
Line 1,368 ⟶ 1,951:
Block 6 does not hold any water units.
Block 7 does not hold any water units.</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
The program builds a matrix of the towers and scans each line looking for pairs of towers that trap water.
 
<syntaxhighlight lang="Delphi">
 
var Towers1: array [0..4] of integer = (1, 5, 3, 7, 2);
var Towers2: array [0..9] of integer = (5, 3, 7, 2, 6, 4, 5, 9, 1, 2);
var Towers3: array [0..15] of integer = (2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1);
var Towers4: array [0..3] of integer = (5, 5, 5, 5);
var Towers5: array [0..3] of integer = (5, 6, 7, 8);
var Towers6: array [0..3] of integer = (8, 7, 7, 6);
var Towers7: array [0..4] of integer = (6, 7, 10, 7, 6);
 
 
type TMatrix = array of array of boolean;
 
function ArrayToMatrix(Towers: array of integer): TMatrix;
{Convert Tower Array to Matrix for analysis}
var Max,I,X,Y: integer;
begin
Max:=0;
for I:=0 to High(Towers) do if Towers[I]>=Max then Max:=Towers[I];
SetLength(Result,Length(Towers),Max);
for Y:=0 to High(Result[0]) do
for X:=0 to High(Result) do Result[X,Y]:=Towers[X]>(Max-Y);
end;
 
 
procedure DisplayMatrix(Memo: TMemo; Matrix: TMatrix);
{Display a matrix}
var X,Y: integer;
var S: string;
begin
for Y:=0 to High(Matrix[0]) do
begin
S:='[';
for X:=0 to High(Matrix) do
begin
if Matrix[X,Y] then S:=S+'#'
else S:=S+' ';
end;
S:=S+']';
Memo.Lines.Add(S);
end;
end;
 
 
function GetWaterStorage(Matrix: TMatrix): integer;
{Analyze matrix to get water storage amount}
var X,Y,Cnt: integer;
var Inside: boolean;
begin
Result:=0;
{Scan each row of matrix to see if it is storing water}
for Y:=0 to High(Matrix[0]) do
begin
Inside:=False;
Cnt:=0;
for X:=0 to High(Matrix) do
begin
{Test if this is a tower}
if Matrix[X,Y] then
begin
{if so, we may be inside trough}
Inside:=True;
{If Cnt>0 there was a previous tower}
{And we've impounded water }
Result:=Result+Cnt;
{Start new count with new tower}
Cnt:=0;
end
else if Inside then Inc(Cnt); {Count potential impounded water}
end;
end;
end;
 
 
procedure ShowWaterLevels(Memo: TMemo; Towers: array of integer);
{Analyze the water storage of towers and display result}
var Water: integer;
var Matrix: TMatrix;
begin
Matrix:=ArrayToMatrix(Towers);
DisplayMatrix(Memo,Matrix);
Water:=GetWaterStorage(Matrix);
Memo.Lines.Add('Storage: '+IntToStr(Water)+CRLF);
end;
 
 
procedure WaterLevel(Memo: TMemo);
begin
ShowWaterLevels(Memo,Towers1);
ShowWaterLevels(Memo,Towers2);
ShowWaterLevels(Memo,Towers3);
ShowWaterLevels(Memo,Towers4);
ShowWaterLevels(Memo,Towers5);
ShowWaterLevels(Memo,Towers6);
ShowWaterLevels(Memo,Towers7);
end;
 
 
 
 
</syntaxhighlight>
{{out}}
<pre>
[ ]
[ # ]
[ # ]
[ # # ]
[ # # ]
[ ### ]
[ ####]
Storage: 2
 
[ ]
[ # ]
[ # ]
[ # # ]
[ # # # ]
[# # # ## ]
[# # #### ]
[### #### ]
[######## #]
Storage: 14
 
[ ]
[ # ]
[ # # ]
[ # # # ]
[ # # # # ## ]
[ # # # # # ### ]
[ ### # # ##### ]
[###### ######## ]
Storage: 35
 
[ ]
[####]
[####]
[####]
[####]
Storage: 0
 
[ ]
[ #]
[ ##]
[ ###]
[####]
[####]
[####]
[####]
Storage: 0
 
[ ]
[# ]
[### ]
[####]
[####]
[####]
[####]
[####]
Storage: 0
 
[ ]
[ # ]
[ # ]
[ # ]
[ ### ]
[#####]
[#####]
[#####]
[#####]
[#####]
Storage: 0
 
 
Elapsed Time: 171.444 ms.
 
</pre>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="easylang">
proc water h[] . .
n = len h[]
len left[] n
len right[] n
for i = 1 to n
max = higher max h[i]
left[i] = max
.
max = 0
for i = n downto 1
max = higher max h[i]
right[i] = max
.
for i = 1 to n
sum += (lower left[i] right[i]) - h[i]
.
print sum
.
repeat
s$ = input
until s$ = ""
water number strsplit s$ " "
.
#
input_data
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
 
</syntaxhighlight>
 
=={{header|Erlang}}==
Line 1,463 ⟶ 2,266:
{ 6, 7, 10, 7, 6 } -> 0
</pre>
 
=={{header|FreeBASIC}}==
Uses Nigel Galloway's very elegant idea, expressed verbosely so you can really see what's going on.
<syntaxhighlight lang="freebasic">type tower
hght as uinteger
posi as uinteger
end type
 
sub shellsort( a() as tower )
'quick and dirty shellsort, not the focus of this exercise
dim as uinteger gap = ubound(a), i, j, n=ubound(a)
dim as tower temp
do
gap = int(gap / 2.2)
if gap=0 then gap=1
for i=gap to n
temp = a(i)
j=i
while j>=gap andalso a(j-gap).hght < temp.hght
a(j) = a(j - gap)
j -= gap
wend
a(j) = temp
next i
loop until gap = 1
end sub
 
'heights of towers in each city prefixed by the number of towers
data 5, 1, 5, 3, 7, 2
data 10, 5, 3, 7, 2, 6, 4, 5, 9, 1, 2
data 16, 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1
data 4, 5, 5, 5, 5
data 4, 5, 6, 7, 8
data 4, 8, 7, 7, 6
data 5, 6, 7, 10, 7, 6
 
dim as uinteger i, n, j, first, last, water
dim as tower manhattan(0 to 1)
for i = 1 to 7
read n
redim manhattan( 0 to n-1 )
for j = 0 to n-1
read manhattan(j).hght
manhattan(j).posi = j
next j
shellsort( manhattan() )
if manhattan(0).posi < manhattan(1).posi then
first = manhattan(0).posi
last = manhattan(1).posi
else
first = manhattan(1).posi
last = manhattan(0).posi
end if
water = manhattan(1).hght * (last-first-1)
for j = 2 to n-1
if first<manhattan(j).posi and manhattan(j).posi<last then water -= manhattan(j).hght
if manhattan(j).posi < first then
water += manhattan(j).hght * (first-manhattan(j).posi-1)
first = manhattan(j).posi
end if
if manhattan(j).posi > last then
water += manhattan(j).hght * (manhattan(j).posi-last-1)
last = manhattan(j).posi
end if
next j
print using "City configuration ## collected #### units of water."; i; water
next i</syntaxhighlight>
{{out}}
<pre>City configuration 1 collected 2 units of water.
City configuration 2 collected 14 units of water.
City configuration 3 collected 35 units of water.
City configuration 4 collected 0 units of water.
City configuration 5 collected 0 units of water.
City configuration 6 collected 0 units of water.
City configuration 7 collected 0 units of water.</pre>
 
=={{header|Go}}==
Line 2,590 ⟶ 3,318:
@[2, 14, 35, 0, 0, 0, 0]
</pre >
 
=={{header|Pascal}}==
{{works with|Delphi|7}}
{{works with|Free Pascal}}
<syntaxhighlight lang="pascal">
program RainInFlatland;
 
{$IFDEF FPC} // Free Pascal
{$MODE Delphi}
{$ELSE} // Delphi
{$APPTYPE CONSOLE}
{$ENDIF}
 
uses SysUtils;
type THeight = integer;
// Heights could be f.p., but some changes to the code would be needed:
// (1) the inc function isn't available for f.p. values,
// (2) the print-out would need extra formatting.
 
{------------------------------------------------------------------------------
Find highest tower; if there are 2 or more equal highest, choose any.
Then fill troughs so that on going towards the highest tower, from the
left-hand or right-hand end, there are no steps down.
Amount of filling required equals amount of water collected.
}
function FillTroughs( const h : array of THeight) : THeight;
var
m, i, i_max : integer;
h_max : THeight;
begin
result := 0;
m := High( h); // highest index, 0-based; there are m + 1 towers
if (m <= 1) then exit; // result = 0 if <= 2 towers
 
// Find highest tower and its index in the array.
h_max := h[0];
i_max := 0;
for i := 1 to m do begin
if h[i] > h_max then begin
h_max := h[i];
i_max := i;
end;
end;
// Fill troughs from left-hand end to highest tower
h_max := h[0];
for i := 1 to i_max - 1 do begin
if h[i] < h_max then inc( result, h_max - h[i])
else h_max := h[i];
end;
// Fill troughs from right-hand end to highest tower
h_max := h[m];
for i := m - 1 downto i_max + 1 do begin
if h[i] < h_max then inc( result, h_max - h[i])
else h_max := h[i];
end;
end;
 
{-------------------------------------------------------------------------
Wrapper for the above: finds amount of water, and prints input and result.
}
procedure CalcAndPrint( h : array of THeight);
var
water : THeight;
j : integer;
begin
water := FillTroughs( h);
Write( water:5, ' <-- [');
for j := 0 to High( h) do begin
Write( h[j]);
if j < High(h) then Write(', ') else WriteLn(']');
end;
end;
 
{---------------------------------------------------------------------------
Main routine.
}
begin
CalcAndPrint([1,5,3,7,2]);
CalcAndPrint([5,3,7,2,6,4,5,9,1,2]);
CalcAndPrint([2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1]);
CalcAndPrint([5,5,5,5]);
CalcAndPrint([5,6,7,8]);
CalcAndPrint([8,7,7,6]);
CalcAndPrint([6,7,10,7,6]);
end.
</syntaxhighlight>
{{out}}
<pre>
2 <-- [1, 5, 3, 7, 2]
14 <-- [5, 3, 7, 2, 6, 4, 5, 9, 1, 2]
35 <-- [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1]
0 <-- [5, 5, 5, 5]
0 <-- [5, 6, 7, 8]
0 <-- [8, 7, 7, 6]
0 <-- [6, 7, 10, 7, 6]
</pre>
 
=={{header|Perl}}==
Line 3,511 ⟶ 4,335:
2 ██████████
1 ██████████ no units of rainwater collected
</pre>
 
=={{header|RPL}}==
{{trans|Python}}
{{works with|HP|49/50}}
« DUPDUP SIZE 1 - NDUPN →LIST
DUP 1 « 1 NSUB SUB 0 + « MAX » STREAM » DOSUBS 0 SWAP + <span style="color:grey">@ the seq of max heights to the left of each tower</span>
SWAP 1 « NSUB 1 + OVER SIZE SUB 0 + « MAX » STREAM » DOSUBS 0 + <span style="color:grey">@ the seq of max heights to the right of each tower</span>
MIN SWAP -
1 « 0 MAX » DOLIST ∑LIST
» '<span style="color:blue">WATER</span>' STO
« { {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} }
1 « <span style="color:blue">WATER</span> » DOLIST
» '<span style="color:blue">TASK</span>' STO
{{out}}
<pre>
1: { 2 14 35 0 0 0 0 }
</pre>
 
Line 3,852 ⟶ 4,700:
0: 8 7 7 6
0: 6 7 10 7 6</pre>
 
=={{header|Visual Basic .NET}}==
===Version 1===
'''Method:''' Instead of "scanning" adjoining towers for each column, this routine converts the tower data into a string representation with building blocks, empty spaces, and potential water retention sites. The potential water retention sites are then "eroded" away where they are found to be unsupported. This is accomplished with the '''.Replace()''' function. The replace operations are unleashed upon the entire "block" of towers, rather than a cell at a time or a line at a time - which perhaps increases the program's execution-time, but reduces program's complexity.
 
The program can optionally display the interim string representation of each tower block before the final count is completed. I've since modified it to have the same block and wavy characters are the
[[{{FULLPAGENAME}}#version_3|REXX 9.3]] output, but used the double-wide columns, as pictured in the task definition area.
<syntaxhighlight lang="vbnet">' Convert tower block data into a string representation, then manipulate that.
Module Module1
Sub Main(Args() As String)
Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1 ' Show towers.
Dim wta As Integer()() = { ' Water tower array (input data).
New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},
New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},
New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},
New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}
Dim blk As String, ' String representation of a block of towers.
lf As String = vbLf, ' Line feed to separate floors in a block of towers.
tb = "██", wr = "≈≈", mt = " " ' Tower Block, Water Retained, eMpTy space.
For i As Integer = 0 To wta.Length - 1
Dim bpf As Integer ' Count of tower blocks found per floor.
blk = ""
Do
bpf = 0 : Dim floor As String = "" ' String representation of each floor.
For j As Integer = 0 To wta(i).Length - 1
If wta(i)(j) > 0 Then ' Tower block detected, add block to floor,
floor &= tb : wta(i)(j) -= 1 : bpf += 1 ' reduce tower by one.
Else ' Empty space detected, fill when not first or last column.
floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt)
End If
Next
If bpf > 0 Then blk = floor & lf & blk ' Add floors until blocks are gone.
Loop Until bpf = 0 ' No tower blocks left, so terminate.
' Erode potential water retention cells from left and right.
While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While
While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While
' Optionaly show towers w/ water marks.
If shoTow Then Console.Write("{0}{1}", lf, blk)
' Subtract the amount of non-water mark characters from the total char amount.
Console.Write("Block {0} retains {1,2} water units.{2}", i + 1,
(blk.Length - blk.Replace(wr, "").Length) \ 2, lf)
Next
End Sub
End Module</syntaxhighlight>
{{out}}<syntaxhighlight lang="text">Block 1 retains 2 water units.
Block 2 retains 14 water units.
Block 3 retains 35 water units.
Block 4 retains 0 water units.
Block 5 retains 0 water units.
Block 6 retains 0 water units.
Block 7 retains 0 water units.</syntaxhighlight>
Verbose output shows towers with water ("Almost equal to" characters) left in the "wells" between towers. Just supply any command-line parameter to see it. Use no command line parameters to see the plain output above.
<syntaxhighlight lang="text"> ██
██
██≈≈██
██≈≈██
██████
████████
██████████
Block 1 retains 2 water units.
 
██
██
██≈≈≈≈≈≈≈≈██
██≈≈██≈≈≈≈██
██≈≈██≈≈██≈≈████
██≈≈██≈≈████████
██████≈≈████████
████████████████≈≈██
████████████████████
Block 2 retains 14 water units.
 
██
██≈≈≈≈≈≈≈≈≈≈≈≈≈≈██
██≈≈≈≈≈≈██≈≈≈≈≈≈≈≈≈≈≈≈≈≈██
██≈≈██≈≈██≈≈≈≈≈≈≈≈██≈≈████
██≈≈██≈≈██≈≈██≈≈≈≈██≈≈██████
██████≈≈██≈≈██≈≈≈≈██████████
████████████≈≈████████████████
████████████████████████████████
Block 3 retains 35 water units.
 
████████
████████
████████
████████
████████
Block 4 retains 0 water units.
 
██
████
██████
████████
████████
████████
████████
████████
Block 5 retains 0 water units.
 
██
██████
████████
████████
████████
████████
████████
████████
Block 6 retains 0 water units.
 
██
██
██
██████
██████████
██████████
██████████
██████████
██████████
██████████
Block 7 retains 0 water units.</syntaxhighlight>
===Version 2===
'''Method:''' More conventional "scanning" method. A Char array is used, but no Replace() statements. Output is similar to version 1, although there is now a left margin of three spaces, the results statement is immediately to the right of the string representation of the tower blocks (instead of underneath), the verb is "hold(s)" instead of "retains", and there is a special string when the results indicate zero.
 
<syntaxhighlight lang="vbnet">Module Module1
''' <summary>
''' wide - Widens the aspect ratio of a linefeed separated string.
''' </summary>
''' <param name="src">A string representing a block of towers.</param>
''' <param name="margin">Optional padding for area to the left.</param>
''' <returns>A double-wide version of the string.</returns>
Function wide(src As String, Optional margin As String = "") As String
Dim res As String = margin : For Each ch As Char In src
res += If(ch < " ", ch & margin, ch + ch) : Next : Return res
End Function
 
''' <summary>
''' cntChar - Counts characters, also custom formats the output.
''' </summary>
''' <param name="src">The string to count characters in.</param>
''' <param name="ch">The character to be counted.</param>
''' <param name="verb">Verb to include in format. Expecting "hold",
''' but can work with "retain" or "have".</param>
''' <returns>The count of chars found in a string, and formats a verb.</returns>
Function cntChar(src As String, ch As Char, verb As String) As String
Dim cnt As Integer = 0
For Each c As Char In src : cnt += If(c = ch, 1, 0) : Next
Return If(cnt = 0, "does not " & verb & " any",
verb.Substring(0, If(verb = "have", 2, 4)) & "s " & cnt.ToString())
End Function
 
''' <summary>
''' report - Produces a report of the number of rain units found in
''' a block of towers, optionally showing the towers.
''' Autoincrements the blkID for each report.
''' </summary>
''' <param name="tea">An int array with tower elevations.</param>
''' <param name="blkID">An int of the block of towers ID.</param>
''' <param name="verb">The verb to use in the description.
''' Defaults to "has / have".</param>
''' <param name="showIt">When true, the report includes a string representation
''' of the block of towers.</param>
''' <returns>A string containing the amount of rain units, optionally preceeded by
''' a string representation of the towers holding any water.</returns>
Function report(tea As Integer(), ' Tower elevation array.
ByRef blkID As Integer, ' Block ID for the description.
Optional verb As String = "have", ' Verb to use in the description.
Optional showIt As Boolean = False) As String ' Show representaion.
Dim block As String = "", ' The block of towers.
lf As String = vbLf, ' The separator between floors.
rTwrPos As Integer ' The position of the rightmost tower of this floor.
Do
For rTwrPos = tea.Length - 1 To 0 Step -1 ' Determine the rightmost tower
If tea(rTwrPos) > 0 Then Exit For ' postition on this floor.
Next
If rTwrPos < 0 Then Exit Do ' When no towers remain, exit the do loop.
' init the floor to a space filled Char array, as wide as the block of towers.
Dim floor As Char() = New String(" ", tea.Length).ToCharArray()
Dim bpf As Integer = 0 ' The count of blocks found per floor.
For column As Integer = 0 To rTwrPos ' Scan from left to right.
If tea(column) > 0 Then ' If a tower exists here,
floor(column) = "█" ' mark the floor with a block,
tea(column) -= 1 ' drop the tower elevation by one,
bpf += 1 ' and advance the block count.
ElseIf bpf > 0 Then ' Otherwise, see if a tower is present to the left.
floor(column) = "≈" ' OK to fill with water.
End If
Next
If bpf > If(showIt, 0, 1) Then ' Continue the building only when needed.
' If not showing blocks, discontinue building when a single tower remains.
' build tower blocks string with each floor added to top.
block = New String(floor) & If(block = "", "", lf) & block
Else
Exit Do ' Ran out of towers, so exit the do loop.
End If
Loop While True ' Depending on previous break statements to terminate the do loop.
blkID += 1 ' increment block ID counter.
' format report and return it.
Return If(showIt, String.Format(vbLf & "{0}", wide(block, " ")), "") &
String.Format(" Block {0} {1} water units.", blkID, cntChar(block, "≈", verb))
End Function
 
''' <summary>
''' Main routine.
'''
''' With one command line parameter, it shows tower blocks,
''' with no command line parameters, it shows a plain report
'''</summary>
Sub Main()
Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1 ' Show towers.
Dim blkCntr As Integer = 0 ' Block ID for reports.
Dim verb As String = "hold" ' "retain" or "have" can be used instead of "hold".
Dim tea As Integer()() = {New Integer() {1, 5, 3, 7, 2}, ' Tower elevation data.
New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},
New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},
New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},
New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}
For Each block As Integer() In tea
' Produce report for each block of towers.
Console.WriteLine(report(block, blkCntr, verb, shoTow))
Next
End Sub
End Module</syntaxhighlight>
Regular version 2 output:
<syntaxhighlight lang="text"> Block 1 holds 2 water units.
Block 2 holds 14 water units.
Block 3 holds 35 water units.
Block 4 does not hold any water units.
Block 5 does not hold any water units.
Block 6 does not hold any water units.
Block 7 does not hold any water units.</syntaxhighlight>
Sample of version 2 verbose output:
<syntaxhighlight lang="text"> ██
██≈≈≈≈≈≈≈≈≈≈≈≈≈≈██
██≈≈≈≈≈≈██≈≈≈≈≈≈≈≈≈≈≈≈≈≈██
██≈≈██≈≈██≈≈≈≈≈≈≈≈██≈≈████
██≈≈██≈≈██≈≈██≈≈≈≈██≈≈██████
██████≈≈██≈≈██≈≈≈≈██████████
████████████≈≈████████████████
████████████████████████████████ Block 3 holds 35 water units.
 
████████
████████
████████
████████
████████ Block 4 does not hold any water units.</syntaxhighlight>
 
=={{header|Wren}}==
Line 4,102 ⟶ 4,705:
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="ecmascriptwren">import "./math" for Math, Nums
import "./fmt" for Fmt
 
var waterCollected = Fn.new { |tower|
Line 4,174 ⟶ 4,777:
2 14 35 0 0 0 0
</pre>
 
=={{header|Yabasic}}==
{{trans|AWK}}
<syntaxhighlight lang="yabasic">data 7
data "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"
data "5,5,5,5", "5,6,7,8", "8,7,7,6", "6,7,10,7,6"
 
read n
 
for i = 1 to n
read n$
wcbt(n$)
next i
 
sub wcbt(s$)
local tower$(1), hr(1), hl(1), n, i, ans, k
n = token(s$, tower$(), ",")
 
redim hr(n)
redim hl(n)
for i = n to 1 step -1
if i < n then
k = hr(i + 1)
else
k = 0
end if
hr(i) = max(val(tower$(i)), k)
next i
for i = 1 to n
if i then
k = hl(i - 1)
else
k = 0
end if
hl(i) = max(val(tower$(i)), k)
ans = ans + min(hl(i), hr(i)) - val(tower$(i))
next i
print ans," ",n$
end sub</syntaxhighlight>
 
=={{header|zkl}}==
Anonymous user