客观的:
详细说明一个函数,该函数返回尺寸为4x4的数组。该函数可能产生的结果的一个示例是:
我所做的一切:
matriz<-function(M){
M<-matrix(ncol=4,nrow=4);
M[1,]<-sample(LETTERS[1:4]);
M[2,]<-sample(LETTERS[1:4]);
for(i in 2:4){
for(j in 1:4){
j<-j
if(j<=4)
if(M[i,j]!= M[i-1,j]){
j<-j+1
}
else{
M[i,]<-sample(LETTERS[1:4])
}
}
i<-i+1
if(i<=4){
M[i,]<-sample(LETTERS[1:4])
j=1
}
else{print(M)}
}
}
debug(matriz); matriz(M)
最佳答案
这似乎有效。它生成所有可能组合的列表,然后删除与先前选择的行匹配的任何组合,最后只保留一个。
matriz <- function(n){
combs <- as.matrix(expand.grid(rep(list(LETTERS[1:n]),n)))
combs <- combs[apply(combs,1,function(r) all(LETTERS[1:n] %in% r)),]
mat <- matrix(NA,nrow=n,ncol=n)
for(i in 1:(n-1)){
mat[i,] <- combs[sample(1:nrow(combs),1),]
combs <- combs[!apply(combs,1,function(r) any(r == mat[i,])),]
}
mat[n,] <- combs
return(mat)
}
> matriz(5)
[,1] [,2] [,3] [,4] [,5]
[1,] "B" "D" "A" "E" "C"
[2,] "E" "C" "D" "B" "A"
[3,] "D" "A" "B" "C" "E"
[4,] "A" "E" "C" "D" "B"
[5,] "C" "B" "E" "A" "D"
> matriz(5)
[,1] [,2] [,3] [,4] [,5]
[1,] "D" "C" "E" "B" "A"
[2,] "E" "A" "C" "D" "B"
[3,] "A" "D" "B" "C" "E"
[4,] "B" "E" "D" "A" "C"
[5,] "C" "B" "A" "E" "D"
使用
combinat
包的版本稍快一些,library(combinat)
matriz <- function(n){
combs <- do.call(rbind,permn(LETTERS[1:n]))
mat <- matrix(NA,nrow=n,ncol=n)
#rest of function as above...
在n> 10左右时,这两个速度都可能非常慢。但是,如果生成了一个有效的正方形
m
,则所有其他正方形都将是排列m[sample(nrow(m)),sample(ncol(m))]
,因此如果您要进行很多处理,这可能是一种更快的方法。关于php - 嵌套循环和调试,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43952416/