Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
12
Task/Knuth-shuffle/R/knuth-shuffle-1.r
Normal file
12
Task/Knuth-shuffle/R/knuth-shuffle-1.r
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
fisheryatesshuffle <- function(n)
|
||||
{
|
||||
pool <- seq_len(n)
|
||||
a <- c()
|
||||
while(length(pool) > 0)
|
||||
{
|
||||
k <- sample.int(length(pool), 1)
|
||||
a <- c(a, pool[k])
|
||||
pool <- pool[-k]
|
||||
}
|
||||
a
|
||||
}
|
||||
21
Task/Knuth-shuffle/R/knuth-shuffle-2.r
Normal file
21
Task/Knuth-shuffle/R/knuth-shuffle-2.r
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
fisheryatesknuthshuffle <- function(n)
|
||||
{
|
||||
a <- seq_len(n)
|
||||
while(n >=2)
|
||||
{
|
||||
k <- sample.int(n, 1)
|
||||
if(k != n)
|
||||
{
|
||||
temp <- a[k]
|
||||
a[k] <- a[n]
|
||||
a[n] <- temp
|
||||
}
|
||||
n <- n - 1
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
#Example usage:
|
||||
fisheryatesshuffle(6) # e.g. 1 3 6 2 4 5
|
||||
x <- c("foo", "bar", "baz", "quux")
|
||||
x[fisheryatesknuthshuffle(4)] # e.g. "bar" "baz" "quux" "foo"
|
||||
19
Task/Knuth-shuffle/R/knuth-shuffle-3.r
Normal file
19
Task/Knuth-shuffle/R/knuth-shuffle-3.r
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
knuth <- function(vec)
|
||||
{
|
||||
last <- length(vec)
|
||||
if(last >= 2)
|
||||
{
|
||||
for(i in last:2)
|
||||
{
|
||||
j <- sample(seq_len(i), size = 1)
|
||||
vec[c(i, j)] <- vec[c(j, i)]
|
||||
}
|
||||
}
|
||||
vec
|
||||
}
|
||||
#Demonstration:
|
||||
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"))
|
||||
Loading…
Add table
Add a link
Reference in a new issue