Bifrost
Bifrost

Reputation: 83

Can't access Julia Array ( BoundsError: attempt to access 0-element Vector{Int64} at index [1] )

Julia Code:

seed = 1234
N = 2
newNum = Int64[]
for i in 1:N
    seq = digits(seed*seed, pad=8)
    seed = seq[6]*1000+seq[5]*100+seq[4]*10+seq[3]
    newNum[i] = seed
end
newNum[2]

Error: https://i.sstatic.net/3p390.png

Upvotes: 5

Views: 1441

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69869

Use:

seed = 1234
N = 2
newNum = Int64[]
for i in 1:N
    seq = digits(seed*seed, pad=8)
    seed = seq[6]*1000+seq[5]*100+seq[4]*10+seq[3]
    push!(newNum, seed)
end
newNum[2]

or

seed = 1234
N = 2
newNum = Vector{Int64}(undef, N)
for i in 1:N
    seq = digits(seed*seed, pad=8)
    seed = seq[6]*1000+seq[5]*100+seq[4]*10+seq[3]
    newNum[i] = seed
end
newNum[2]

However, in general, I would recommend you to wrap this code in a function, as otherwise it will be inefficient, and moreover if you try running it as a script (i.e. not interactively in REPL) you will get an error:

┌ Warning: Assignment to `seed` in soft scope is ambiguous because a global variable by the same name exists: `seed` will 
be treated as a new local. Disambiguate by using `local seed` to suppress this warning or `global seed` to assign to the existing global variable.
└ 
ERROR: LoadError: UndefVarError: seed not defined

The reason is that seed is a global variable that you rebind in local scope introduced by for loop. You might want to check out this part of the Julia Manual to learn more about it.

Upvotes: 4

Related Questions