Knuth shuffle: Difference between revisions
Content added Content deleted
ReeceGoding (talk | contribs) m (→{{header|R}}: Syntax highlighting.) |
Not a robot (talk | contribs) (Add CLU) |
||
Line 1,362: | Line 1,362: | ||
vect (range (dec (count vect)) 1 -1)))</lang> |
vect (range (dec (count vect)) 1 -1)))</lang> |
||
This works by generating a sequence of end-indices from n-1 to 1, then reducing that sequence (starting with the original vector) through a function that, given a vector and end-index, performs a swap between the end-index and some random index less than the end-index. |
This works by generating a sequence of end-indices from n-1 to 1, then reducing that sequence (starting with the original vector) through a function that, given a vector and end-index, performs a swap between the end-index and some random index less than the end-index. |
||
=={{header|CLU}}== |
|||
<lang clu>knuth_shuffle = proc [T: type] (a: array[T]) |
|||
lo: int := array[T]$low(a) |
|||
hi: int := array[T]$high(a) |
|||
for i: int in int$from_to_by(hi, lo+1, -1) do |
|||
j: int := lo + random$next(i-lo+1) |
|||
temp: T := a[i] |
|||
a[i] := a[j] |
|||
a[j] := temp |
|||
end |
|||
end knuth_shuffle |
|||
start_up = proc () |
|||
po: stream := stream$primary_output() |
|||
d: date := now() |
|||
random$seed(d.second + 60*(d.minute + 60*d.hour)) |
|||
arr: array[int] := array[int]$[1,2,3,4,5,6,7,8,9] |
|||
knuth_shuffle[int](arr) |
|||
for i: int in array[int]$elements(arr) do |
|||
stream$puts(po, int$unparse(i) || " ") |
|||
end |
|||
end start_up</lang> |
|||
{{out}} |
|||
<pre>7 9 2 3 4 8 1 6 5</pre> |
|||
(Or any other order.) |
|||
=={{header|CMake}}== |
=={{header|CMake}}== |