Home > Software design >  Create all possible numeric combinations given n values
Create all possible numeric combinations given n values

Time:09-02

I want to create a function such that, given a vector of n numbers, create all possible combinations from them (the same expand.grid() does, really).

For example, given the vector [1, 2] I want to create a function such that it outputs all possible combinations, i.e., "11", "12", "21", "21".

This is what I've come up with:

V <- trunc(runif(3, 0, 9))
FE2 <- function(V){
  C <- c()
  n <- 0
  for(i in 1:length(V)){
    for (j in 1:length(V)){
      for (k in 1:length(V)){
        C <- c(paste0(V[i], V[j], V[k]))
        n <- n   1
        print(c(paste0("Number of combination: ", n), paste0("Combination: ", C)))
      }
    }
  }
}
FE2(V)

The function does work. The problem is that for each element of the original vector, I have to add another for(). That is, if I wanted to compute all possible combinations for a vector of 10 elements, say [1, 2, ..., 10] I would have to create 10 for()-loops in my function. I wonder if there's another, more efficient way to do it, as long as it does not significantly differs from my actual solution.

CodePudding user response:

With expand.grid you then need to "collapse" the rows:

apply( expand.grid( 1:2, 1:2), 1, paste0, collapse="")
[1] "11" "21" "12" "22"

I'm not sure if I understood the goals but here's that method applied to 1:10 with 2 and then 3 instances of the vector.

> str(apply( expand.grid( 1:10, 1:10), 1, paste0, collapse="") )
 chr [1:100] "11" "21" "31" "41" "51" "61" "71" "81" "91" "101" "12" "22" "32" "42" "52" "62" "72" "82" "92" ...
> str(apply( expand.grid( 1:10, 1:10, 1:10), 1, paste0, collapse="") )
 chr [1:1000] "111" "211" "311" "411" "511" "611" "711" "811" "911" "1011" "121" "221" "321" "421" "521" "621" ...

CodePudding user response:

x <- 1:3

Use Reduce to iteratively apply the same operation

op <- function (a, b) {
  paste(rep(a, times = length(b)), rep(b, each = length(a)), sep = "-")
}

Reduce(op, rep(list(x), length(x)))
# [1] "1-1-1" "2-1-1" "3-1-1" "1-2-1" "2-2-1" "3-2-1" "1-3-1" "2-3-1" "3-3-1"
#[10] "1-1-2" "2-1-2" "3-1-2" "1-2-2" "2-2-2" "3-2-2" "1-3-2" "2-3-2" "3-3-2"
#[19] "1-1-3" "2-1-3" "3-1-3" "1-2-3" "2-2-3" "3-2-3" "1-3-3" "2-3-3" "3-3-3"

Generate permutations

library(RcppAlgos)

permuteGeneral(x, length(x), repetition = TRUE,
               FUN = function (x) paste0(x, collapse = "-"))
  • Related