Skip to content

Instantly share code, notes, and snippets.

@travisofthenorth
Last active November 17, 2016 00:42
Show Gist options
  • Save travisofthenorth/018dd777e908696bb1f2b9975764cb83 to your computer and use it in GitHub Desktop.
Save travisofthenorth/018dd777e908696bb1f2b9975764cb83 to your computer and use it in GitHub Desktop.
Determine if a contiguous set of positive integers in an array add up to n
class Array
def contains_sum?(n)
return false if n.nil?
low = 0
high = 0
sum = first
while sum != n && low < size
if sum < n || low == high
return false if high == size - 1
high += 1
sum += self[high]
elsif sum > n
sum -= self[low]
low += 1
end
end
sum == n
end
end
@travisofthenorth
Copy link
Author

travisofthenorth commented Nov 14, 2016

Testing:

irb(main):022:0> a = [5, 3, 8, 10, 1]
=> [5, 3, 8, 10, 1]
irb(main):023:0> a.contains_sum?(11)
=> true
irb(main):024:0> a.contains_sum?(1)
=> true
irb(main):025:0> a.contains_sum?(2)
=> false
irb(main):026:0> a.contains_sum?(21)
=> true
irb(main):027:0> a.contains_sum?(5)
=> true
irb(main):028:0> [].contains_sum?(10)
=> false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment