Last active
August 20, 2020 06:55
-
-
Save pasikonik/d9052de85b85bdc510032634478171b8 to your computer and use it in GitHub Desktop.
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
# Napisz funkcję, która przyjmuje jako argument tablicę liczb całkowitych oraz liczbę całkowitą n i jako wynik zwraca wartość logiczną określającą czy w tablicy istnieją dwie liczby, których suma jest równa n . | |
def containsSum(numbers, n) | |
return false if numbers.length < 2 | |
result = false | |
length = numbers.length | |
for i in 0..(length-1) | |
for j in 0..(length-1) | |
return true if numbers[i] + numbers[j] = n | |
end | |
end | |
return result | |
end | |
# Przykład: | |
# containsSum([1, 2], 3) -> true // 1+2 == 3 | |
# containsSum([1, 3], 3) -> false | |
# containsSum([2, 4], 4) -> false | |
# containsSum([2, 2], 4) -> true // 2+2 == 4 | |
# containsSum([0, 2], 2) -> true // 0+2 == 2 | |
# containsSum([4, 3, 2, 1, 0], 4) -> true // 1+3 == 4 | |
# containsSum([1], 1) -> false | |
# containsSum([], 1) -> false | |
# containsSum([2, 1, 0], 1) -> true | |
# containsSum([-1, -1, 0], -2) -> true | |
p containsSum([1, 2], 3) | |
p containsSum([1, 3], 3) | |
p containsSum([2, 4], 4) | |
p containsSum([2, 2], 4) | |
p containsSum([0, 2], 2) | |
p containsSum([4, 3, 2, 1, 0], 4) | |
p containsSum([1], 1) | |
p containsSum([], 1) | |
p containsSum([2, 1, 0], 1) | |
p containsSum([-1, -1, 0], -2) | |
rozwiązanie Szota | |
def contains_sum?(array, sum) | |
array.combination(2).any? { |a, b| a + b == sum } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment