0

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'])
1
  • It's just to stop the program. Otherwise it lives its own life... Commented Sep 18, 2011 at 22:04

1 Answer 1

1

I modified your code a bit (only the log-output). Most important thing: I show the nesting level (index_).

def generate_subsets(elements)
  generate_subsets2(elements, [], 0)
end

def log( txt, arr, level )
  puts "%-20s %-2i %s" % [ txt, level, arr ]
end

def generate_subsets2(left, right, index_)

  log "received as left:", left.inspect, index_
  #~ log "received as right:", right.inspect, index_
  return if index_ >= 1

  left.each_with_index do |element, index|
      log "left in loop:", left.inspect, index_
      #~ log "right in loop:", right.inspect, index_
      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'])

The result is

received as left:    0  ["a", "b", "c", "d"]
left in loop:        0  ["a", "b", "c", "d"]
received as left:    1  ["b", "c", "d"]
left in loop:        0  ["a", "b", "c", "d"]
received as left:    1  ["a", "c", "d"]
left in loop:        0  ["a", "b", "c", "d"]
received as left:    1  ["a", "b", "d"]
left in loop:        0  ["a", "b", "c", "d"]
received as left:    1  ["a", "b", "c"]

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.