递归问题

时间:2011-09-18 21:29:44

标签: ruby recursion

我是Ruby的新手,所以不要尖叫我...... 我正在尝试给出所有元素的子集,即使我知道有方法“置换”来做到这一点。问题在于两个阵列。在循环之前它打印正确的数组并在循环内部打印不同的数组... 附:需要index_来停止递归,因为数组不能按要求工作

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 个答案:

答案 0 :(得分:1)

我稍微修改了你的代码(只有日志输出)。最重要的是:我展示了嵌套级别(索引_)。

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'])

结果是

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"]

您会看到,左循环与在同一嵌套级别上收到的相同。没有嵌套级别,你就会有印象,左边就是变化。好吧,它改变了,但这是另一个电话。