Skip to content

Instantly share code, notes, and snippets.

@anandology
Created July 3, 2016 15:49
Show Gist options
  • Save anandology/990ec7b9b52526d7122606644c3dd4ec to your computer and use it in GitHub Desktop.
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?
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