Lvassilopoulos
Lvassilopoulos

Reputation: 105

Julia | Error with Reverse For Loop

I would like to create an array that goes like this

[1, 2, 1, 3, 2, 1, 4, 3, 2, 1]

I use the following code, that should be right, but I am not getting the result I would like.

x = 0

for i in 1:4
   for z in i:1

       x = x + 1
       index[x] = z

   end
end

Thank you for your time.

Upvotes: 1

Views: 172

Answers (1)

Colin T Bowers
Colin T Bowers

Reputation: 18560

I would use the following one-liner:

index = [ n for m in 1:4 for n in m:-1:1 ]

If you actually need to pre-allocate index for some reason, you can also write the loop out more verbosely like so:

m = 4
index = ones(Int, sum(1:m))
c = 1
for m in 1:4
    for n in m:-1:1
        index[c] = n
        c += 1
    end
end

Upvotes: 2

Related Questions