Home > Back-end >  Generate all combinations of vector with consecutive occurrences is considered as single occurrence
Generate all combinations of vector with consecutive occurrences is considered as single occurrence

Time:02-11

I want to generate vectors with all possible combinations of vector elements where a consecutive multiple occurrences of an element is considered as single occurrence of that element.

simple cases for n=2,

original<-c("a","a","a","b","b","b")
      v1<-c("b","b","b","a","a","a")

so all unique occurrences of ‘a’ swap with ‘b’ for n=3,

original<-c("a","a","a","b","b","b","c","c","c")
    ver1<-c("a","a","a","c","c","c","b","b","b")
    ver2<-c("b","b","b","a","a","a","c","c","c")
    ver3<-c("b","b","b","c","c","c","a","a","a")
    ver4<-c("c","c","c","b","b","b","a","a","a")
    ver5<-c("c","c","c","a","a","a","b","b","b")

so all unique occurrences of ‘a’ swap with ‘b’ and ‘c’, all unique occurrences of’b’ swap with’a’ and ‘c’ AND all unique occurrences of ‘c’ swap with ‘b’ and ‘a’

the cases go upto n=10,(I believe the possible vectors with different combinations are 10!) Also there can be more than single chunk of a,b,c,..

Complex case n=2

original<-c("a","a","a","b","b","b","a","a","b","b")
    ver1<-c("b","b","b","a","a","a","b","b","a","a")

But if we swap the elements correctly the complex case and simple case should not matter.

What I am trying:(for n=2)

original<-c("a","a","a","b","b","b")
ver1<-replace(original,which(original=='a'),'b')
ver1<-replace(ver1,which(original=='b'),'a')
gives ver1<-c("b","b","b","a","a","a")

but not sure how to automate this

CodePudding user response:

Using gtools::permutations. Results are each columns of the matrix. The idea is to get the permutations from unique values, and the repeat the values to match the desired group length.

f <- function(x){
  r <- rle(x)
  l <- length(r$values)
  apply(gtools::permutations(n=l, r=l, v=r$values), 1, function(x) rep(x, each = unique(r$l)))
}

output

original<-c("a","a","a","b","b","b","c","c","c")
f(original)
      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,] "a"  "a"  "b"  "b"  "c"  "c" 
 [2,] "a"  "a"  "b"  "b"  "c"  "c" 
 [3,] "a"  "a"  "b"  "b"  "c"  "c" 
 [4,] "b"  "c"  "a"  "c"  "a"  "b" 
 [5,] "b"  "c"  "a"  "c"  "a"  "b" 
 [6,] "b"  "c"  "a"  "c"  "a"  "b" 
 [7,] "c"  "b"  "c"  "a"  "b"  "a" 
 [8,] "c"  "b"  "c"  "a"  "b"  "a" 
 [9,] "c"  "b"  "c"  "a"  "b"  "a" 
  •  Tags:  
  • r
  • Related