Created
September 24, 2012 15:59
-
-
Save ColinDKelley/3776709 to your computer and use it in GitHub Desktop.
elevation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Elevation | |
attr_reader :elevations | |
def initialize(elevations) | |
@elevations = elevations | |
highest = 0 | |
@highest_lefts = @elevations.map { |elevation| | |
highest = Math.max(highest, elevation) | |
} | |
highest = 0 | |
@highest_rights = @elevations.reverse.map { |elevation| | |
highest = Math.max(highest, elevation) | |
}.reverse | |
end | |
def highest_left(n) | |
@highest_lefts[n] | |
end | |
def highest_right(n) | |
@highest_rights[n] | |
end | |
def depth(n) | |
high_left = highest_left(n) | |
high_right = highest_right(n) | |
water_height = Math.min(high_left, high_right) | |
water_height - elevations[n] | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require File.expand_path('../../test_helper', __FILE__) | |
ELEVATIONS = [1, 3, 5, 3, 2, 4, 3, 6, 1] | |
# 0 1 2 3 4 5 6 7 8 | |
class ElevationTest < ActiveSupport::TestCase | |
should "be constructed" do | |
elevation = Elevation.new(ELEVATIONS) | |
end | |
should "store data" do | |
elevation = Elevation.new(ELEVATIONS) | |
assert_equal(ELEVATIONS, elevation.elevations) | |
end | |
should "compute highest_left" do | |
elevation = Elevation.new(ELEVATIONS) | |
assert_equal 5, elevation.highest_left(3) | |
end | |
should "compute highest_right" do | |
elevation = Elevation.new(ELEVATIONS) | |
assert_equal 6, elevation.highest_right(3) | |
end | |
should "compute highest_right at edge" do | |
elevation = Elevation.new(ELEVATIONS) | |
assert_equal 1, elevation.highest_right(8) | |
end | |
should "compute depth" do | |
elevation = Elevation.new(ELEVATIONS) | |
assert_equal 2, elevation.depth(3) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment