How to resolve the algorithm Water collected between towers step by step in the CLU programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Water collected between towers step by step in the CLU 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 CLU programming language
Source code in the clu programming language
max = proc [T: type] (a,b: T) returns (T)
where T has lt: proctype (T,T) returns (bool)
if a
else return(a)
end
end max
% based on: https://stackoverflow.com/a/42821623
water = proc (towers: sequence[int]) returns (int)
si = sequence[int]
w: int := 0
left: int := 1
right: int := si$size(towers)
max_left: int := si$bottom(towers)
max_right: int := si$top(towers)
while left <= right do
if towers[left] <= towers[right] then
max_left := max[int](towers[left], max_left)
w := w + max[int](max_left - towers[left], 0)
left := left + 1
else
max_right := max[int](towers[right], max_right)
w := w + max[int](max_right - towers[right], 0)
right := right - 1
end
end
return(w)
end water
start_up = proc ()
si = sequence[int]
ssi = sequence[si]
po: stream := stream$primary_output()
tests: ssi := ssi$[
si$[1, 5, 3, 7, 2],
si$[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
si$[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
si$[5, 5, 5, 5],
si$[5, 6, 7, 8],
si$[8, 7, 7, 6],
si$[6, 7, 10, 7, 6]
]
for test: si in ssi$elements(tests) do
stream$puts(po, int$unparse(water(test)) || " ")
end
end start_up
You may also check:How to resolve the algorithm Binary strings step by step in the Lua programming language
You may also check:How to resolve the algorithm Loops/N plus one half step by step in the LabVIEW programming language
You may also check:How to resolve the algorithm Search a list step by step in the GAP programming language
You may also check:How to resolve the algorithm Search a list of records step by step in the Elixir programming language
You may also check:How to resolve the algorithm Strip whitespace from a string/Top and tail step by step in the Run BASIC programming language