如何写入显示所有可能的“N”位 “A” &“B”,其中“A”和“B”形成一对和“B”的组合的逻辑只能插,如果我们已经有一个非配对的“A”。组合中的R
对于前:
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"]
如何写入显示所有可能的“N”位 “A” &“B”,其中“A”和“B”形成一对和“B”的组合的逻辑只能插,如果我们已经有一个非配对的“A”。组合中的R
对于前:
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"]
我相信这应该得到你所期待的。
# 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 = ""))
你试过了什么?另外,你能解释更多吗?我不明白“形成一对”(As和Bs的数量相等吗?)或什么是“不配对的A”意味着什么。为什么“ABBA”,“BAAB”,“BABA”,“BBAA”不包括在n = 4的输出中? – Gregor
完全失去了这个问题.. – Wen
这个问题有点不清楚,@mak。你的意思是只有一定数量的B可以被添加来匹配字符串中已经存在的相同数量的A? –