1
votes

I am trying to learn Julia by repeating some of the easy ProjectEuler problems in Julia. Everything has been really smooth so far, up until I encountered this frustrating problem. I spent some time debugging my code, and here's what I found: (Hopefully I'm not missing something really stupid here)

function is_abundant(n::Int)                        #just a function
    return prod(map(x->int((x[1]^(x[2]+1)-1)/(x[1]-1)),factor(n))) > 2 * n
end

abundants=[12]     #there should be a better way to initialize an Array
for i=13:28120
    if is_abundant(i)
        push!(abundants,i)
    end
end

le=abundants;      #The following lines are the problems
ri=abundants;
d=length(abundants)
println(d)
pop!(le)
shift!(ri)
println(le==ri, " ", endof(ri), " ", endof(abundants))

The output I get is:

6964 true 6962 6962

which means that Julia has changed all three sets of le , ri and abundants with each of pop! and shift! commands. I was able to work around this bug/problem by using a dumb extra identity mapping:

le=map(x->x,abundants)
ri=map(x->x,abundants)

Now the output would change to what I initially expected:

6964 false 6963 6964

My question is, if this is not a bug, why is Julia keeping an equivalence relation between le , ri and abundants sets in the first place? Also, can anyone reproduce this behaviour? I am using Julia "Version 0.3.0-rc3+14 (2014-08-13 16:01 UTC)" on Ubuntu 14.04.

1
There is only ever one array, you're just making many references to it. Related: julia.readthedocs.org/en/latest/manual/faq/….StefanKarpinski

1 Answers

5
votes

le and ri both point to the same list that abundants points to, so this is expected behavior - they are all operating on the same memory. This part of the manual might help you understand. Or possibly the MATLAB differences section, as it is different in MATLAB (but most other languages are like Julia).

For

abundants=[12] #there should be a better way to initialize an Array

how about

abundants = {}  # Vector of anything

or

abundants = Int[]  # Vector of ints

and instead of your map(x->x,...), you can just use copy.