fork download
  1. # @param input 一個list, 每個list element 都是一個vector
  2. # @return list 列出input[[1]], input[[2]], ..., input[[n]] 中所有可能的組合
  3. # ex: list(c(input[[1]][1], input[[2]][1], ..., input[[n]][1]),
  4. # ...
  5. # c(input[[1]][length(input[[1]])], ..., input[[n]][length(input[[n]])])
  6. combination <- function(input) {
  7. if (length(input) == 1) {
  8. return(lapply(input[[1]], function(a) a))
  9. }
  10. n <- length(input)
  11. temp <- combination(input[1:(n-1)])
  12. retval <- rep(temp, length(input[[n]]))
  13. index <- 1
  14. for(i in 1:length(input[[n]])) {
  15. for(j in 1:length(temp)) {
  16. retval[[index]] <- c(retval[[index]], input[[n]][i])
  17. index <- index + 1
  18. }
  19. }
  20. return(retval)
  21. }
  22.  
  23. combination(list(1:3,4:6,7:8))
Success #stdin #stdout 0.45s 22824KB
stdin
Standard input is empty
stdout
[[1]]
[1] 1 4 7

[[2]]
[1] 2 4 7

[[3]]
[1] 3 4 7

[[4]]
[1] 1 5 7

[[5]]
[1] 2 5 7

[[6]]
[1] 3 5 7

[[7]]
[1] 1 6 7

[[8]]
[1] 2 6 7

[[9]]
[1] 3 6 7

[[10]]
[1] 1 4 8

[[11]]
[1] 2 4 8

[[12]]
[1] 3 4 8

[[13]]
[1] 1 5 8

[[14]]
[1] 2 5 8

[[15]]
[1] 3 5 8

[[16]]
[1] 1 6 8

[[17]]
[1] 2 6 8

[[18]]
[1] 3 6 8