How to resolve the algorithm Water collected between towers step by step in the Wren programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Water collected between towers step by step in the Wren 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 Wren programming language
Source code in the wren programming language
import "/math" for Math, Nums
import "/fmt" for Fmt
var waterCollected = Fn.new { |tower|
var n = tower.count
var highLeft = [0] + (1...n).map { |i| Nums.max(tower[0...i]) }.toList
var highRight = (1...n).map { |i| Nums.max(tower[i...n]) }.toList + [0]
var t = (0...n).map { |i| Math.max(Math.min(highLeft[i], highRight[i]) - tower[i], 0) }
return Nums.sum(t)
}
var 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 (tower in towers) Fmt.print("$2d from $n", waterCollected.call(tower), tower)
You may also check:How to resolve the algorithm Loops/Nested step by step in the Fantom programming language
You may also check:How to resolve the algorithm Variable size/Get step by step in the COBOL programming language
You may also check:How to resolve the algorithm First-class functions step by step in the Delphi programming language
You may also check:How to resolve the algorithm Copy a string step by step in the Mirah programming language
You may also check:How to resolve the algorithm Hello world/Standard error step by step in the PureBasic programming language