Created
July 3, 2016 15:49
-
-
Save anandology/990ec7b9b52526d7122606644c3dd4ec to your computer and use it in GitHub Desktop.
Given an array and a number , how do I find that sum of any consecutive array elements equals the number?
This file contains hidden or 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 search(array, sum, expected, head, tail) | |
if head > tail | |
return false | |
elsif sum == expected | |
return [head, tail] | |
else | |
return (search(array, sum - array[head], expected, head+1, tail) or search(array, sum - array[tail], expected, head, tail-1)) | |
end | |
end | |
def search_sum(array, expected) | |
sum = array.inject(0){|sum,x| sum + x } | |
result = search(array, sum, expected, 0, array.length-1) | |
if result | |
head_, tail = result | |
return array[head_..tail] | |
end | |
end | |
print(search_sum([1, 3, 4, 5, 2], 12)) | |
print("\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment