Home >Web Front-end >JS Tutorial >JavaScript implementation of twitter puddles algorithm example_javascript skills
I found a very interesting algorithm question today. The following is its algorithm description, which is derived from an interview question on Twitter.
Twitter puddles algorithm description
Look at a picture first
The numbers in the picture above are described based on the contents of an array. Finally, the height of a wall will be simulated based on the size of each number, and finally a wall will be generated. I ask you, when it rains, this wall can be installed How much water, in units of 1.
Here is what a wall looks like after filling it with water
After reading the above picture, I think it is very interesting. Indeed, let’s briefly analyze its algorithm implementation
In fact, this principle is relatively simple. There are a few key points in total:
1. The far left and rightmost sides must not be filled with water
2. The height of water filling depends on the minimum of the two maximum values on the left and right sides
Below we use js to simply implement it:
Summary
Hey, the implementation is quite simple, in fact, as long as you are willing to think, you can achieve a lot of fun things with js.