2011-09-18 9 views
0

Ruby를 처음 접해 보니 비명을 지르지 마십시오 ... 이 작업을 수행하는 "순열 (permutation)"메서드가 있다는 것을 알고 있더라도 주어진 요소의 모든 하위 집합을 만들려고합니다. . 두 배열 모두에 문제가 있습니다. 루프 전에는 오른쪽 배열을 인쇄하고 루프 내부에는 다른 배열을 인쇄합니다 ... P. 배열은 필요에 따라 작동하지 않기 때문에 재귀를 막기 위해 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']) 
+0

왜'return index_> = 1'입니까? –

+0

그냥 프로그램을 중지하는 것입니다. 그렇지 않으면 그것은 자신의 삶을 살고 ... – damluar

답변

1

약간의 코드 (로그 출력 만)가 수정되었습니다. 가장 중요한 사항 : 중첩 수준 (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']) 

결과는 루프에 왼쪽 볼

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

것은 동일한 중첩 레벨에 접수 바와 같다. 중첩 수준이 없으면 왼쪽의 느낌이 달라집니다. 음, 바뀌지 만, 또 다른 부름입니다.

+0

고마워요! 멍청한 실수) – damluar