Today I found a very interesting algorithm, the following is its algorithm description, from the Twitter of a face test.
Twitter Puddles algorithm Description
First look at a picture
The figure above is based on an array of content to describe, and finally based on the size of each number to simulate the height of a wall, and finally create a wall, ask you, when it rains, this wall can be installed how much water to 1 for the count unit.
Below is the appearance of a wall after the water is loaded.
After reading the above picture, the feeling is not very fun, indeed, the following simple analysis of its algorithm implementation
In fact, this principle is relatively simple, a total of the following several points:
1. The left and the far right must not be loaded with water.
2. The height of water loading depends on the minimum of two maximum values in the left and right sides.
Here we use JS to simply implement it:
Copy Code code as follows:
/**
* Calculate how much water can be loaded with a wall of an array
* Array example [2,5,1,2,3,4,7,7,6,9]
**/
function Getwatercounts (ARG) {
var i = 0,
j = 0,
Count = 0;
The first and last items have to be ruled out.
for (i = 1; i < arg.length-1; i++) {
var left = Math.max.apply (null, arg.slice (0, i + 1));
var right = Math.max.apply (null, Arg.slice (i, arg.length));
var min = left >= right? Right:left;
To the left and right sides of the maximum value of the small
If the current value is greater than or equal to this value, do nothing.
if (Arg[i] < min) {
Count + = Min-arg[i];
}
}
Console.log (count);
}
Getwatercounts ([2,5,1,2,3,4,7,7,6,9]); 11
Summarize
Hey, realize is not quite simple, in fact, as long as you are willing to think, with JS can achieve a lot of fun things.