Knuth shuffle: Difference between revisions

→‎{{header|Julia}}: A new entry for Julia
(→‎{{header|Julia}}: A new entry for Julia)
Line 1,337:
agglib is loaded
[12 6 8 4 14 18 7 15 1 0 11 13 5 10 16 2 19 17 9 20 3]
</pre>
 
=={{header|Julia}}==
Julia provides the built-ins <tt>shuffle</tt> and <tt>shuffle!</tt> that implement the Kunth shuffle (with the latter being an in-place version). These methods work for any sort of vector. The current (version 0.3) source for the most general version of <tt>shuffle!</tt> as contained in [https://github.com/JuliaLang/julia/blob/master/base/random.jl <tt>random.jl</tt>] is
<lang Julia>
function shuffle!(r::AbstractRNG, a::AbstractVector)
for i = length(a):-1:2
j = rand(r, 1:i)
a[i], a[j] = a[j], a[i]
end
return a
end
</lang>
As an example, here is <tt>shuffle</tt> in action.
<lang Julia>
a = collect(1:20)
b = shuffle(a)
 
print("Unshuffled Array:\n ")
println(a)
print("Shuffled Array:\n ")
println(b)
</lang>
 
{{out}}
<pre>
Unshuffled Array:
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
Shuffled Array:
[1,13,19,17,6,4,10,8,18,20,2,5,7,3,12,16,9,15,11,14]
</pre>