Skip to content

Instantly share code, notes, and snippets.

@jwperry
Created May 28, 2019 21:12
Show Gist options
  • Save jwperry/c4a7a18c547ea0afa91bd1c50696e045 to your computer and use it in GitHub Desktop.
Save jwperry/c4a7a18c547ea0afa91bd1c50696e045 to your computer and use it in GitHub Desktop.
Hill Pooling Solution
def hills(terrain)
return 0 if terrain.empty?
forward_pool_depths = find_pools(terrain, "forward")
reverse_pool_depths = find_pools(terrain.reverse, "reverse")
return (forward_pool_depths + reverse_pool_depths)
end
def find_pools(terrain, direction)
highest_point = 0
potential_pools = []
total_depth = 0
terrain.map do |height|
if (height > highest_point)
total_depth += pool_depths(potential_pools, highest_point)
highest_point = height
potential_pools = []
elsif (height == highest_point && direction == "forward")
total_depth += pool_depths(potential_pools, highest_point)
highest_point = height
potential_pools = []
else
potential_pools.push(height)
end
end
return total_depth
end
def pool_depths(potential_pools, highest_point)
return 0 if potential_pools.empty?
potential_pools.compact.map { |n| highest_point - n }.sum
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment