2017-07-03 1 views
2

Comment écrire une logique pour afficher toutes les combinaisons de chiffres "0" possibles de "A" & "B" où "A" et "B" forment une paire et "B" ne peut être inséré que si nous ont déjà un "A" non apparié.Combinaison dans R

Ex:

when N=2, output should be ["AB"] 
when N=4, output should be ["AABB","ABAB"] 
when N=6, output should be ["AAABBB","AABBAB","AABABB","ABABAB","ABAABB"] 
+1

Qu'avez-vous essayé? Aussi, pouvez-vous expliquer plus? Je ne comprends pas ce que vous entendez par "forme une paire" (nombre égal d'As et de Bs?) Ou par "A non apparié". Pourquoi "ABBA", "BAAB", "BABA", "BBAA" ne sont pas inclus dans la sortie n = 4? – Gregor

+0

Totalement perdu avec la question .. – Wen

+0

Cette question est un peu floue, @mak. Voulez-vous dire que seulement un certain nombre de B peut être ajouté pour correspondre au même nombre de A déjà existant dans la chaîne? –

Répondre

3

Je crois que cela devrait vous obtenir ce que vous recherchez.

# Number of combinations 
n <- 6 

# Create dataframe of all combinations for 1 and -1 taken n number of times 
# For calculations 1 = A and -1 = B 
df <- expand.grid(rep(list(c(1,-1)), n)) 

# Select only rows that have 1 as first value 
df <- df[df[,1] == 1,] 

# Set first value for all rows as "A" 
df[,1] <- "A" 

# Set value for first calculation column as 1 
df$s <- 1 

# Loop through all columns starting with 2 
for(i in 2:n){ 
    # Get name of current column 
    cur.col <- colnames(df)[i] 

    # Get the difference between the number of 1 and -1 for current column and the running total 
    df$s2 <- apply(df[,c(cur.col,"s")], 1, sum) 

    # Remove any rows with a negative value 
    df <- df[df$s2 >= 0,] 

    # Set running total to current total 
    df$s <- df$s2 

    # Set values for current column 
    df[,i] <- sapply(as.character(df[,i]), switch, "1" = "A", "-1" = "B") 

    # Check if current column is last column 
    if(i == n){ 
    # Only select rows that have a total of zero, indicating that row has a pairs of AB values 
    df <- df[df$s2 == 0, 1:n] 
    } 
} 

# Get vector of combinations 
combos <- unname(apply(df[,1:n], 1, paste0, collapse = "")) 
+0

Merci Matt pour l'aide .. cela résout mon problème ..., ☺ – mak

+1

@mak si cela était utile, envisager [accepter comme une réponse] (https://meta.stackexchange.com/q/5234/228487). – zx8754