JavaScript to implement twitter puddles algorithm instance, twitterpuddles
Today I found a very interesting algorithm question. The following is a description of its algorithm, which is derived from a twitter interview question.
Twitter puddles Algorithm Description
First look at a diagram
The number in is described based on an array. At last, the height of a wall is simulated based on the size of each number. Finally, a wall is generated. Ask, when it rains, how much water can this wall hold, in the unit of 1.
The following figure shows a wall after the water is installed.
After reading the above picture, I think it is fun. Indeed, the following is a simple analysis of its algorithm implementation.
In fact, this principle is relatively simple. There are several points in total:
1. water cannot be filled on the leftmost and rightmost sides.
2. The height of the filled water depends on the two maximum values in the left and right sides of the water.
Below we will use js to simply implement it:
Copy codeThe Code is as follows:
/**
* Calculate the amount of water that can be attached to a wall with the array height.
* Array example [,]
**/
Function getWaterCounts (arg ){
Var I = 0,
J = 0,
Count = 0;
// The first and last items must be excluded.
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;
// The value is smaller than the maximum value on the left and right sides.
// If the current value is greater than or equal to this value, nothing will be done.
If (arg [I] <min ){
Count + = min-arg [I];
}
}
Console. log (count );
}
GetWaterCounts ([,]); // 11
Summary
Hey, is implementation quite simple? In fact, as long as you are willing to think about it, js can be used to implement many interesting things.