Shuffle a part of an array

Hi everyone,
I am new to julia, can someone please let me know how to shuffle a part of an array in julia using the shuffle function…?

using Random

A=collect(1:10)

shuffle!(A[1:9])
println(A[1:9])

shuffle!(A)
println(A)

output

[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 10, 6, 8, 9, 3, 5, 7, 4, 1]

You can observe that shuffle!(A[1:9]) is not working.

julia> A=collect(1:10);

julia> shuffle!(view(A,1:9));

julia> A
10-element Vector{Int64}:
  8
  2
  6
  4
  5
  1
  7
  3
  9
 10
3 Likes

Explanation:
When you do

A[1:9] is separated out as a new (temporary) array, with its own separate memory, so shuffle! only gets to modify that. A itself remains unchanged.

Doing view(A, 1:9) or @view(A[1:9]) (both do the same thing) gives you access to that part of the array without allocating in a different new memory spot. This lets shuffle! modify the contents of A itself.

view is a very useful feature to know for performance too, because allocating new memory can be costly, and views avoid that. So when you need high performance in some part of the code and are accessing slices of arrays like A[1:9] in it, changing those into @views can give a good performance boost (unless you actually need a copy of the values, of course).

4 Likes

Thank you for your help @digital_carver

1 Like

Thank you for your help @oheil

1 Like