Knuth shuffle: Difference between revisions
Content added Content deleted
Not a robot (talk | contribs) (Add CLU) |
ReeceGoding (talk | contribs) m (→Short version: Improved syntax.) |
||
Line 3,956: | Line 3,956: | ||
===Short version=== |
===Short version=== |
||
After accounting for R being 1-indexed rather than 0-indexed, it's not hard to implement the pseudo-code given in the task almost exactly: |
After accounting for R being 1-indexed rather than 0-indexed, it's not hard to implement the pseudo-code given in the task almost exactly: |
||
<lang rsplus>knuth<-function(vec) |
<lang rsplus>knuth <- function(vec) |
||
{ |
{ |
||
last<-length(vec) |
last <- length(vec) |
||
if(last |
if(last >= 2) |
||
else for(i in last:2) |
|||
{ |
{ |
||
for(i in last:2) |
|||
{ |
|||
⚫ | |||
j <- sample(seq_len(i), size = 1) |
|||
⚫ | |||
} |
|||
} |
} |
||
vec |
vec |
||
Line 3,970: | Line 3,972: | ||
knuth(integer(0)) |
knuth(integer(0)) |
||
knuth(c(10)) |
knuth(c(10)) |
||
replicate(10,knuth(c(10,20))) |
replicate(10, knuth(c(10, 20))) |
||
replicate(10,knuth(c(10,20,30))) |
replicate(10, knuth(c(10, 20, 30))) |
||
knuth(c("Also","works","for","strings"))</lang> |
knuth(c("Also", "works", "for", "strings"))</lang> |
||
{{Out}} |
{{Out}} |
||
<pre>> knuth(integer(0)) |
<pre>> knuth(integer(0)) |
||
Line 3,978: | Line 3,980: | ||
> knuth(c(10)) |
> knuth(c(10)) |
||
[1] 10 |
[1] 10 |
||
> replicate(10,knuth(c(10,20))) |
> replicate(10, knuth(c(10, 20))) |
||
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] |
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] |
||
[1,] 20 20 10 10 20 10 20 10 20 10 |
[1,] 20 20 10 10 20 10 20 10 20 10 |
||
[2,] 10 10 20 20 10 20 10 20 10 20 |
[2,] 10 10 20 20 10 20 10 20 10 20 |
||
> replicate(10,knuth(c(10,20,30))) |
> replicate(10, knuth(c(10, 20, 30))) |
||
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] |
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] |
||
[1,] 30 10 20 20 30 30 10 30 10 10 |
[1,] 30 10 20 20 30 30 10 30 10 10 |
||
[2,] 10 20 30 10 10 10 20 20 20 20 |
[2,] 10 20 30 10 10 10 20 20 20 20 |
||
[3,] 20 30 10 30 20 20 30 10 30 30 |
[3,] 20 30 10 30 20 20 30 10 30 30 |
||
> knuth(c("Also","works","for","strings")) |
> knuth(c("Also", "works", "for", "strings")) |
||
[1] "strings" "Also" "for" "works"</pre> |
[1] "strings" "Also" "for" "works"</pre> |
||