Seguendo la logica ricorsiva consente di calcolare tutte le combinazioni, senza ripetizioni e senza la necessità di calcolare tutti loro prima. Funziona molto bene, a condizione che scegli (nx-1, ning-1) restituisca un intero. In caso contrario, calcolare le possibilità è un po 'ridicolo.
È un processo ricorsivo, quindi potrebbe richiedere molto tempo e causerà problemi di memoria quando i vettori superano un certo limite. Ma poi di nuovo, la divisione di un insieme di 14 elementi in 7 gruppi offre già 135135 possibilità uniche. Le cose sfuggono di mano molto velocemente in questo genere di cose.
La logica di pseudo-qualcosa (non sarebbe chiamarlo pseudocodice)
nb = number of groups
ning = number of elements in every group
if(nb == 2)
1. take first element, and add it to every possible
combination of ning-1 elements of x[-1]
2. make the difference for each group defined in step 1 and x
to get the related second group
3. combine the groups from step 2 with the related groups from step 1
if(nb > 2)
1. take first element, and add it to every possible
combination of ning-1 elements of x[-1]
2. to define the other groups belonging to the first groups obtained like this,
apply the algorithm on the other elements of x, but for nb-1 groups
3. combine all possible other groups from step 2
with the related first groups from step 1
Traducendo questo a R ci dà:
perm.groups <- function(x,n){
nx <- length(x)
ning <- nx/n
group1 <-
rbind(
matrix(rep(x[1],choose(nx-1,ning-1)),nrow=1),
combn(x[-1],ning-1)
)
ng <- ncol(group1)
if(n > 2){
out <- vector('list',ng)
for(i in seq_len(ng)){
other <- perm.groups(setdiff(x,group1[,i]),n=n-1)
out[[i]] <- lapply(seq_along(other),
function(j) cbind(group1[,i],other[[j]])
)
}
out <- unlist(out,recursive=FALSE)
} else {
other <- lapply(seq_len(ng),function(i)
matrix(setdiff(x,group1[,i]),ncol=1)
)
out <- lapply(seq_len(ng),
function(i) cbind(group1[,i],other[[i]])
)
}
out
}
Per vederlo funziona:
> perm.groups(1:6,3)
[[1]]
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
[[2]]
[,1] [,2] [,3]
[1,] 1 3 4
[2,] 2 5 6
[[3]]
[,1] [,2] [,3]
[1,] 1 3 4
[2,] 2 6 5
[[4]]
[,1] [,2] [,3]
[1,] 1 2 5
[2,] 3 4 6
[[5]]
[,1] [,2] [,3]
[1,] 1 2 4
[2,] 3 5 6
[[6]]
[,1] [,2] [,3]
[1,] 1 2 4
[2,] 3 6 5
[[7]]
[,1] [,2] [,3]
[1,] 1 2 5
[2,] 4 3 6
[[8]]
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[[9]]
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 6 5
[[10]]
[,1] [,2] [,3]
[1,] 1 2 4
[2,] 5 3 6
[[11]]
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 5 4 6
[[12]]
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 5 6 4
[[13]]
[,1] [,2] [,3]
[1,] 1 2 4
[2,] 6 3 5
[[14]]
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 6 4 5
[[15]]
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 6 5 4
La tua "lista" è in realtà un 'vettore'. – Roland
È '(1,2,3,4)' e '(1,2,4,3)' desiderabile? – Arun
Questo tipo di confusione tra permutazioni e combinazioni sembra essere spuntato molto recentemente. Sembra che tu voglia combinazioni, * non * permanenti, nel qual caso penso che la risposta di Juba sia appropriata. –