fork download
  1. # 列舉抽出且放回1-5的所有情況,一列一輪,共5^3種情況
  2. m <- gtools::permutations(5, 3, repeats.allowed = T)
  3.  
  4. # 保留左右相鄰不等的列,剩80種
  5. ri1 <-
  6. apply(m, 1, function(x) {
  7. foo <- vector("logical", length(x) - 1)
  8. for (i in 1:(length(x) - 1)) {
  9. if (x[i] != x[i + 1]) {
  10. foo[i] <- T
  11. }
  12. }
  13. all(foo)
  14. })
  15. m <- m[ri1, ]
  16.  
  17. # 取出二個列的所有可能排列序號
  18. ri2 <- gtools::permutations(nrow(m), 2)
  19. # 用來儲存符合題意的容器
  20. res <- vector("list", nrow(ri2))
  21. # 上下相鄰全不相等的情況存入容器中
  22. for (i in 1:nrow(ri2)) {
  23. m.this <- m[ri2[i, ], ]
  24. if (all(m.this[1, ] != m.this[2, ])) {
  25. res[[i]] <- m.this
  26. }
  27. }
  28.  
  29. # 去除NULL後為所求,共3380種情況
  30. ans <- res[!sapply(res, is.null)]
  31. length(ans)
  32. print(ans[1:10])
  33.  
Success #stdin #stdout 0.22s 188992KB
stdin
Standard input is empty
stdout
[1] 3380
[[1]]
     [,1] [,2] [,3]
[1,]    1    2    1
[2,]    2    1    2

[[2]]
     [,1] [,2] [,3]
[1,]    1    2    1
[2,]    2    1    3

[[3]]
     [,1] [,2] [,3]
[1,]    1    2    1
[2,]    2    1    4

[[4]]
     [,1] [,2] [,3]
[1,]    1    2    1
[2,]    2    1    5

[[5]]
     [,1] [,2] [,3]
[1,]    1    2    1
[2,]    2    3    2

[[6]]
     [,1] [,2] [,3]
[1,]    1    2    1
[2,]    2    3    4

[[7]]
     [,1] [,2] [,3]
[1,]    1    2    1
[2,]    2    3    5

[[8]]
     [,1] [,2] [,3]
[1,]    1    2    1
[2,]    2    4    2

[[9]]
     [,1] [,2] [,3]
[1,]    1    2    1
[2,]    2    4    3

[[10]]
     [,1] [,2] [,3]
[1,]    1    2    1
[2,]    2    4    5