【问题标题】:How to return values from recursive function to array如何将递归函数的值返回到数组
【发布时间】:2015-05-20 17:50:39
【问题描述】:
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)

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

我觉得答案很简单,我对递归有些不懂。

【问题讨论】:

  • 在你的尾递归中包含并返回一个累加器会满足你想要的吗?
  • 按照Combinations iterator model 为迭代器创建自己的Typelengthstartnextdone 将是一个很好的练习。
  • @rickhg12hs 累加器是一种计数器,如果我们说的是一样的话。实际上,我需要组合本身,而不是计数器。但似乎我对此的理解不正确。例如,你能显示几行代码吗?
  • @rickhg12hs 谈到来自combinatorics.jl 的组合,是的,你说得对,良好的锻炼是正确的。我知道这个迭代器实现。但它是在没有递归的情况下完成的。我不明白如何在递归情况下实现它。算法重写肯定是可能的,但我试图用递归函数来澄清情况。首先,我想回答一个简单的问题:是否可以从递归函数中进行迭代器?感谢您的帮助。
  • 我已经发布了 a 方法来返回 all 组合。迭代器是可能的,但这应该是一个单独的问题。

标签: recursion julia


【解决方案1】:

这当然不是最佳的,但它很实用。

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}:
 ['+','+','+']
 ['+','+','-']
 ['+','+','*']
 ['+','+','/']
 ['+','-','-']
 ['+','-','*']
 ['+','-','/']
 ['+','*','*']
 ['+','*','/']
 ['+','/','/']
 ['-','-','-']
 ['-','-','*']
 ['-','-','/']
 ['-','*','*']
 ['-','*','/']
 ['-','/','/']
 ['*','*','*']
 ['*','*','/']
 ['*','/','/']
 ['/','/','/']

【讨论】:

  • 你是我的英雄 ;D 非常感谢。我试图做类似的事情,但没有deepcopy()。结果令人沮丧。也许我稍后会打开关于递归迭代器的下一个线程。
猜你喜欢
  • 1970-01-01
  • 2016-11-23
  • 2019-09-16
  • 2015-10-23
  • 2015-04-27
  • 1970-01-01
  • 2020-10-10
  • 2021-06-11
  • 2012-03-11
相关资源
最近更新 更多