Adding selected elements in an array using Recursion

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.

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]]]
2 Likes

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.

1 Like

Try this:

arr = [1,2,3,4,5]

first, *rest = arr
(1..arr.size-1).flat_map { |n| rest.combination(n).to_a }.
                map { |a| a.unshift(first) }
  #=> [[1, 2], [1, 3], [1, 4], [1, 5],
  #    [1, 2, 3], [1, 2, 4], [1, 2, 5],
  #      [1, 3, 4], [1, 3, 5],
  #      [1, 4, 5],
  #    [1, 2, 3, 4], [1, 2, 3, 5],
  #      [1, 2, 4, 5],
  #      [1, 3, 4, 5],
  #    [1, 2, 3, 4, 5]] 

Notice that the desired result is asymmetric in the sense that all digits other than the first (1) are incremented. Forgetting about the 1’s it is seen that what is wanted follows a familiar pattern.

The title asks for a solution that uses recursion. This one does not. Yes, recursion could be used, but why restrict solutions to the use of a particular technique? This is an example of what is sometimes called an X-Y problem. If you specifically want a recursive solution let me know and I’ll post one.

1 Like

@SouravGoswami, nice solution. It’s curious how you do chaining. I’ve not seen that before.

1 Like