如何将值从递归函数返回到数组

时间:2015-05-18 09:31:06

标签: recursion julia

function nestedLoop(depth::Integer, n::Integer, symbArr, len::Integer, k::Integer, num_arr)
  for i = k:len
    num_arr[depth-n+1] = symbArr[i]
    n == 1 && println(num_arr)
    (n > 1) && nestedLoop(depth, n-1, symbArr, len, i, num_arr)
  end
end

function combwithrep(symbArr, n::Integer)
  len = length(symbArr)
  num_arr = Array(eltype(symbArr),n)
  nestedLoop(n, n, symbArr, len, 1, num_arr)
end
@time combwithrep(["+","-","*","/"], 3)

我从基本递归函数返回值时会遇到一些麻烦,它会计算重复的组合。我无法实现如何在println函数中使用某些返回数组来替换combwithrep()。我也没有为此使用任务。最好的结果是在这个值上获得迭代器,但在递归时不可能,不是吗?

我觉得答案很简单,我对递归不了解。

1 个答案:

答案 0 :(得分:2)

这当然不是最佳的,但它是有效的。

julia> function nested_loop{T <: Integer, V <: AbstractVector}(depth::T, n::T, symb_arr::V, len::T, k::T, num_arr::V, result::Array{V,1})
           for i = k:len
               num_arr[depth-n+1] = symb_arr[i]
               n == 1 ? push!(result, deepcopy(num_arr)) : nested_loop(depth, n-1, symb_arr, len, i, num_arr, result)
           end
       end
nested_loop (generic function with 1 method)

julia> function combwithrep(symb_arr::AbstractVector, n::Integer)
           len = length(symb_arr)
           num_arr = Array(eltype(symb_arr),n)
           result = Array{typeof(num_arr)}(0)
           nested_loop(n, n, symb_arr, len, 1, num_arr, result)
           return result
       end
combwithrep (generic function with 1 method)

julia> combwithrep(['+', '-', '*', '/'], 3)
20-element Array{Array{Char,1},1}:
 ['+','+','+']
 ['+','+','-']
 ['+','+','*']
 ['+','+','/']
 ['+','-','-']
 ['+','-','*']
 ['+','-','/']
 ['+','*','*']
 ['+','*','/']
 ['+','/','/']
 ['-','-','-']
 ['-','-','*']
 ['-','-','/']
 ['-','*','*']
 ['-','*','/']
 ['-','/','/']
 ['*','*','*']
 ['*','*','/']
 ['*','/','/']
 ['/','/','/']