# 列舉抽出且放回1-5的所有情況,一列一輪,共5^3種情況 m <- gtools::permutations(5, 3, repeats.allowed = T) # 保留左右相鄰不等的列,剩80種 ri1 <- apply(m, 1, function(x) { foo <- vector("logical", length(x) - 1) for (i in 1:(length(x) - 1)) { if (x[i] != x[i + 1]) { foo[i] <- T } } all(foo) }) m <- m[ri1, ] # 取出二個列的所有可能排列序號 ri2 <- gtools::permutations(nrow(m), 2) # 用來儲存符合題意的容器 res <- vector("list", nrow(ri2)) # 上下相鄰全不相等的情況存入容器中 for (i in 1:nrow(ri2)) { m.this <- m[ri2[i, ], ] if (all(m.this[1, ] != m.this[2, ])) { res[[i]] <- m.this } } # 去除NULL後為所求,共3380種情況 ans <- res[!sapply(res, is.null)] length(ans) print(ans[1:10])
Standard input is empty
[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