Adding selected elements in an array using Recursion

#1

I want to achieve the below via recursion:
[1,2,3,4,5]

first iteration => 1 + 2
second iteration => 1+ 3
third iteration => 1+4
fourth iteration =>1+5
fifth iteration => 1+2+3
sixth iteration => 1+2+4
seventh iteration =>1+2+5
eigth iteration => 1+2+3+4
ninth iteration => 1+2+3+5

but I do not know if there is a good way provided in Ruby to do this. Kindly assist please.

#2

Hi there. You can do this:
#!/usr/bin/ruby -w

ary = [1, 2, 3, 4, 5]
sz = ary.size - 1

sz.-(1).times do |i|
	(i + 1..sz).each { |j| puts ary[0..i].<<(ary[j]).then { |v| "#{v.join(' + ')} = #{v.sum}" } }
end

Output:

1 + 2 = 3
1 + 3 = 4
1 + 4 = 5
1 + 5 = 6
1 + 2 + 3 = 6
1 + 2 + 4 = 7
1 + 2 + 5 = 8
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 5 = 11

I am not sure what you want to do with the strings like this. If you want the arrays itself:

# Added 6:
ary = [1, 2, 3, 4, 5, 6]
sz = ary.size - 1

p (0..sz.-(2)).map { |i| (i + 1..sz).map { |j| ary[0..i].<<(ary[j]) } }

Output:

[[[1, 2], [1, 3], [1, 4], [1, 5], [1, 6]], [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 2, 6]], [[1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 3, 6]], [[1, 2, 3, 4, 5], [1, 2, 3, 4, 6]]]
1 Like
#3

thanks so much! I actually need the second part(not the string version). I want to add the numbers in that format and test if it is equal to another number. I was looking at implementing the second part using recursion.