How to return values from a recursive function to an array
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)
I have some problems with return values from a rudimentary recursive function that calculates combinations with repetitions. I can't figure out how to capture the replacement with println
some return to an array in a function combwithrep()
. I was also unable to use tasks for this. The best result is to get an iterator over those values, but that's not possible in recursion, right?
I feel like the answer is simple and I don't understand anything about recursion.
+3
source to share
1 answer
It's certainly not optimal, but functional.
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}:
['+','+','+']
['+','+','-']
['+','+','*']
['+','+','/']
['+','-','-']
['+','-','*']
['+','-','/']
['+','*','*']
['+','*','/']
['+','/','/']
['-','-','-']
['-','-','*']
['-','-','/']
['-','*','*']
['-','*','/']
['-','/','/']
['*','*','*']
['*','*','/']
['*','/','/']
['/','/','/']
+2
source to share