Created
October 31, 2013 20:08
-
-
Save AhmedNadar/7256203 to your computer and use it in GitHub Desktop.
Define a method sum_to_n? which takes an array of integers and an additional integer, n, as arguments and returns true if any two elements in the array of integers sum to n. An empty array should sum to zero by definition.
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 sum_to_n?(arr, n) | |
(arr.empty? && n.zero?) || arr.permutation(2).any? { |a, b| a + b == n } | |
end | |
# OR | |
def sum_to_n?(arr, n) | |
return true if arr.empty? && n.zero? | |
arr.combination(2).any? {|a, b| a + b == n } | |
end | |
puts "sum_to_n?([0,5,4,7,1], 10)" | |
puts sum_to_n?([0,5,4,7,1], 10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment