ベクトルの要素(ベクトルは常に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.