Knuth shuffle: Difference between revisions

m
→‎Short version: Improved syntax.
(Add CLU)
m (→‎Short version: Improved syntax.)
Line 3,956:
===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:
<lang rsplus>knuth <- function(vec)
{
last <- length(vec)
if(last< >= 2){return(vec)}
else for(i in last:2)
{
j<-samplefor(1:i,1 in last:2)
{
vec[c(i,j)]<-vec[c(j,i)]
j <- sample(seq_len(i), size = 1)
vec[c(i, j)] <- vec[c(j, i)]
}
}
vec
Line 3,970 ⟶ 3,972:
knuth(integer(0))
knuth(c(10))
replicate(10, knuth(c(10, 20)))
replicate(10, knuth(c(10, 20, 30)))
knuth(c("Also", "works", "for", "strings"))</lang>
{{Out}}
<pre>> knuth(integer(0))
Line 3,978 ⟶ 3,980:
> knuth(c(10))
[1] 10
> replicate(10, knuth(c(10, 20)))
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 20 20 10 10 20 10 20 10 20 10
[2,] 10 10 20 20 10 20 10 20 10 20
> replicate(10, knuth(c(10, 20, 30)))
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 30 10 20 20 30 30 10 30 10 10
[2,] 10 20 30 10 10 10 20 20 20 20
[3,] 20 30 10 30 20 20 30 10 30 30
> knuth(c("Also", "works", "for", "strings"))
[1] "strings" "Also" "for" "works"</pre>
 
331

edits