Java to julia

hi
i am new i julia and i have an java code that want to convert it to julia.

public static int sumpairs(Integer input , int k){
static int input = new int{1, 5, 2,4,3};
HashMap <Integer,Integer> map = new HashMap<>();
int count=0;

for(int i =0; i<input.length; i++){
    int complement= k-input[i];
    int value=input[i];
    
    if(map.ContainsKey(complement)){
        int freq = map.get(complement)-1;
        count++;
    } if (freq==0){
        map.remove(complement);
      }else {
        map.put(complement, freq);
    }
    else {
        if(map.ContainsKey(value)){
            map.put(value,map.get(value)+1);
        }  else {
            map.put(value,1);
        }
    }
    
}
return count;

}

public static void main(String args) {
System.out.print("Total pairs " + sumpairs(input , 6));
}

Welcome to the community! What have you tried so far and what obstacles have you met?

ok, so in the first place i need to create a dictionary and a for loop to insert the Integer input in .
and this is like that ?
hash = dict(); # to creat a dect ?
how i wrote this i julia - (map.ContainsKey(complement) or this map.get(complement) or this map.put(complement, freq);

I started to respond but wound up writing the whole thing for the fun of it:

function sumpairs(input::AbstractVector{<:Integer}, k::Integer)
    map = Dict{eltype(input),eltype(input)}()
    count = 0
    for (i,v) ∈ enumerate(input)
        c = k - v
        if haskey(map, c)          
            freq = map[c]-1
            count += 1
            freq == 0 ? delete!(map, c) : (map[c] = freq)
        else   
            map[v] = haskey(map, v) ? (map[v]+1) : 1       
        end
    end
    count
end

Haven’t checked thoroughly for correctness but looks ok. I feel like this can probably be done with a lot fewer allocations.

Note that you don’t really need the type assertions in the argument. Constructing Dicts for temporary use like this can be tricky in Julia because, for your code to be performant, it needs to be correctly typed (the first parameter is the key type, the second is the value type). As you see, in this case I made it just take its types from input.

1 Like

A somewhat more cryptic function than @ExpandingMan 's:

# require the type of `k` to be the same 
# as the type of the elements of `input`
# and that type `T` is an integer type;
# `Vector` is an 1D array
function sumpairs(input::Vector{T}, k::T) where T<:Integer
    # `map` is a dictionary with keys of type `T` and 
    # values of type `Int` (Int32 or Int64, 
    # depending on your OS pointer size)
    map = Dict{T,Int}()
    count = 0
    # if you only need values from a collection,
    # use `for val in collection` syntax
    for n in input
        complement = k - n
        # `get(collection, key, default)` will 
        # return the default value if key is missing
        compl_freq = get(map, complement, 0)
        # judging by the algorithm, all values in `map` must be strictly positive
        # so, 0 can be only encountered as a default return value
        if compl_freq != 0
            count += 1
            if compl_freq == 1
                delete!(map, complement)
            else
                map[complement] -= 1
            end
        else
            # using `get` again for shorter code
            map[n] = get(map, n, 0) + 1
        end
    end
    return count
end
2 Likes

I have come up with a quite unconventional solution that I like, but it has a few pitfalls as it doesn’t work if you need to keep the order of the input (as it sorts the array) or if the array is large (each iteration step introduces a cache miss AFAIK)

function sumpairs(input, k)
    sort!(input)
    left = first(LinearIndices(input))
    right = last(LinearIndices(input))
    count = 0
    while left<right
        s = input[left]+input[right]
        if s==k
            count+=1
            left+=1
            right+=1
        elseif s<k
            left+=1
        elseif s>k
            right+=1
        end
    end
    return count
end
1 Like

thanks a lot , this code what i need, but i still figure why its not working yet,
can you tell me
this is the cade

function sumpairs(input, k)

map = Dict{Int,Int}() count = 0
input = [1,5,2,4,3]
k=6
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

return count
end

end

Oh, I forgot to close the for loop before return. Edited my first post. Must be working now.

1 Like

its with no wrong but with no output.
i wrote this line sumpairs([1,2,3,4,5,6,1,2],6) and still with no output, how i can run it ?
i am using the online julia https://www.tutorialspoint.com/execute_julia_online.php

thank you very much

Oh, OK.
On Tutorialspoint, you don’t have an interactive Julia shell (v0.6.0 is also a bit dated now).
So, you need to explicitly put print or println commands for output:

println("Total pairs ", sumpairs([1,2,3,4,5,6,1,2], 6))

would be the closest to what you had in Java.
In an interactive REPL, you would see the return value printed out after entering a command.

1 Like

it’s work !! thank you very much :slight_smile:

I recently found an online compiler/REPL that already hosts Julia 1.1.0 and is usable without registration, you might want to give it a try :slight_smile:

Repl.it online editor
I recently registered due to the referral system :smiley: and I liked it! :slight_smile: