Advertisement
BillBodkin

Untitled

Aug 19th, 2019
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.98 KB | None | 0 0
  1. #By BillBodkin
  2.  
  3. '''
  4. You are given an array of non-negative integers that represents a two-dimensional elevation map where each element is
  5. unit-width wall and the integer is the height. Suppose it will rain and all spots between two walls get filled up.
  6.  
  7. Compute how many units of water remain trapped on the map in O(N) time and O(1) space.
  8.  
  9. For example, given the input [2, 1, 2], we can hold 1 unit of water in the middle.
  10.  
  11. Given the input [3, 0, 1, 3, 0, 5], we can hold 3 units in the first index, 2 in the second, and 3 in the fourth index
  12. (we cannot hold 5 since it would run off to the left), so we can trap 8 units of water
  13. '''
  14.  
  15. #heightmap = [2, 1, 2]
  16. heightmap = [3, 0, 1, 3, 0, 5]
  17.  
  18. water = [0] * len(heightmap)
  19.  
  20. def rain(amt):
  21.     for w in range(0, len(water)):
  22.         water[w] += amt
  23.  
  24. def slosh(waterMoveSpeed):
  25.     for w in range(0, len(water)):
  26.         height = heightmap[w] + water[w]
  27.         leftHeight = -999
  28.         rightHeight = -999
  29.  
  30.         if(w > 0):
  31.             leftHeight = heightmap[w - 1] + water[w - 1]
  32.         if(w < len(water) - 1):
  33.             rightHeight = heightmap[w + 1] + water[w + 1]
  34.            
  35.         #print("index: " + str(w))
  36.         #print("height: " + str(height))
  37.         #print("leftHeight: " + str(leftHeight))
  38.         #print("rightHeight: " + str(rightHeight))
  39.        
  40.         if(height > leftHeight):
  41.  
  42.             toMove = min(waterMoveSpeed, water[w], height - leftHeight)
  43.  
  44.             water[w] -= toMove
  45.             if(leftHeight > -1):
  46.                 water[w - 1] += toMove
  47.  
  48.         height = heightmap[w] + water[w]
  49.         if(height > rightHeight):
  50.  
  51.             toMove = min(waterMoveSpeed, water[w], height - rightHeight)
  52.  
  53.             water[w] -= toMove
  54.             if(rightHeight > -1):
  55.                 water[w + 1] += toMove
  56.  
  57. for i in range(0, 100):
  58.     rain(0.1)
  59.  
  60. for i in range(0, 2000):
  61.     slosh(0.1)
  62.  
  63. for w in range(0, len(water)):
  64.     water[w] = round(water[w], 2)
  65.  
  66. print(water)
  67. print(sum(water))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement