Wednesday, April 23, 2014

Calculating Water

I came across this interesting programming challenge and couldn't help but dig in and solve it for myself. The solution below is a re-write of the approach I found in this book. My first (less efficient) solution involved a breadth first traversal of a histogram "graph" storing visited & filled cells in a HashSet. 

/**
* Trapping Water
*
* A one-dimensional container is specified by an array of
* n nonnegative integers, specifying the eight of each
* unit-width rectangle. Design an algorithm for computing
* the capacity of the container.
*
* Ex: (X = Occupied, ▤ = Water)
*
* X X
* XXX XXX
* XXXX X XXXX▤▤▤X
* X XXXX X X ==> X▤XXXX▤X▤X ==> 1+2+1+3 = 7
* XXXXXXXXX X XXXXXXXXX▤X
* 12134451203
*/
public class TrappingWater {
/**
* The key to this problem is realizing that the water
* poured into the "container" will flow out of bounds
* on the left and right sides (index < 0 &
* index > array.length). If we are able to find the
* highest point in the array (maxVal), we can divide
* the array into two segments (left and right) around
* this midpoint. For both left & right, there will be
* a region of increasing altitude, and decreasing
* altitude. In the regions of decreasing altitude,
* this is where water will be stored. All we need to
* do is find the local maxima in each left and right
* region.
*
* Thus, the problem can be solved in 3 phases:
* 1) Find the column index with the highest height
* (maxIndex)
* 2) Calculate water in the left hand side: For
* i = [0, maxIndex-1] if we find a new local
* maxima, store it, otherwise we have water
* trapped and we can caluculate the volume
* 3) Calculate water in the right hand side in a
* similar manner for i = [maxIndex+1,
* array.length-1]
*
* Solution is O(N) time, O(1) space
*/
private static int calculateWater(int[] heights) {
// Arrays less than 3 can't contain water
if (heights.length < 3 || heights == null) {
return 0;
}
// 1) Calculate max height index
int maxVal = 0, maxIndex = 0;
for (int i = 0; i < heights.length; i++) {
if (heights[i] > maxVal) {
maxVal = heights[i];
maxIndex = i;
}
}
// 2) Calculate water in left portion of array
int count = 0;
int leftMax = 0;
for (int i = 0; i < maxIndex - 1; i++) {
if (heights[i] > leftMax) {
leftMax = heights[i];
} else {
count += leftMax = heights[i];
}
}
// 3) Calculate water in right portion of array
int rightMax = 0;
for (int i = heights.length - 1; i > maxIndex; i--) {
if (heights[i] > rightMax) {
rightMax = heights[i];
} else {
count += rightMax - heights[i];
}
}
return count;
}
// --- Test code
public static void main(String[] args) {
int[] testData1 = {1};
testCalculateWater(1, testData1, 0);
int[] testData2 = {1, 2, 1, 3, 4, 4, 5, 1, 2, 0, 3};
testCalculateWater(2, testData2, 7);
int[] testData3 = {1, 2, 3, 4, 3, 2, 1};
testCalculateWater(3, testData3, 0);
int[] testData4 = {1, 0, 1, 0, 1, 0, 1, 0};
testCalculateWater(4, testData4, 3);
int[] testData5 = {Integer.MAX_VALUE,
Integer.MAX_VALUE,
Integer.MAX_VALUE,
Integer.MAX_VALUE};
testCalculateWater(5, testData5, 0);
}
private static void testCalculateWater(int testId,
int[] input,
int expectedVal) {
int ret = calculateWater(input);
if (ret == expectedVal) {
System.out.println("PASS");
} else {
System.out.println(
String.format(
"Test %d: FAIL\n\tExpected return = %d\n\tActual return = %d",
testId, expectedVal, ret)
);
}
}
}
The follow up question to this is even more interesting:
"Solve this problem with an algorithm that accesses A's elements in order and can read an element only once. Use minimal additional space."

14 comments:

  1. I'm sorry, although website link developing continues to be going to function as SEARCH ENGINE OPTIMIZATION trump credit card with the foreseeable future. My spouse and i might not store your own air intended for google search algorithms 200-101 to set fewer significance with website link acceptance before the Semantic Web comes, or it could be when HTTP receives replaced by way of a fresh method.

    ReplyDelete
  2. Get free amazon gift card code generator amazon gift cards and start shopping at amazon.

    ReplyDelete
  3. This site provide us free codes of xbox live game so if you wanna free codes of xbox live game then you should visit on this site Thank you free xbox live gold code

    ReplyDelete
  4. amazon gift card now available in the market you can easily download amazon gift card codes generator online

    ReplyDelete
  5. i am latterly very poor in maths and coding but i am an expert in Android Development Services Islamabad so i am not good in maths may be but i am good in android app development.

    ReplyDelete
  6. The most common problem in playing game hay day is lack of coins and diamonds. But now no need to worry about this problem. Here we have a hay day coins and diamonds generator which generate genuine coins and all stuff without any cost. Try is once.

    ReplyDelete
  7. Hello admin,
    this is Ayesha Saleem. I have examine your blog and this post especially. You title is really attractive, Calculating Walter :P . weeks of pregnancy Well, about one and half month ago, i had an uncovered romance with my husband. Now i think i am pregnant and i was searching for the weeks of pregnancy so that i can verify my pregnancy.

    ReplyDelete
  8. Hi admin,
    I am really shocked that how can you measure the amount of water in the rivers and sea. what is mesothelioma Well, i was searching for what is mesothelioma. so i can learn and guide it to someone.

    ReplyDelete
  9. Hi how are you?
    I read your post about how to calculate the water in larger medium, i am not really good at mathematics and you shared a good content. What about also providing information cat wallpaper i hope you'll think about this.

    ReplyDelete
  10. Hello admin
    I have examine your blog and this post especially. You title is really attractive about calculating water xmovies8
    you can watch free and latest movies i hpoe you will think about this

    ReplyDelete
  11. Good Morning Sir,
    I'm so glad that i read your post and all the work is absolutely perfectly defined and explained.Well read latest pakistan urdu news this is exceptionally great an providing us with all the other information which we are looking forward in this blog.

    ReplyDelete
  12. I have examine your weblog and this put up certainly. You title is particularly attractive about calculating water watch online movies

    that you can watch free and state-of-the-art films i hpoe you will think about this

    ReplyDelete
  13. Hi Admin, This is Faisal I really like your post the which you share is really very different and in fact this is new for me because i never heard about this before. international urdu news paper

    ReplyDelete