JavaScript implements Twitter Puddles algorithm instance _javascript skill

Source: Internet
Author: User
Tags array example

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.