Created
February 4, 2014 20:24
-
-
Save anonymous/8811629 to your computer and use it in GitHub Desktop.
platzhirsch's problem
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 'pp' | |
# Function that solves an interview question commonly known as | |
# platzhirsch's problem. | |
def overlap(array, interval) | |
left = array.select { |array_interval| array_interval[1] < interval[0] } | |
right = array.select { |array_interval| array_interval[0] > interval[1] } | |
rest = array-left-right | |
left + [[rest.first[0] <= interval[0] ? rest.first[0] : interval[0], rest.last[1] >= interval[1] ? rest.last[1] : interval[1]]] + right | |
end | |
pp overlap(array = [[1, 4], [6, 10], [14, 19]], interval = [13, 17]) # => [1, 4], [6, 10], [13, 19] | |
pp overlap(array = [[1, 5], [6, 15], [20, 21], [23, 26], [27, 30], [35, 40]], s_interval = [14, 33]) # => [1, 5], [6, 33], [35, 40] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment