I’m new to Ruby, so don’t scream at me…
I’m trying to make all subsets of elements given, even though I know that there is method “permutation” to do this. The problem is with both arrays. Before loop it prints right array and inside the loop it prints different array…
P.S. index_ was needed to stop recursion, since arrays don’t work as required
def generate_subsets(elements)
generate_subsets2(elements, [], 0)
end
def generate_subsets2(left, right, index_)
puts "received as left: #{left.inspect}"
puts "received as right: #{right.inspect}"
return if index_ >= 1
left.each_with_index do |element, index|
puts "left in loop: #{left.inspect}"
copy_left = Array.new(left)
copy_right = Array.new(right)
copy_left.delete_at(index)
copy_right.push(element)
puts "#{copy_left.inspect} & #{copy_right.inspect}"
generate_subsets2(copy_left, copy_right, index_ + 1)
end
end
generate_subsets(['a','b','c','d'])
I modified your code a bit (only the log-output). Most important thing: I show the nesting level (index_).
The result is
You see, left in loop is the same as received on the same nesting level. Without the nesting level, you have the impression, left is changing. Well, it change, but it’s another call.