开发者

Problem with recursion

开发者 https://www.devze.com 2023-04-06 05:44 出处:网络
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

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_).

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消