Merge to number

hi all
i have two arrays a and b
find the maximum between a[i] and b[i] and return it
if i have a = [1,5,9,2] and b =[3,3,7,8,6,4]
the output will be
res = [3,5,9,8,6,4]
it is easy i know but i don’t know why my code not 100% working.

it is not issue of julia forgive me but if some one can fix it i appreciate that

thanks

this is my code…

function MaxPair(a,b)
   
    if length(a) >= length(b)
        c = length(a)
        sh = length(b)
    else  
        c = length(b)
        sh = length(a)
    end
    println(c , sh)
    res = Array{Int64}(undef,c)
    i=1
    while i<=sh
        if a[i] >= b[i]
            res[i] = a[i]
            i+=1
        else
            res[i] = b[i]
            i +=1
        end
    end
    if length(a) >= length(b)
        while sh<=length(a)
            res[sh] = a[sh]
            sh+=1
        end
    end
    if length(b) >= length(a) 
        while sh <= length(b)
            res[sh] = b[sh]
            sh+=1
        end
    end
    return res
end
a = [1,5,880,9999]
b = [3,2,9,99999]
println(MaxPair(a,b))

You have to redefine a to be of the same size as b.

julia>  a = [1,5,9,2,0,0]

Then it’s as easy as this:

julia> max.(b, a)
6-element Array{Int64,1}:
 3
 5
 9
 8
 6
 4
2 Likes

and if i don’t know the length in the first place ?

can you write it with the familiar way not with max.

Here’s an idea to handle different length arrays the way you describe your output:

function max_pair(a, b)
    na, nb = length(a), length(b)
    na == nb && return max.(a, b)

    # make sure a is the longer one
    if nb > na
        a, b = b, a
        na, nb = nb, na
    end
    # compare the comparable
    maxes = max.(a[1:nb], b)
    # append the rest
    append!(maxes, a[nb+1:end])
    return maxes
end
1 Like

that’s help
thanks
here is the final code, i want it with out the max.

function MaxPair(a,b)
    na, nb = length(a), length(b)
    # make sure a is the longer one
    if nb > na
        a, b = b, a
        na, nb = nb, na
    end
    res = Array{Int64}(undef,na)
    i=1
    while i<=nb
        if a[i] >= b[i]
            res[i] = a[i]
            i+=1
        else
            res[i] = b[i]
            i +=1
        end
    end
        while nb+1<=length(a)
            res[nb+1] = a[nb+1]
            nb+=1
        end
    return res
end
a = [1,5,880,99,3254,3245,3254,345,3245,324599]
b = [3,2,9,9999,2345,324,3,4,34,3254,2345,23244,4,234,2435,9]
println(MaxPair(a,b))