JavaScript to implement twitter puddles algorithm instance, twitterpuddles

Source: Internet
Author: User

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.

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.