0
votes

you wil be given an array integer, and number, you should to return the sum of number in (a,b) example : (1,2,3,6,7,8,9,1) and the number is 10 the output is = (1,9),(2,8),(3,7),(8,2),(9,1),(9,1)

    function sumpairs(input, k)

        map = Dict{Int,Int}() 
        count = 0

        for n in input
            complement = k - input[n]
            compl_freq = get(map, complement, 0)

            if compl_freq != 0
                count += 1
                if compl_freq == 1
                    delete!(map, complement)
                else
                    map[complement] -= 1
                end
            else
                map[n] = get(map, n, 0) + 1
            end

        end
          return count
        end
 sumpairs([1,2,3,4,5,6,1,2],6)

i wrote the code in julia, but it doesn't work, can some one explain why? and if its wrote right ?

1
You are missing some of the code. There is no value for k and the code must be wrapped inside a function declaration. Did you write this yourself? Can you provide the entire code? - DNF
i edit the code, but it still not workimg.. can you tell me why ? - Nicholas
Now you have input and k both as input arguments and as constants inside the function. And the return statement is in the wrong place. Can you try to clean this up, and then post an example showing how you call it and what output you get? - DNF
i edited it , it still with no output and no error - Nicholas
What do you mean? It does return an output. It returns the number 2. I don't think that's what you want, though. Why are you returning count instead of map? You need to understand the algorithm if you're going to solve this problem. - DNF

1 Answers

0
votes
function sumpairs(inputvector::Vector{Int64},k::Int64)
    # first create an empty dictionary
    mydict = Dict{Int64,Int64}()

    # Put the inputvector elements into the mydict
    for n in inputvector
        mydict[n] = 1
    end

    # create an outputvector
    outputvector = Vector{Tuple{Int64,Int64}}(undef,0)

    # Now loop throught the inputvector again
    for number in inputvector
        complement = k - number
        if haskey(mydict,number) && haskey(mydict,complement)
            push!(outputvector,(number,complement))
        end
    end

    # Now return the outputvector
    return outputvector
end

resultvector = sumpairs([1,2,3,6,7,8,9,1],10)
println("RESULT = $resultvector")
println("COUNT = ",length(resultvector))

The output of the program is

RESULT = Tuple{Int64,Int64}[(1, 9), (2, 8), (3, 7), (7, 3), (8, 2), (9, 1), (1, 9)]
COUNT = 7