How to resolve the algorithm Water collected between towers step by step in the Swift programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Water collected between towers step by step in the Swift 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 Swift programming language

Source code in the swift programming language

// Based on this answer from Stack Overflow:
// https://stackoverflow.com/a/42821623

func waterCollected(_ heights: [Int]) -> Int {
    guard heights.count > 0 else {
        return 0
    }
    var water = 0
    var left = 0, right = heights.count - 1
    var maxLeft = heights[left], maxRight = heights[right]
    
    while left < right {
        if heights[left] <= heights[right] {
            maxLeft = max(heights[left], maxLeft)
            water += maxLeft - heights[left]
            left += 1
        } else {
            maxRight = max(heights[right], maxRight)
            water += maxRight - heights[right]
            right -= 1
        }
    }
    return water
}

for heights 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]] {
    print("water collected = \(waterCollected(heights))")
}


  

You may also check:How to resolve the algorithm Array concatenation step by step in the LabVIEW programming language
You may also check:How to resolve the algorithm Verify distribution uniformity/Naive step by step in the OCaml programming language
You may also check:How to resolve the algorithm Read a configuration file step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Heronian triangles step by step in the Logtalk programming language
You may also check:How to resolve the algorithm JSON step by step in the zkl programming language