I want to get the index of sorted array components at the primary array using a recursive function.
Important note: I know this can be done using a half line of Julia code, But I'm trying to practice writing recursive functions!
Example:
input --> [5, 1, 7, 2, 3, 4]
output (Julia) --> [3, 1, 6, 5, 4, 2]
Since the argmax of the input is 3, and after that, the next argmax is 1, and so on.
And the code which I wrote for this:
julia> function sort_argmax(array)
all(==(-Inf), array) && nothing
any(!=(-Inf), array) && vcat(argmax(array) ,sort_argmax(vcat(array[1:argmax(array)-1], -Inf,array[argmax(array) 1:end])))
end
sort_argmax (generic function with 1 method)
The expected output for the given [5, 1, 7, 2, 3, 4]
Vector:
7-element Vector{Int64}:
3
1
6
5
4
2
The real output:
julia> sort_argmax([5, 1, 7, 2, 3, 4])
7-element Vector{Int64}:
3
1
6
5
4
2
0
There is a surplus 0
at the end of the output, and I don't expect that! How can I achieve the expected result? And, what's the reason behind emerging the last 0
?
CodePudding user response:
The fact that there is no nothing
as part of the output is a clue that something may be wrong with that part of the code. When we take another look at that line:
all(==(-Inf), array) && nothing
we see that it just evaluates to nothing
, but doesn't do anything with that value. Your intention here is probably to return nothing
from here - which needs an explicit return
keyword unless you're at the very end of the function.
all(==(-Inf), array) && return nothing
However, when you run that code, the output is:
julia> sort_argmax([5, 1, 7, 2, 3, 4])
7-element Vector{Union{Nothing, Int64}}:
3
1
6
5
4
2
nothing
a Vector{Union{Nothing, Int64}}
is not exactly what we wanted. This happens because nothing
is a value on its own, and takes part in the vcat
as an argument. There are a few different ways to fix this, but the easiest/laziest way here is probably to return an empty array instead:
all(==(-Inf), array) && return Int[]
julia> sort_argmax([5, 1, 7, 2, 3, 4])
6-element Vector{Int64}:
3
1
6
5
4
2