Created
October 31, 2013 09:49
-
-
Save leikind/7247086 to your computer and use it in GitHub Desktop.
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
def count_blocks_with_water blocks | |
blocks.max.downto(0).reduce(0){|sum, level| | |
sum + | |
blocks.each_with_index.select{|block, idx| | |
block >= level | |
}.map{|_, idx| | |
idx | |
}.each_cons(2).reduce(0){|accu, tuple| | |
accu + tuple[1] - tuple[0] - 1 | |
} | |
} | |
end | |
require 'minitest/unit' | |
class CountBlocks < MiniTest::Unit::TestCase | |
# X | |
# XXX | |
def test_case1 | |
assert_equal 0, count_blocks_with_water([1, 2, 1]) | |
end | |
# XXX | |
# XXX | |
def test_case2 | |
assert_equal 0, count_blocks_with_water([2, 2, 2]) | |
end | |
# X X | |
# XXX | |
def test_case3 | |
assert_equal 1, count_blocks_with_water([2, 1, 2]) | |
end | |
# X X | |
# X X | |
def test_case4 | |
assert_equal 2, count_blocks_with_water([2, 0, 2]) | |
end | |
# X | |
# X | |
# X X | |
# XX X X | |
# X XX XXX | |
# XXX XXXXXXX | |
def test_case5 | |
assert_equal 15, count_blocks_with_water([1, 2, 1, 0, 0, 4, 3, 1, 1, 3, 2, 6]) | |
end | |
def test_case6 | |
# Stolen from https://gist.github.com/igor47/7228586 | |
[ | |
[[1,0,1], 1], | |
[[5,0,5], 5], | |
[[0,1,0,1,0], 1], | |
[[1,0,1,0], 1], | |
[[1,0,1,2,0,2], 3], | |
[[2,5,1,2,3,4,7,7,6], 10], | |
[[5,1,0,1], 1], | |
[[2,5,1,2,3,4,7,7,6,3,5], 12] | |
].each do |blocks, result| | |
assert_equal result, count_blocks_with_water(blocks) | |
end | |
end | |
end | |
MiniTest::Unit.autorun |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment