forked from ruby-course-may-2014/homework0
-
Notifications
You must be signed in to change notification settings - Fork 0
/
task1.rb
executable file
·57 lines (54 loc) · 1.29 KB
/
task1.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# Takes an array of integers as an argument
# and returns the sum of its elements.
# For an empty array it should return zero.
def sum(array)
array.reduce(0) { |res, elem| res + elem }
end
# Takes an array of integers as an argument
# and returns the sum of its two largest elements.
# For an empty array it should return zero.
# For an array with just one element,
# it should return that element.
def max_2_sum(array)
array_new = []
while(!array.empty? && array_new.size < 2)
max_elem = array.max
array_new << max_elem
array.delete(max_elem)
end
sum(array_new)
end
# DIFFICULT
# 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.
def sum_to_n?(array, n)
if (array.empty?)
if (n == 0)
true
else
false
end
elsif (array.size == 1)
(array.first == n)
else equal_sum(array, n)
end
end
def equal_sum(array, n)
array_new = []
0.upto(array.size - 2) do |i|
(i + 1).upto(array.size - 1) do |j|
array_new << array[i] << array[j]
if (equal?(array_new, n))
return true
end
array_new = []
end
end
return false
end
def equal?(array, value)
sum(array) == value
end