1
\$\begingroup\$

This question already has an answer here:

Imagine a histogram. Pour an infinite amount of water on to it. Then stop. How much water does the histogram hold?

Let's say we have a histogram with columns of these heights:

1 3 2 1 4 1 3

That would look like this:

    #
 #  # #
 ## # #
#######
1321413

If we pour an infinite amount of water on this histogram, some of those holes will fill up, and we'll end up with this:

    #
 #..#.#
 ##.#.#
#######
1321413

Apparently, this histogram can hold 5 slots of water.

Your task, should you choose to accept it, is to calculate the number of slots of water that a given histogram can hold. You may accept the input as a list, string, array, matrix, bitmap or whatever format you like. The output should be nothing but a single integer, in any format you like.

The input will only contain column heights between 1 and 1000, and the input size is between 1 and 1000 columns.

Test cases:

1 -> 0
2 1 2 -> 1
1 3 2 1 4 1 3 -> 5
1 3 5 7 6 4 2 1 -> 0
7 1 1 1 1 1 1 1 1 1 7 -> 54
2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1 -> 35

If you're looking for possible ways to solve this problem, here's four.

This is code golf, so the least bytes of source code wins.

\$\endgroup\$

marked as duplicate by xnor code-golf Jul 13 '17 at 21:18

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    \$\begingroup\$ Unfortunately we've had this challenge already: Find the capacity of 2D printed objects \$\endgroup\$ – xnor Jul 13 '17 at 21:17
  • \$\begingroup\$ Ah, okey. Didn't find it while searching. We'll just mark this as a dupe then. \$\endgroup\$ – Filip Haglund Jul 13 '17 at 21:19
1
\$\begingroup\$

Retina, 16 bytes

(?<=# *) (?= *#)

Try it online! Link includes test case. Works by counting the spaces which are surrounded by #s.

\$\endgroup\$
  • \$\begingroup\$ How did you answer this 14 minute ago if this question was closed 22 minutes ago? :o \$\endgroup\$ – HyperNeutrino Jul 13 '17 at 21:41
0
\$\begingroup\$

Python 2, 68 bytes

lambda l:sum(min(max(l[:i+1]),max(l[i:]))-v for i,v in enumerate(l))

Try it online!

\$\endgroup\$
  • \$\begingroup\$ How did you answer this 1 minute ago if this question was closed 22 minutes ago? :o \$\endgroup\$ – HyperNeutrino Jul 13 '17 at 21:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.