2016-10-27 12 views
2

ベクトルの要素(ベクトルは常に1:nの間のシーケンス)をすべてのユニークな組み合わせを得る効率的な方法を理解しようとしています。同じサイズのグループ。ベクトルの各要素は、(2つのグループのうちの1つに)1回表示する必要があります。たとえば、n = 6の場合、ベクトルは[1,2,3,4,5,6]になります。そう、値の順序が内のグループは関係ないことをベクトルを2つのグループに分けるためのすべての組み合わせR

123 | 456 
124 | 356 
125 | 346 
126 | 345 
134 | 256 
135 | 246 
136 | 245 
145 | 236 
146 | 235 
156 | 234 

注:これは、2つの等しいサイズのグループを形成するために、10のユニークな方法に分けることができ

156 | 234 

があります

651 | 342 

はまたそう、左右対称のソリューションはどちらかの問題ではありませんのでご注意:

と同じ
156 | 234 

と同じである。

234 | 156 

N = 4、3つのソリューションが存在します。 n = 6の場合、10の解が存在する。 n = 8の場合、35の解が存在する。 Rでこれらの解を得る方法を思いついたと思います。しかし、nが大きくなると少し遅くなります。ほとんどの場合、私は自分の持っているものに満足していますが、スピードやコードの品質などを向上させる方法について誰かが提案しているかどうか尋ねたいと思っています。特に、反復が多いソリューションから始めます。削除を繰り返す。これは、アルゴリズムがかなり遅くなると思う。

library(combinat) 
# Number of elements in array 
n = 6 
# Array 
dat <- 1:n 

# All possible permutations for array 
ans <- permn(dat) 
lengthAns <- length(ans) 
ansDF <- data.frame() 
# Place first permutation in final answer data frame 
ansDF <- rbind(ansDF, ans[[1]]) 

# Look at the rest of the possible permutations. Determine for each one if it is truly unique from all the previously-listed possible permutations. If it is unique from them, then add it to the final answer data frame 
for (i in 2:lengthAns){ 
    j = i 
    k = TRUE 
    while (k && j > 1){ 
    j = j-1 
    if(setequal(ans[[i]][1:(n/2)], ans[[j]][1:(n/2)])) 
     k = FALSE 
    if(setequal(ans[[i]][1:(n/2)], ans[[j]][(n/2+1):(n)])) 
     k = FALSE 
    } 
    if (k){ 
    ansDF <- rbind(ansDF, ans[[i]]) 
    } 
} 

# At this point, ansDF contains all unique possible ways to split the array into two-equally sized groups. 

答えて

2
N = 6 
x = 1:N 
x1 = combn(x, N/2) #how many ways can we take half the elements to form the 1st group 
NC = NCOL(x1) 
x2 = x1[, NC:1] # simplified way to generate the complementary groups that include values not in x1 
grp1 = t(x1[,1:(NC/2)]) # We only need half of the rows, the 2nd half containing the same set in reverse order 
grp2 = t(x2[,1:(NC/2)]) 
all.comb = cbind(grp1, grp2) 

#  [,1] [,2] [,3] [,4] [,5] [,6] 
# [1,] 1 2 3 4 5 6 
# [2,] 1 2 4 3 5 6 
# [3,] 1 2 5 3 4 6 
# [4,] 1 2 6 3 4 5 
# [5,] 1 3 4 2 5 6 
# [6,] 1 3 5 2 4 6 
# [7,] 1 3 6 2 4 5 
# [8,] 1 4 5 2 3 6 
# [9,] 1 4 6 2 3 5 
#[10,] 1 5 6 2 3 4 
関連する問題