我要生成n!R中给定n的置换
假设n=3 那么输出应该是:一个包含向量的向量: 123 213 132 231我要生成n!R中给定n的置换,r,permutation,R,Permutation,假设n=3 那么输出应该是:一个包含向量的向量: 123 213 132 231 321以下是一些非递归代码: maxdepth <- 4 curdepth <- 1 l <- list() i <- 0 while (i < maxdepth) { l <- c(l, 1) i <- i+1 } done <- 0 results <- list() resct <- 1 print(paste(sep=",",l)
321以下是一些非递归代码:
maxdepth <- 4
curdepth <- 1
l <- list()
i <- 0
while (i < maxdepth) {
l <- c(l, 1)
i <- i+1
}
done <- 0
results <- list()
resct <- 1
print(paste(sep=",",l))
while (curdepth > 0) {
if (curdepth == maxdepth) {
results[[resct]] <- l
resct <- resct+1
l[[curdepth]] <- l[[curdepth]]+1
}
if (l[[curdepth]] == maxdepth+1) {
while (!done && l[[curdepth]] == maxdepth+1) {
l[[curdepth]] <- 1
curdepth <- curdepth-1
if (curdepth == 0) {
done <- 1
}
}
if (!done) {
l[[curdepth]] <- l[[curdepth]]+1
}
} else if (curdepth < maxdepth) {
curdepth <- curdepth+1
}
}
maxdepth这将解决您的问题:
install.packages("combinat")
require(combinat)
permn(1:3)
还有功能:选择、合并、扩展.grid
将来可能会对您有用。gregmisc
包应该具有permutations()
函数
permutations3,3)
我不知道情况是否如此,但我会试一试。
如果你想做一些有大量排列的长一点的向量的事情,那么使用蒙特卡罗并简单地用大量随机排列对空间进行采样(这可能是在R中使用sample
函数生成的)要求要低得多,效果也差不多 不久前,我不得不在base R中执行此操作,而不加载任何包:
permutations <- function(n){
if(n==1){
return(matrix(1))
} else {
sp <- permutations(n-1)
p <- nrow(sp)
A <- matrix(nrow=n*p,ncol=n)
for(i in 1:n){
A[(i-1)*p+1:p,] <- cbind(i,sp+(sp>=i))
}
return(A)
}
}
permutations <- function(n){
if(n==1){
return(matrix(1))
} else {
sp <- permutations(n-1)
p <- nrow(sp)
A <- matrix(nrow=n*p,ncol=n)
for(i in 1:n){
A[(i-1)*p+1:p,] <- cbind(i,sp+(sp>=i))
}
return(A)
}
}
> permutations(3)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 1 3 2
[3,] 2 1 3
[4,] 2 3 1
[5,] 3 1 2
[6,] 3 2 1